<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="850"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '订单详情' : '订单详情'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
    >
      <a-form-item label="用户" name="userId">
        <div class="user-box">
          <a-avatar
            :size="30"
            :src="`${form.avatar}`"
            style="margin-right: 4px"
          >
            <template #icon>
              <UserOutlined />
            </template>
          </a-avatar>
          <div class="user-info">
            <span>{{ form.realName }}</span>
            <span class="ele-text-placeholder">{{ form.nickname }}</span>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="提现金额" name="money">
        <span class="ele-text-warning">￥{{ form.money }}</span>
      </a-form-item>
      <a-form-item label="打款方式" name="payType">
        <a-tag v-if="form.payType === 10">微信</a-tag>
        <a-tag v-if="form.payType === 20">支付宝</a-tag>
        <a-tag v-if="form.payType === 30">银行卡</a-tag>
      </a-form-item>
      <a-form-item label="账号信息" name="account">
        <div class="ele-text-warning" v-if="form.payType === 20">{{
          form.alipayName
        }}</div>
        <div class="ele-text-warning" v-if="form.payType === 20">{{
          form.alipayAccount
        }}</div>
        <div class="ele-text-warning" v-if="form.payType === 30">{{
          form.bankName
        }}</div>
        <div class="ele-text-warning" v-if="form.payType === 30">{{
          form.bankAccount
        }}</div>
        <div class="ele-text-warning" v-if="form.payType === 30">{{
          form.bankCard
        }}</div>
      </a-form-item>
      <a-form-item label="处理状态" name="applyStatus">
        <a-space direction="horizontal">
          <a-radio-group v-model:value="form.applyStatus">
            <a-radio :value="10">待审核</a-radio>
            <a-radio :value="20">审核通过</a-radio>
            <a-radio :value="30">驳回</a-radio>
            <a-radio :value="40">已打款</a-radio>
          </a-radio-group>
        </a-space>
      </a-form-item>
      <a-form-item label="驳回信息" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="这一刻想法"
          v-model:value="form.rejectReason"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { MerchantWithdraw } from '@/api/merchant/withdraw/model';
  import {
    addMerchantWithdraw,
    updateMerchantWithdraw
  } from '@/api/merchant/withdraw';
  import { FormInstance, Rule, RuleObject } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from '@/api/system/file';
  import useFormData from '@/utils/use-form-data';
  import { assignObject, messageLoading } from 'ele-admin-pro';

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: MerchantWithdraw | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const files = ref<ItemType[]>([]);
  const formRef = ref<FormInstance | null>(null);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单数据
  const { form, resetFields } = useFormData<MerchantWithdraw>({
    id: undefined,
    userId: undefined,
    avatar: '',
    nickname: '',
    money: undefined,
    payType: undefined,
    alipayName: '',
    alipayAccount: '',
    bankName: '',
    bankAccount: '',
    bankCard: '',
    applyStatus: undefined,
    rejectReason: undefined,
    comments: '',
    sortNumber: 100,
    status: 0
  });

  // /* 上传事件 */
  // const uploadHandler = (file: File) => {
  //   const item: ItemType = {
  //     file,
  //     uid: (file as any).uid,
  //     name: file.name
  //   };
  //   if (!file.type.startsWith('image')) {
  //     message.error('只能选择图片');
  //     return;
  //   }
  //   if (file.size / 1024 / 1024 > 2) {
  //     message.error('大小不能超过 2MB');
  //     return;
  //   }
  //   onUpload(item);
  // };

  // 上传文件
  // const onUpload = (item) => {
  //   const { file } = item;
  //   uploadFile(file)
  //     .then((data) => {
  //       files.value.push({
  //         uid: data.id,
  //         thumb: data.thumb,
  //         url: data.url,
  //         status: 'done'
  //       });
  //       if (data.contentType == 'video/mp4') {
  //         form.accept = 'video';
  //       }
  //       // form.image = data.thumbnail;
  //       message.success('上传成功');
  //     })
  //     .catch((e) => {
  //       message.error(e.message);
  //     });
  // };

  // 上传文件
  // const onUploadVideo = (item) => {
  //   const { file } = item;
  //   if (!file.type.startsWith('video')) {
  //     message.error('只能选择视频文件');
  //     return;
  //   }
  //   if (file.size / 1024 / 1024 > 30) {
  //     message.error('大小不能超过 30MB');
  //     return;
  //   }
  //   const hide = messageLoading({
  //     content: '上传中..',
  //     duration: 0,
  //     mask: true
  //   });
  //   uploadFile(file)
  //     .then((data) => {
  //       hide();
  //       form.video = data.url;
  //       message.success('上传成功');
  //     })
  //     .catch((e) => {
  //       message.error(e.message);
  //       hide();
  //     });
  // };

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    userId: [
      {
        required: true,
        type: 'string',
        message: '请选择会员',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: number) => {
          if (value == 0) {
            return Promise.reject('请选择会员');
          }
          return Promise.resolve();
        }
      }
    ],
    sortNumber: [
      {
        required: true,
        type: 'number',
        message: '请输入排序号',
        trigger: 'blur'
      }
    ]
  });

  // const chooseUserId = (data: MerchantWithdraw) => {
  //   form.userId = data.userId;
  //   form.nickname = data.nickname;
  // };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const dataForm = {
          ...form,
          files: JSON.stringify(files.value)
        };
        const saveOrUpdate = isUpdate.value
          ? updateMerchantWithdraw
          : addMerchantWithdraw;
        saveOrUpdate(dataForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            resetFields();
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          isUpdate.value = true;
          assignObject(form, props.data);
          // files.value = props.data.files;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .flex-sb {
    display: flex;
    justify-content: space-between;
  }
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
