<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="900"
    :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: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <!-- 申请人信息 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">申请人信息</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="用户ID" name="userId">
            <a-input-number
              :min="1"
              placeholder="请输入用户ID"
              :disabled="isUpdate"
              v-model:value="form.userId"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="真实姓名" name="realName">
            <a-input
              placeholder="请输入真实姓名"
              v-model:value="form.realName"
              :disabled="isUpdate"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="手机号码" name="mobile">
            <a-input
              placeholder="请输入手机号码"
              :disabled="isUpdate"
              v-model:value="form.mobile"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="推荐人ID" name="refereeId">
            <a-input-number
              :min="1"
              placeholder="请输入推荐人用户ID"
              :disabled="isUpdate"
              v-model:value="form.refereeId"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 审核信息 -->
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600;">审核信息</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="审核状态" name="applyStatus">
            <a-select v-model:value="form.applyStatus" placeholder="请选择审核状态" @change="handleStatusChange">
              <a-select-option :value="10">
                <a-tag color="processing">待审核</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-option :value="30">
                <a-tag color="error">审核驳回</a-tag>
                <span style="margin-left: 8px;">申请驳回</span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
<!--        <a-col :span="12">-->
<!--          <a-form-item label="审核时间" name="auditTime" v-if="form.applyStatus === 20 || form.applyStatus === 30">-->
<!--            <a-date-picker-->
<!--              v-model:value="form.auditTime"-->
<!--              show-time-->
<!--              format="YYYY-MM-DD HH:mm:ss"-->
<!--              placeholder="请选择审核时间"-->
<!--              style="width: 100%"-->
<!--            />-->
<!--          </a-form-item>-->
<!--        </a-col>-->
      </a-row>

      <a-row :gutter="16" v-if="form.applyStatus === 30">
        <a-col :span="24">
          <a-form-item label="驳回原因" name="rejectReason">
            <a-textarea
              v-model:value="form.rejectReason"
              placeholder="请输入驳回原因"
              style="width: 100%"
              :rows="3"
              :maxlength="200"
              show-count
            />
          </a-form-item>
        </a-col>
      </a-row>
    </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, uuid } from 'ele-admin-pro';
  import { addShopDealerApply, updateShopDealerApply } from '@/api/shop/shopDealerApply';
  import { ShopDealerApply } from '@/api/shop/shopDealerApply/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  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 images = ref<ItemType[]>([]);

  // 表单数据
  const form = reactive<ShopDealerApply>({
    applyId: undefined,
    userId: undefined,
    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({
    userId: [
      {
        required: true,
        message: '请输入用户ID',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        message: '请输入真实姓名',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 20,
        message: '姓名长度应在2-20个字符之间',
        trigger: 'blur'
      }
    ],
    mobile: [
      {
        required: true,
        message: '请输入手机号码',
        trigger: 'blur'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    applyType: [
      {
        required: true,
        message: '请选择申请方式',
        trigger: 'change'
      }
    ],
    applyStatus: [
      {
        required: true,
        message: '请选择审核状态',
        trigger: 'change'
      }
    ],
    rejectReason: [
      {
        required: true,
        message: '驳回时必须填写驳回原因',
        trigger: 'blur'
      }
    ],
    auditTime: [
      {
        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>
