<!-- 用户编辑弹窗 -->
<template>
  <a-drawer
    :width="600"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    :footer-style="{ textAlign: 'right' }"
    @update:visible="updateVisible"
    :maskClosable="isUpdate"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
      :model="form"
      :rules="rules"
    >
      <a-form-item label="提现金额" name="money">
        <a-input-number
          allow-clear
          style="width: 100%"
          :placeholder="`可提现金额：￥3000.00`"
          v-model:value="form.money"
        />
      </a-form-item>
      <a-form-item label="收款方式" name="payType">
        <DictSelect
          dict-code="withdrawType"
          v-model:value="form.payType"
          placeholder="选择收款方式"
        />
      </a-form-item>
      <!--      <a-form-item-->
      <!--        label="开户行名称"-->
      <!--        name="bankName"-->
      <!--        v-if="form.payType === '30'"-->
      <!--      >-->
      <!--        <a-input-->
      <!--          allow-clear-->
      <!--          :placeholder="`请选择开户的银行名称`"-->
      <!--          v-model:value="merchant.bankName"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <!--      <a-form-item-->
      <!--        label="银行开户名"-->
      <!--        name="bankAccount"-->
      <!--        v-if="form.payType === '30'"-->
      <!--      >-->
      <!--        <a-input-->
      <!--          allow-clear-->
      <!--          :placeholder="`请填写银行卡姓名`"-->
      <!--          v-model:value="merchant.bankAccount"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <!--      <a-form-item-->
      <!--        label="银行卡号"-->
      <!--        name="bankCard"-->
      <!--        v-if="form.payType === '30'"-->
      <!--      >-->
      <!--        <a-input-->
      <!--          allow-clear-->
      <!--          :placeholder="`请填写银行卡号`"-->
      <!--          v-model:value="merchant.bankCard"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入备注"
          v-model:value="form.comments"
        />
      </a-form-item>
      <a-form-item v-role="'superAdmin'" label="处理状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">未处理</a-radio>
          <a-radio :value="1">已处理</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="save">保存</a-button>
      </a-space>
    </template>
  </a-drawer>
</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 { FILE_SERVER, FILE_THUMBNAIL } from '@/config/setting';
  import useFormData from '@/utils/use-form-data';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import DictSelect from '@/components/DictSelect/index.vue';
  import dayjs, { Dayjs } from 'dayjs';
  import { createCode, createOrderNo } from "@/utils/common";
  import { Merchant } from '@/api/merchant/model';
  // import MultiSpec from './MultiSpec.vue';

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: MerchantWithdraw | null;
    merchant?: Merchant[];
  }>();
  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const disabled = ref(false);
  // 选择日期
  const batteryDeliveryTime = ref<Dayjs>();
  const ctiveTime = ref<Dayjs>();

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const images = ref<ItemType[]>([]);

  const formRef = ref<FormInstance | null>(null);
  // 选项卡位置
  // const activeKey = ref('1');
  // 编辑器内容，双向绑定
  const content = ref<any>('');
  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<MerchantWithdraw>({
    id: undefined,
    withdrawCode: `W${createCode()}`,
    money: undefined,
    payType: '30',
    bankName: undefined,
    bankAccount: undefined,
    bankCard: undefined,
    comments: '',
    applyStatus: undefined,
    sortNumber: 100,
    status: 0,
    merchantCode: undefined
  });

  /* 上传事件 */
  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) => {
        images.value.push({
          uid: data.id,
          url: FILE_THUMBNAIL + data.path,
          status: 'done'
        });
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    money: [
      {
        required: true,
        message: '请输入提现金额',
        type: 'number',
        trigger: 'blur'
      }
    ],
    payType: [
      {
        required: true,
        message: '请选择收款方式',
        type: 'string',
        trigger: 'blur'
      }
    ],
    status: [
      {
        required: true,
        type: 'number',
        message: '请选择设备状态',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        type: 'number',
        message: '请输入排序号',
        trigger: 'blur'
      }
    ],
    // images: [
    //   {
    //     required: true,
    //     type: 'string',
    //     message: '请选择设备图片',
    //     trigger: 'blur',
    //     validator: async (_rule: RuleObject, value: string) => {
    //       if (images.value.length == 0) {
    //         return Promise.reject('请上传设备图片');
    //       }
    //       return Promise.resolve();
    //     }
    //   }
    // ],
    content: [
      {
        required: true,
        type: 'string',
        message: '请输入文章内容',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (content.value == '') {
            return Promise.reject('请输入文字内容');
          }
          return Promise.resolve();
        }
      }
    ]
  });

  /* 控制放店开关 */
  const editStatus = () => {
    if (form.status == 0) {
      form.status = 1;
    } else {
      form.status = 0;
    }
    updateMerchantWithdraw(form)
      .then(() => {
        message.success('操作成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const onClose = () => {
    updateVisible(false);
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        // 获取第一张图片作为封面图
        // images.value.map((d, i) => {
        //   if (i === 0) {
        //     form.image = d.url;
        //   }
        // });
        // 判断可提现金额是否足够
        if (props?.merchant?.money < form.money) {
          message.error('可提现金额不足！');
          return;
        }
        const equipmentFaultForm = {
          ...form,
          files: JSON.stringify(images.value),
          content: content.value,
          batteryDeliveryTime: batteryDeliveryTime.value?.format(
            'YYYY-MM-DD HH:mm:ss'
          ),
          ctiveTime: ctiveTime.value?.format('YYYY-MM-DD HH:mm:ss')
        };
        const saveOrUpdate = isUpdate.value
          ? updateMerchantWithdraw
          : addMerchantWithdraw;
        saveOrUpdate(equipmentFaultForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignFields({
            ...props.data
          });
          if (props.data.batteryDeliveryTime) {
            batteryDeliveryTime.value = dayjs(
              props.data.batteryDeliveryTime,
              'YYYY-MM-DD'
            );
            ctiveTime.value = dayjs(props.data.ctiveTime, 'YYYY-MM-DD');
          } else {
            batteryDeliveryTime.value = undefined;
            ctiveTime.value = undefined;
          }
          // images.value = JSON.parse(String(props.data.files));
          content.value = props.data.content;
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
</style>
