<template>
  <BasicModal v-bind="$attrs" destroyOnClose @register="registerModal" showFooter :title="getTitle" width="40%" @ok="handleSubmit" @cancel="handleCancel" :showOkBtn="!isDisable">
    <a-form ref="formRef" class="formViewStyle" :model="formState" :rules="rules" v-bind="{labelCol: { span: 8 },wrapperCol: { span: 16 },}">
      <a-row>
        <a-col :span="12">
          <a-form-item label="证书名称" name="docTypeCode" :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }">
            <a-select v-model:value="formState.docTypeCode" placeholder="请选择证书名称" :disabled="isDisable" style="width: 100%" allow-clear>
              <a-select-option v-for="item in optionList" :key="item.code" :value="item.code">
                  {{ item.fullName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="资质证书编号" name="docNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }">
            <a-input  v-model:value="formState.docNo" placeholder="请输入资质证书编号" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="有效期开始" name="dateFrom" :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }">
            <a-date-picker v-model:value="formState.dateFrom" format="YYYY-MM-DD" :disabled="isDisable" :disabled-date="disabledDateStart" style="width: 100%" placeholder="请选择有效期开始" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="有效期结束" name="dateTo" :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }">
            <a-date-picker v-model:value="formState.dateTo" format="YYYY-MM-DD" :disabled="isDisable" :disabled-date="disabledDateEnd" style="width: 100%" placeholder="请选择有效期结束" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="note" :label-col="{ span: 4 }" :wrapper-col="{ span: 24 }">
            <a-textarea  v-model:value="formState.note"  placeholder="请输入备注，最多50字" :disabled="isDisable" :maxlength="50"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="上传附件" name="fileList" :label-col="{ span: 4 }" :wrapper-col="{ span: 24 }">
            <div style="color: #ccc; font-size: 12px">{{ fileTip }}</div>
            <Upload :disabled="isDisable" v-model:value="formState.filePath" v-model:tableName="tableName" v-model:columnName="columnName" 
            :multiple="true" @change="changeUplod" :dataDelete="true" :file-list="formState.fileList" :maxSize="200" :accept="accept"></Upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </BasicModal>
</template>

<script setup lang="ts">
import {  ref, onMounted, computed, unref,reactive } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { Form, message } from 'ant-design-vue';
import { useI18n } from '/@/hooks/web/useI18n';
import type { Rule } from 'ant-design-vue/es/form';
import { useMessage } from '/@/hooks/web/useMessage';
import { getDocCpList } from '/@/api/sales/Customer';
import type { FormInstance } from 'ant-design-vue';
import dayjs from 'dayjs';
import Upload from '/@/components/Form/src/components/Upload.vue';

const tableName = 'Customer'
const columnName = 'fileList'
const { t } = useI18n(); 
const isUpdate = ref(true);
const isDisable = ref(false);
let optionList = reactive([])
const uploadRef = ref()
const fileTip = '支持格式.rar .zip .doc .docx .pdf ，单个文件不能超过20MB';
const accept ='.rar,.zip, .doc, .docx, .pdf, .RAR, .ZIP, .DOC, .DOCX, .PDF'
const formRef = ref()
const { notification } = useMessage();
const emit = defineEmits(['success','register']);
const getTitle = computed(() => (!unref(isUpdate) ? t('新增证书') : t('编辑证书')));
let formState = reactive({
  docTypeCode: '',
  fileList: [],
  filePath: ''
});
const list = ref()
const rules = {
  docTypeCode: [{ required: true, message: "该项为必填项", trigger: 'change' }],
};
const curData = ref()
   
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  curData.value = ''
  formState.filePath = ''
  getOption()
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  isDisable.value = data?.btnType == 'view' ? true : false 
  list.value = data.list
  if (unref(isUpdate)) {
    let dateFrom = data.record?.dateFrom ? dayjs(data.record?.dateFrom) : null
    let dateTo = data.record?.dateTo ? dayjs(data.record?.dateTo) : null
    Object.assign(formState, {...data.record,dateFrom, dateTo})
    let json = JSON.parse(JSON.stringify(data.record))
    formState.filePath = (json?.fileList||[])[0]?.tableId
    curData.value = json?.docTypeCode
    }
  });

  onMounted(() => {
    getOption()
  });
  const disabledDateStart = (startValue) => {
    const endValue = formState.dateTo;
    if (!startValue || !endValue) {
      return false
    }
    return startValue.valueOf() >= endValue.valueOf();
  }
    const disabledDateEnd = (endValue) => {
      const startValue = formState.dateFrom;
    if (!endValue || !startValue) {
      return false
    }
    return endValue.valueOf() <= startValue.valueOf();
  }
  function changeUplod (val) {
    formState.fileList = val
    console.log(val, 532, )
  }
  async function getOption() {
    optionList = await getDocCpList({'valid': 'Y'})
  }
  const handleCancel = () => {
    formRef.value.resetFields();
  }
  const handleSubmit = async () => {
    try {
      await formRef.value.validate();
      // 验证通过，提交表单
      let obj = {
        ...formState,
        dateFrom: formState.dateFrom ? dayjs(formState.dateFrom).format('YYYY-MM-DD') : '',
        dateTo: formState.dateTo ? dayjs(formState.dateTo).format('YYYY-MM-DD') : '',
        fileList: formState.fileList || []
      }
      let idx =list.value.findIndex(v => v.docTypeCode == obj.docTypeCode)
      if (idx > -1 && formState.docTypeCode !=curData.value) {
        message.warn('证书已存在')
        formRef.value.resetFields();
        closeModal();
        return
      }
      emit('success', obj);
      notification.success({
        message: t('操作'),
        description:!unref(isUpdate)? t('新增成功') : t('编辑成功')
      }); //提示消息
      formRef.value.resetFields();
      closeModal();
    } catch (error) {
      console.log('验证失败:', error);
    }
  };
  </script>