<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="40%" @visibleChange="handleBack">
    <BasicForm @register="registerForm">
      <template #uploadDk="{ model }">
        <a-upload v-model:file-list="fileList" accept=".xls,.xlsx" name="file" :maxCount="1" action="/soil/zcgl/gplxz/importExcel" :headers="headers" @change="handleChange">
          <a-button>
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../Gplxz.data';
  import { saveOrUpdate } from '../Gplxz.api';
  import { message } from 'ant-design-vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { getToken } from '/@/utils/auth';
  import { uploadMyFile, uploadUrl } from '/@/api/common/api';

  const handleChange = (info) => {
    console.log(info);
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      if (info.file.response.code==200 && info.file.response?.result.length > 0) {
        const formData = new FormData();
        formData.append('file', info.file.originFileObj);
        formData.append('biz', 'temp');
        uploadMyFile(uploadUrl, formData).then((res: any) => {
          console.log('uploadMyFile', res);
          if (res && res.data) {
            message.success(`${info.file.name} 上传成功`);
            setFieldsValue({
              ...{
                  dksl:''+info.file.response.result.length,
                  bz:JSON.stringify(info.file.response.result),
                  dkbmFile:res.data.message,
              }
            })
          }
        });
      } else {
        fileList.value = [];
        message.error(`${info.file.response.message || '文件内无符合要求地块信息，请重新上传'}`);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };

  const fileList = ref([]);
  const headers = {
    'X-Access-Token': getToken(),
    'Authorization': getToken(),
  };
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  const handleBack = ()=>{
    fileList.value = [];
    resetFields();
  }
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      if (values.bz==''){
        message.error('请上传文件');
        return;
      }
      if (values.dksl==''){
        message.error('请上传文件');
        return;
      }
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, values });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped></style>
