<template>
  <d-modal v-model="visible" class="w-[900px] repo-setting-modal">
    <template #header>
      <gc-modal-header>
        <span class="text-G900 text-base font-bold leading-[24px]">企业认证</span>
      </gc-modal-header>
      <div class="line bg-G200"></div>
    </template>

    <d-form ref="formRef" layout="vertical" :label-align="'end'" :data="newFormData" :rules="rules">
      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="primaryKey" label="主键">
            <d-input
              placeholder="请输入主键"
              v-model="newFormData.primaryKey"
              :rules="[{ required: true, message: '请填写主键' }]"
            />
          </d-form-item>
        </d-col>
        <d-col :span="12">
          <d-form-item field="applicant" label="申请人">
            <d-input
              placeholder="请输入申请人"
              v-model="newFormData.applicant"
              :rules="[{ required: true, message: '请填写申请人' }]"
            />
          </d-form-item>
        </d-col>
      </d-row>

      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="enterpriseName" label="企业名称">
            <d-input
              placeholder="请输入企业名称"
              v-model="newFormData.enterpriseName"
              :rules="[{ required: true, message: '请填写企业名称' }]"
            />
          </d-form-item>
        </d-col>
        <d-col :span="12">
          <d-form-item field="creditCode" label="统一信用代码">
            <d-input
              placeholder="请输入统一信用代码"
              v-model="newFormData.creditCode"
              :rules="[{ required: true, message: '请填写统一信用代码' }]"
            />
          </d-form-item>
        </d-col>
      </d-row>

      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="website" label="企业官网">
            <d-input
              placeholder="请输入企业官网"
              v-model="newFormData.website"
              :rules="[{ required: true, message: '请填写企业官网' }]"
            />
          </d-form-item>
        </d-col>
        <d-col :span="12">
          <d-form-item field="industry" label="所属行业">
            <d-input
              placeholder="请输入所属行业"
              v-model="newFormData.industry"
              :rules="[{ required: true, message: '请填写所属行业' }]"
            />
          </d-form-item>
        </d-col>
      </d-row>

      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="introduction" label="企业简介">
            <d-input
              placeholder="请输入企业简介"
              v-model="newFormData.introduction"
              :rows="2"
              type="textarea"
              :rules="[{ required: true, message: '请填写企业简介' }]"
            />
          </d-form-item>
        </d-col>
      </d-row>

      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="businessLicenseUrl" label="营业执照">
            <div class="img-container" v-if="!showUpload">
              <img class="img-preview" :src="businessLicenseUrl" alt="营业执照预览" />
              <div class="delete-img" @click="handleDel">
                <d-icon name="delete" size="14px"></d-icon>
              </div>
            </div>
            <d-upload class="upload-demo-new" accept=".png,.jpg,.jpeg" :upload-options="uploadOptions" :before-upload="beforeUpload" v-if="showUpload">
              <div class="upload-trigger">
                <div><d-icon name="multi-picture" size="20px"></d-icon></div>
                <div style="margin-top: 8px;">
                  添加图片
                </div>
              </div>
            </d-upload>
          </d-form-item>
        </d-col>
      </d-row>

      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="contactEmail" label="联系人邮箱">
            <d-input
              placeholder="请输入联系人邮箱"
              v-model="newFormData.contactEmail"
              :rules="[{ required: true, message: '请填写联系人邮箱' }, { type: 'email', message: '请输入正确的邮箱格式' }]"
            />
          </d-form-item>
        </d-col>
        <d-col :span="12">
          <d-form-item field="contactName" label="联系人姓名">
            <d-input
              placeholder="请输入联系人姓名"
              v-model="newFormData.contactName"
              :rules="[{ required: true, message: '请填写联系人姓名' }]"
            />
          </d-form-item>
        </d-col>
      </d-row>

      <d-row :gutter="32" class="mb-3">
        <d-col :span="12">
          <d-form-item field="contactPhone" label="联系电话">
            <d-input
              placeholder="请输入联系电话"
              v-model="newFormData.contactPhone"
              :rules="[{ required: true, message: '请填写联系电话' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
            />
          </d-form-item>
        </d-col>
      </d-row>
    </d-form>

    <template #footer>
      <div class="flex justify-center px-[24px] pb-[24px] gap-2">
        <d-button variant="solid" @click="handleConfirm">确定</d-button>
        <d-button @click="handleCancel">取消</d-button>
      </div>
    </template>
  </d-modal>
</template>

<script setup>
import { ref, nextTick,defineEmits  } from 'vue';
import NoData from '@/components/NoData/NoData.vue';
import { Message } from 'vue-devui';
import { addEnterprise, updateEnterprise } from '@/api/organizationManage/organizationManageApi';
import { uploadImage } from '@/api/jyh';
import { useAccountStore } from '@/stores/user';

const { accountInfo } = useAccountStore();
const userName = accountInfo?.username

const visible = ref(false);
const formRef = ref(null);
const businessLicenseUrl = ref(''); // 营业执照预览URL

// 表单校验规则（全部设为必填）
const rules = ref({
  primaryKey: [{ required: true, message: '请填写主键', trigger: 'blur' }],
  applicant: [{ required: true, message: '请填写申请人', trigger: 'blur' }],
  enterpriseName: [{ required: true, message: '请填写企业名称', trigger: 'blur' }],
  creditCode: [
    { required: true, message: '请填写统一信用代码', trigger: 'blur' }
  ],
  website: [
    { required: true, message: '请填写企业官网', trigger: 'blur' }
  ],
  industry: [{ required: true, message: '请填写所属行业', trigger: 'blur' }],
  introduction: [{ required: true, message: '请填写企业简介', trigger: 'blur' }],
  businessLicenseUrl: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  contactEmail: [
    { required: true, message: '请填写联系人邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  contactName: [{ required: true, message: '请填写联系人姓名', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请填写联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
});

// 表单数据（与field保持一致）
const newFormData = ref({
  primaryKey: '',         // 主键
  applicant: '',          // 申请人
  enterpriseName: '',     // 企业名称
  creditCode: '',         // 统一信用代码
  website: '',            // 企业官网
  industry: '',           // 所属行业
  introduction: '',       // 企业简介
  businessLicenseUrl: '',    // 营业执照（存储上传后的URL或ID）
  contactEmail: '',       // 联系人邮箱
  contactName: '',        // 联系人姓名
  contactPhone: '',       // 联系电话
});

// 图片上传
const showUpload = ref(true);
const uploadOptions = ref({
  uri: 'https://run.mocky.io/v3/132b3ea3-23ea-436b-aed4-c43ef9d116f0',
});

const beforeUpload = async (file) => {
  debugger
  showUpload.value = false; // 先隐藏上传区域，显示加载状态

  try {
    // 调用上传接口
    const response = await uploadImage(file[0].file);
    if (response.data.code === 200) {
      const imageUrl = response.data.data; // 获取上传后的图片地址
      businessLicenseUrl.value = imageUrl;
      newFormData.value.businessLicenseUrl = imageUrl; // 保存到表单数据
      Message.success('图片上传成功');
    } else {
      showUpload.value = true; // 上传失败，恢复上传区域
      // Message.error(response.data.msg || '图片上传失败');
    }
  } catch (error) {
    showUpload.value = true; // 网络错误，恢复上传区域
    // Message.error('图片上传网络失败，请重试');
    console.error('图片上传异常:', error);
  }

  return false; // 阻止默认上传行为
};

const handleDel = () => {
  showUpload.value = true;
  businessLicenseUrl.value = '';
  newFormData.value.businessLicenseUrl = ''; // 清空表单数据
};

// 暴露给父组件的方法
defineExpose({
  open,
  close,
  resetForm // 新增重置表单方法
});

const qyId = ref('');
// 打开模态框（支持传入初始数据）
function open(initialData = {}) {
  debugger
  // 重置表单状态
  resetForm();
  if(initialData.id) {
    qyId.value = initialData.id
  } else {
    qyId.value = '';
  }
  // 填充初始数据（如果有）
  if (Object.keys(initialData).length) {
    Object.assign(newFormData.value, initialData);

    // 如果有营业执照数据，显示预览
    if (initialData.businessLicenseUrl) {
      showUpload.value = false;
      businessLicenseUrl.value = initialData.businessLicenseUrl;
    }
  }

  visible.value = true;
}

// 关闭模态框
function close() {
  visible.value = false;
  qyId.value = '';
}

// 重置表单
function resetForm() {
  // 清空表单数据
  newFormData.value = {
    primaryKey: '',
    applicant: '',
    enterpriseName: '',
    creditCode: '',
    website: '',
    industry: '',
    introduction: '',
    businessLicenseUrl: '',
    contactEmail: '',
    contactName: '',
    contactPhone: '',
  };

  // 重置上传状态
  showUpload.value = true;
  businessLicenseUrl.value = '';

  // 重置表单校验状态
  formRef.value?.resetFields();
}

const emits = defineEmits(['refresh'])
// 提交表单
const handleConfirm = async () => {
  formRef.value.validate(async (isValid, invalidFields) => {
    if (isValid) {
      // 构造请求参数（过滤掉空值和非必填字段）
      const requestData = {
        applicant: newFormData.value.applicant,
        userName: userName,
        enterpriseName: newFormData.value.enterpriseName,
        creditCode: newFormData.value.creditCode,
        website: newFormData.value.website || undefined, // 非必填，空值转为undefined
        industry: newFormData.value.industry,
        introduction: newFormData.value.introduction || undefined, // 非必填
        contactName: newFormData.value.contactName,
        contactEmail: newFormData.value.contactEmail || undefined, // 非必填
        contactPhone: newFormData.value.contactPhone,
        businessLicenseUrl: newFormData.value.businessLicenseUrl,
      };
      if(qyId.value) {
        try {
          // 调用编辑接口
          const response = await updateEnterprise({
            id: qyId.value,
            auditStatus: 0,
            ...requestData
          });
          if (response.data.code === 200) {
            Message.success('企业认证编辑成功');
            close(); // 关闭模态框
            // 通知父组件刷新列表（可通过事件实现）
            emits('refresh');
          } else {
            // Message.error(response.data.msg || '编辑失败，请重试');
          }
        } catch (error) {
          // Message.error('网络请求失败，请检查网络连接');
          console.error('编辑接口异常:', error);
        }
      } else {
        try {
          // 调用新增接口
          const response = await addEnterprise(requestData);
          if (response.data.code === 200) {
            Message.success('企业认证添加成功');
            close(); // 关闭模态框
            // 通知父组件刷新列表（可通过事件实现）
            emits('refresh');
          } else {
            // Message.error(response.data.msg || '添加失败，请重试');
          }
        } catch (error) {
          // Message.error('网络请求失败，请检查网络连接');
          console.error('新增接口异常:', error);
        }
      }
    } else {
      // 显示第一个错误字段的提示
      const firstError = Object.values(invalidFields)[0]?.[0]?.message;
      Message.error(firstError || '请完善表单信息');
    }
  });
};

function handleCancel() {
  close();
}
</script>

<style lang="scss" scoped>
.repo-setting-modal {
  width: 600px;
}

.card-key {
  display: inline-block;
  color: #666;
  margin-right: 8px;
}

.card-val {
  color: #333;
}

.upload-demo-new .upload-trigger {
  background-color: #f2f2f2;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.upload-demo-new .upload-trigger .link {
  color: #5e7ce0;
}

.img-container {
  position: relative;
  width: 100px;
  height: 100px;
}

.img-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.delete-img {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 16px;
  height: 16px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  color: white;
}
</style>
