<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';

import {
  computed,
  defineEmits,
  defineExpose,
  nextTick,
  reactive,
  ref,
} from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { updateCoupon2UserInfoApi } from '#/api/coupon/coupon2';
import { getDictListApi } from '#/api/dict';
import { getAttachmentListApi } from '#/api/file';
import UploadFile from '#/components/upload-file/index.vue';

const emit = defineEmits(['finish']);

const formRef = ref<FormInstance>();
const formData = reactive({
  coupon2sid: '', // 优惠券ID
  userstype: '个人' as '个人' | '企业',
  usersname: '',
  idNumber: '',
  phone: '',
  idCardIds: [] as any[],
  idCardFiles: [] as any[],
  businessLicenseIds: [] as any[],
  businessLicenseFiles: [] as any[],
  buyerPhotoIds: [] as any[],
  buyerPhotoFiles: [] as any[],
});

const submitLoading = ref(false);

const usersnameLabel = computed(() =>
  formData.userstype === '个人' ? '姓名' : '企业名称',
);
const idNumberLabel = computed(() =>
  formData.userstype === '个人' ? '身份证号' : '统一社会信用代码',
);
const phoneNumberRule = {
  trigger: 'blur',
  validator: (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error('请输入手机号'));
    } else if (/^1[3-9]\d{9}$/.test(value)) {
      callback();
    } else {
      callback(new Error('请输入正确的手机号格式'));
    }
  },
};

// 表单验证规则
const rules = reactive<FormRules>({
  userstype: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
  usersname: [
    {
      required: true,
      message: `请输入${usersnameLabel.value}`,
      trigger: 'blur',
    },
  ],
  idNumber: [
    {
      required: true,
      message: `请输入${idNumberLabel.value}`,
      trigger: 'blur',
    },
  ],
  idCardIds: [
    {
      required: true,
      validator: (_rule, value, callback) => {
        if (formData.userstype === '个人' && (!value || value.length === 0)) {
          callback(new Error('请上传身份证正面照片'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  businessLicenseIds: [
    {
      required: true,
      validator: (_rule, value, callback) => {
        if (formData.userstype === '企业' && (!value || value.length === 0)) {
          callback(new Error('请上传营业执照照片'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  phone: [phoneNumberRule],
});

// 获取文件前缀地址
const getFilePrefix = async () => {
  try {
    const filePrefixData = await getDictListApi({
      groupname: 'fileheadurl',
      pageindex: 1,
      rows: 999,
    });

    if (filePrefixData.Data.length > 0) {
      return filePrefixData.Data[0].substance;
    }
  } catch (error) {
    console.error('获取文件前缀失败:', error);
  }
  return '';
};

// 获取身份证附件
const getCertificateAttachments = async (
  coupon2sid: string,
  filePrefix: string,
  userstype: string,
) => {
  try {
    const certificateData = await getAttachmentListApi({
      attlsh: coupon2sid,
      attmodel: 'coupon_identity',
      pageindex: 1,
      rows: 10,
    });

    if (certificateData.Data.length > 0) {
      const attachments = certificateData.Data.map((item: any) => ({
        id: item.attid,
        attId: item.attid,
        name: item.attorginname || `${item.attname}.${item.atttype}`,
        url: `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`,
        uid: `existing_${item.attid}`,
        status: 'success',
        percentage: 100, // 确保已存在的文件进度为100
      }));

      if (userstype === '个人') {
        formData.idCardIds = attachments;
        formData.idCardFiles = attachments;
      } else {
        formData.businessLicenseIds = attachments;
        formData.businessLicenseFiles = attachments;
      }
    }
  } catch (error) {
    console.error('获取身份证附件失败:', error);
  }
};

// 获取购机者照片附件
const getBuyerPhotoAttachments = async (
  coupon2sid: string,
  filePrefix: string,
) => {
  try {
    const buyerPhotoData = await getAttachmentListApi({
      attlsh: coupon2sid,
      attmodel: 'coupon_buyer',
      pageindex: 1,
      rows: 10,
    });

    if (buyerPhotoData.Data.length > 0) {
      const attachments = buyerPhotoData.Data.map((item: any) => ({
        id: item.attid,
        attId: item.attid,
        name: item.attorginname || `${item.attname}.${item.atttype}`,
        url: `${filePrefix}${item.attpath}${item.attname}.${item.atttype}`,
        uid: `existing_${item.attid}`,
        status: 'success',
        percentage: 100, // 确保已存在的文件进度为100
      }));

      formData.buyerPhotoIds = attachments;
      formData.buyerPhotoFiles = attachments;
    }
  } catch (error) {
    console.error('获取购机者照片失败:', error);
  }
};

// 用户类型切换，重置表单
function handleUserTypeChange() {
  formData.usersname = '';
  formData.idNumber = '';
  formData.idCardIds = [];
  formData.idCardFiles = [];
  formData.businessLicenseIds = [];
  formData.businessLicenseFiles = [];
  formData.buyerPhotoIds = [];
  formData.buyerPhotoFiles = [];
  formRef.value?.clearValidate();
}

// 确认提交
async function handleSubmit(): Promise<boolean> {
  if (!formRef.value) return false;

  try {
    // 验证表单
    const valid = await formRef.value.validate();
    if (!valid) {
      return false;
    }

    // 验证证件照片上传
    const hasUploadedFiles =
      formData.userstype === '个人'
        ? formData.idCardIds.length > 0
        : formData.businessLicenseIds.length > 0;

    if (!hasUploadedFiles) {
      ElMessage.error(
        `请上传${formData.userstype === '个人' ? '身份证照片' : '营业执照照片'}`,
      );
      return false;
    }

    submitLoading.value = true;

    try {
      // 准备提交参数
      const submitParams: any = {
        coupon2sid: formData.coupon2sid, // 优惠券ID
        userstype: formData.userstype, // 用户类型
        usersname: formData.usersname, // 姓名或企业名称
        coupon2phone: formData.phone, // 手机号（参考uniapp参数名）
      };

      // 根据用户类型添加证件号
      if (formData.userstype === '个人') {
        submitParams.usersidcardnumber = formData.idNumber; // 身份证号
      } else {
        submitParams.usersshtyxydm = formData.idNumber; // 统一社会信用代码
      }

      // 处理文件ID
      const fileIds: string[] = [];

      // 添加身份证/营业执照文件ID
      if (formData.userstype === '个人' && formData.idCardIds.length > 0) {
        fileIds.push(...formData.idCardIds.map((item) => item.id));
      } else if (
        formData.userstype === '企业' &&
        formData.businessLicenseIds.length > 0
      ) {
        fileIds.push(...formData.businessLicenseIds.map((item) => item.id));
      }

      // 添加购机者照片文件ID（可选）
      if (formData.buyerPhotoIds.length > 0) {
        fileIds.push(...formData.buyerPhotoIds.map((item) => item.id));
      }

      // 设置文件ID参数
      if (fileIds.length > 0) {
        submitParams.filesid = fileIds.filter(Boolean).join(',');
      }

      // 调用更新购机者信息API
      await updateCoupon2UserInfoApi(submitParams);

      ElMessage.success('购机者信息修改成功！系统将重新审核您的优惠券。');

      return true;
    } catch (error) {
      console.error('提交修改失败:', error);
      ElMessage.error('提交失败，请稍后重试');
      return false;
    }
  } catch (error) {
    console.error('表单验证失败或提交出错：', error);
    ElMessage.error('请检查表单填写是否正确');
    return false;
  } finally {
    submitLoading.value = false;
  }
}

const [Modal, modalApi] = useVbenModal({
  class: 'w-[800px]',
  title: '修改购机者信息',
  showCancelButton: true,
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  async onConfirm() {
    const success = await handleSubmit();
    if (success) {
      modalApi.close();
      emit('finish');
    }
  },
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const modalData = modalApi.getData() as {
        coupon2sid?: string;
        usersidcardnumber?: string;
        usersname?: string;
        usersphone?: string;
        usersshtyxydm?: string;
        userstype?: string;
      };

      // 填充表单数据
      formData.coupon2sid = modalData?.coupon2sid || '';
      formData.userstype = (modalData?.userstype as '个人' | '企业') || '个人';
      formData.usersname = modalData?.usersname || '';
      formData.idNumber =
        modalData?.userstype === '个人'
          ? modalData?.usersidcardnumber || ''
          : modalData?.usersshtyxydm || '';
      formData.phone = modalData?.usersphone || '';

      // 首先重置文件上传数据
      formData.idCardIds = [];
      formData.idCardFiles = [];
      formData.businessLicenseIds = [];
      formData.businessLicenseFiles = [];
      formData.buyerPhotoIds = [];
      formData.buyerPhotoFiles = [];

      formRef.value?.clearValidate();
      submitLoading.value = false;

      // 获取现有附件
      if (modalData?.coupon2sid) {
        try {
          const filePrefix = await getFilePrefix();
          const userstype = modalData?.userstype || '个人';

          // 并行获取身份证和购机者照片附件
          await Promise.allSettled([
            getCertificateAttachments(
              modalData.coupon2sid,
              filePrefix,
              userstype,
            ),
            getBuyerPhotoAttachments(modalData.coupon2sid, filePrefix),
          ]);

          // 使用 nextTick 确保数据设置完成后再触发组件更新
          await nextTick();
        } catch (error) {
          console.error('获取附件失败:', error);
        }
      }
    } else {
      // 关闭时清理数据
      formData.coupon2sid = '';
      formData.userstype = '个人';
      formData.usersname = '';
      formData.idNumber = '';
      formData.phone = '';
      formData.idCardIds = [];
      formData.idCardFiles = [];
      formData.businessLicenseIds = [];
      formData.businessLicenseFiles = [];
      formData.buyerPhotoIds = [];
      formData.buyerPhotoFiles = [];
    }
  },
});

// 打开修改购机者信息弹窗的方法
function openEditBuyerInfoModal(data: {
  coupon2sid: string;
  usersidcardnumber?: string;
  usersname?: string;
  usersphone?: string;
  usersshtyxydm?: string;
  userstype?: string;
}) {
  modalApi.setData(data);
  modalApi.open();
}

defineExpose({
  openEditBuyerInfoModal,
});
</script>

<template>
  <Modal>
    <div class="p-4">
      <div
        class="rounded-md border border-gray-200 bg-white px-4 py-4 shadow-sm"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="140px"
        >
          <el-form-item label="用户类型" prop="userstype">
            <el-radio-group
              v-model="formData.userstype"
              @change="handleUserTypeChange"
            >
              <el-radio value="个人">个人</el-radio>
              <el-radio value="企业">企业</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="usersnameLabel" prop="usersname">
            <el-input
              v-model="formData.usersname"
              :placeholder="`请输入${usersnameLabel}`"
              clearable
            />
          </el-form-item>

          <el-form-item :label="idNumberLabel" prop="idNumber">
            <el-input
              v-model="formData.idNumber"
              :placeholder="`请输入${idNumberLabel}`"
              clearable
            />
          </el-form-item>

          <el-form-item
            :label="formData.userstype === '个人' ? '身份证正面' : '营业执照'"
            :prop="
              formData.userstype === '个人' ? 'idCardIds' : 'businessLicenseIds'
            "
          >
            <UploadFile
              v-if="formData.userstype === '个人'"
              v-model="formData.idCardFiles"
              v-model:file-ids="formData.idCardIds"
              attmodel="coupon_identity"
              :limit="1"
              list-type="picture-card"
              tips="请上传身份证正面照片"
            />
            <UploadFile
              v-else
              v-model="formData.businessLicenseFiles"
              v-model:file-ids="formData.businessLicenseIds"
              attmodel="coupon_identity"
              :limit="1"
              list-type="picture-card"
              tips="请上传营业执照"
            />
          </el-form-item>

          <el-form-item label="购机者照片" prop="buyerPhotoIds">
            <UploadFile
              v-model="formData.buyerPhotoFiles"
              v-model:file-ids="formData.buyerPhotoIds"
              attmodel="coupon_buyer"
              :limit="1"
              list-type="picture-card"
              tips="请上传购机者照片"
            />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号码"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Modal>
</template>

<style lang="scss" scoped>
.rules-text p {
  margin-bottom: 0.25rem;
}
</style>
