<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="600"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑企业' : '新增企业'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="企业名称" name="dealerName">
        <a-input placeholder="请输入企业名称" v-model:value="form.dealerName" />
      </a-form-item>
      <a-form-item label="入市状态" name="applyStatus">
        <a-select
          v-model:value="form.applyStatus"
          placeholder="请选择入市状态"
          @change="handleStatusChange"
        >
          <a-select-option :value="10">
            <a-tag>未入市</a-tag>
            <span style="margin-left: 8px">未入市</span>
          </a-select-option>
          <a-select-option :value="20">
            <a-tag color="success">已入市</a-tag>
            <span style="margin-left: 8px">已入市</span>
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { assignObject } from 'ele-admin-pro';
  import {
    addShopDealerApply,
    updateShopDealerApply
  } from '@/api/shop/shopDealerApply';
  import { ShopDealerApply } from '@/api/shop/shopDealerApply/model';
  import { FormInstance } from 'ant-design-vue/es/form';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ShopDealerApply | null;
  }>();

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);

  // 表单数据
  const form = reactive<ShopDealerApply>({
    applyId: undefined,
    type: 3,
    userId: undefined,
    dealerName: '',
    realName: '',
    mobile: '',
    refereeId: undefined,
    applyType: 10,
    applyTime: undefined,
    applyStatus: 10,
    auditTime: undefined,
    rejectReason: '',
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  });

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

  // 表单验证规则
  const rules = reactive({
    dealerName: [
      {
        required: true,
        message: '请输入经销商名称',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        message: '请输入企业名称',
        trigger: 'blur'
      }
    ],
    applyStatus: [
      {
        required: true,
        message: '请选择审核状态',
        trigger: 'change'
      }
    ]
  });

  const { resetFields } = useForm(form, rules);

  /* 处理审核状态变化 */
  const handleStatusChange = (value: number) => {
    // 当状态改为审核通过或驳回时，自动设置审核时间为当前时间
    if ((value === 20 || value === 30) && !form.auditTime) {
      form.auditTime = dayjs();
    }
    // 当状态改为待审核时，清空审核时间和驳回原因
    if (value === 10) {
      form.auditTime = undefined;
      form.rejectReason = '';
    }
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }

    // 动态验证规则
    const validateFields: string[] = [
      'userId',
      'realName',
      'mobile',
      'applyStatus'
    ];

    // 如果是驳回状态，需要验证驳回原因
    if (form.applyStatus === 30) {
      validateFields.push('rejectReason');
    }

    // 如果是审核通过或驳回状态，需要验证审核时间
    if (form.applyStatus === 20 || form.applyStatus === 30) {
      validateFields.push('auditTime');
    }

    formRef.value
      .validate(validateFields)
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };

        // 处理时间字段转换 - 转换为ISO字符串格式
        if (formData.applyTime) {
          if (dayjs.isDayjs(formData.applyTime)) {
            formData.applyTime = formData.applyTime.format(
              'YYYY-MM-DD HH:mm:ss'
            );
          } else if (typeof formData.applyTime === 'number') {
            formData.applyTime = dayjs(formData.applyTime).format(
              'YYYY-MM-DD HH:mm:ss'
            );
          }
        }

        if (formData.auditTime) {
          if (dayjs.isDayjs(formData.auditTime)) {
            formData.auditTime = formData.auditTime.format(
              'YYYY-MM-DD HH:mm:ss'
            );
          } else if (typeof formData.auditTime === 'number') {
            formData.auditTime = dayjs(formData.auditTime).format(
              'YYYY-MM-DD HH:mm:ss'
            );
          }
        }

        // 当审核状态为通过或驳回时，确保有审核时间
        if (
          (formData.applyStatus === 20 || formData.applyStatus === 30) &&
          !formData.auditTime
        ) {
          formData.auditTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        }

        // 当状态为待审核时，清空审核时间
        if (formData.applyStatus === 10) {
          formData.auditTime = undefined;
        }

        const saveOrUpdate = isUpdate.value
          ? updateShopDealerApply
          : addShopDealerApply;
        saveOrUpdate(formData)
          .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) {
          assignObject(form, props.data);
          // 处理时间字段 - 确保转换为dayjs对象
          if (props.data.applyTime) {
            form.applyTime = dayjs(props.data.applyTime);
          }
          if (props.data.auditTime) {
            form.auditTime = dayjs(props.data.auditTime);
          }
          isUpdate.value = true;
        } else {
          // 重置为默认值
          Object.assign(form, {
            applyId: undefined,
            userId: undefined,
            realName: '',
            mobile: '',
            refereeId: undefined,
            applyType: 10,
            applyTime: dayjs(),
            applyStatus: 10,
            auditTime: undefined,
            rejectReason: '',
            tenantId: undefined,
            createTime: undefined,
            updateTime: undefined
          });
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
  :deep(.ant-divider-horizontal.ant-divider-with-text-left) {
    margin: 24px 0 16px 0;

    .ant-divider-inner-text {
      padding: 0 16px 0 0;
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 16px;
  }

  :deep(.ant-radio) {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .ant-radio-inner {
      margin-right: 8px;
    }
  }

  :deep(.ant-select-selection-item) {
    display: flex;
    align-items: center;
  }
</style>
