<template>
  <!-- 自定义表单 -->
  <!-- <el-divider content-position="left">模板表格文件下载</el-divider>
    <div style="padding-left: 40px;">
        <el-button slot="trigger" type="primary">下载模板</el-button>
    </div> -->
  <BasicForm @register="registerApprovalMoneyForm" v-if="dataTo.taskName == '立项审批'" />
  <BasicForm @register="registerContractMoneyForm" v-if="dataTo.taskName == '合同签订'" />

  <el-divider content-position="left">上传文件</el-divider>
  <el-divider content-position="left" v-if="dataTo.taskName.indexOf('可研报告初稿编制') >= 0"
    >支持上传文件数量为1-2份</el-divider
  >
  <el-divider content-position="left" v-if="dataTo.taskName.indexOf('可研报告送审稿编制') >= 0"
    >支持上传文件数量为1-3份</el-divider
  >
  <el-form ref="importFormRef">
    <el-form-item
      v-for="(item, index) in dataTo.files"
      :key="index"
      :label="item"
      label-width="auto"
    >
      <el-upload
        class="upload-demo"
        ref="upload"
        action
        :http-request="httpRequest"
        :before-upload="
          (file) => {
            return beforeUpload(file, item);
          }
        "
        :on-exceed="handleExceed"
        :limit="1"
        :on-remove="removeFile"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传{{ item }}且不超过500M</div>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitImportForm" :disabled="isSubmitting"
        >开始导入</el-button
      >
      <el-button type="info" @click="dialogVisible">关闭窗口</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" name="uploadFile" setup>
  import { reactive, defineProps, onMounted, ref } from 'vue';
  import { planUploadFile, planUploadModifyFile, planREUploadFile } from './projectPlan.api';
  import { message } from 'ant-design-vue';
  import { queryProjectInfoById } from '@/views/projectLib/projectInfo/projectInfo.api';
  import { getplaninfoByid } from '@/views/projectLib/projectPlan/projectPlan.api';
  import {
    ApprovalMoneyFormSchemas,
    ContractMoneyFormSchemas,
  } from '@/views/projectLib/projectPlan/projectPlan.data';
  import { useForm, BasicForm } from '@/components/Form';
  const [
    registerApprovalMoneyForm,
    {
      validate: validateApprovalMoneyForm,
      getFieldsValue: getApprovalMoneyFieldsValue,
      setFieldsValue: setApprovalMoneyFieldsValue,
    },
  ] = useForm({
    //注册表单列
    schemas: ApprovalMoneyFormSchemas,
    showActionButtonGroup: false,
    //回车提交
    // autoSubmitOnEnter: true,
    // //不显示重置按钮
    // showResetButton: false,
    //自定义提交按钮文本和图标
    // submitButtonOptions: { text: '提交', preIcon: '' },
    //查询列占比 24代表一行 取值范围 0-24
    // actionColOptions: { span: 17 },
    // size: "small",
    // labelCol: { style: { width: '120px' } },
    wrapperCol: { style: { width: 'auto' } },
  });
  const [
    registerContractMoneyForm,
    {
      validate: validateContractMoneyForm,
      getFieldsValue: getContractMoneyFieldsValue,
      setFieldsValue: setContractMoneyFieldsValue,
      updateSchema: updateContractMoneySchema,
    },
  ] = useForm({
    //注册表单列
    schemas: ContractMoneyFormSchemas,
    showActionButtonGroup: false,
    //回车提交
    // autoSubmitOnEnter: true,
    // //不显示重置按钮
    // showResetButton: false,
    //自定义提交按钮文本和图标
    // submitButtonOptions: { text: '提交', preIcon: '' },
    //查询列占比 24代表一行 取值范围 0-24
    // actionColOptions: { span: 17 },
    // size: "small",
    // labelCol: { style: { width: '120px' } },
    wrapperCol: { style: { width: 'auto' } },
  });

  let fileList = reactive<Array<any>>([]);
  let projectId = ref('');
  let isSubmitting = ref(false);
  let dataTo = defineProps(['type', 'files', 'planinfoid', 'taskName']);
  const emit = defineEmits(['close']);
  //加载项目数据
  onMounted(async () => {
    console.log('dataTo', dataTo);
    let resList = await getplaninfoByid({ planinfoid: dataTo.planinfoid });
    let param: any = {
      projectid: resList[0].projectId,
    };
    projectId.value = resList[0].projectId;
    let res = await queryProjectInfoById(param);
    if (dataTo.taskName == '立项审批') {
      setApprovalMoneyFieldsValue({ approvalTotalMoney: res.urtEstimatedAmount });
    }
    if (dataTo.taskName == '合同签订') {
      updateContractMoneySchema({
        field: 'contractTotalMoney',
        componentProps: {
          precision: 2,
          min: 0,
          style: { width: '100%' },
          max: res.urtEstimatedAmount,
        },
      });
    }
  });

  function httpRequest(option) {
    fileList.push(option);
    console.log(fileList, option);
  }
  function removeFile(option) {
    for (let i = 0; i < fileList.length; i++) {
      if (fileList[i].file.name == option.name) {
        fileList.splice(i, 1);
      }
    }
    console.log(fileList, option);
  }
  // 上传前处理
  function beforeUpload(file, item) {
    console.log('file,item', file, item);
    let fileSize = file.size;
    const FIVE_M = 500 * 1024 * 1024;
    //大于5M，不允许上传
    if (fileSize > FIVE_M) {
      message.error('最大上传500M');
      return false;
    }
    let geShi = ['xlx', 'xlsx', 'docx', 'doc', 'pdf'] as Array<string>;
    if (geShi.indexOf(file.name.substring(file.name.lastIndexOf('.') + 1)) == -1) {
      message.error('文件格式错误！仅支持' + 'xlx,xlsx, docx, doc, pdf');
      console.log('文件格式错误！仅支持' + 'xlsx', 'docx', 'doc', 'pdf');
      return false;
    }
    if (item.indexOf(file.name.substring(0, file.name.indexOf('.'))) == -1) {
      message.error('请上传文件:' + item);
      return false;
    }
    console.log('文件上传成功');

    return true;
  }
  // 文件数量过多时提醒
  function handleExceed() {
    message.warning('最多只能上传一个文件');
  }
  //导入Excel病种信息数据
  async function submitImportForm() {
    if (fileList.length == 0) {
      message.error('未选择任何文件，无法上传！');
      return;
    }
    // type ==0新增，type ==1 是修改
    //“可研报告初稿编制”阶段：需支持上传《可行性研究报告（初稿）》或《项目建议书》（支持上传文件数量为1-2份）
    if (
      dataTo.taskName.indexOf('可研报告初稿编制') >= 0 ||
      dataTo.taskName.indexOf('可研报告送审稿编制') >= 0
    ) {
      //有一个文件就行
    } else {
      if (fileList.length != dataTo.files.length && dataTo.type == 0) {
        message.error('上传的文件数量与项目计划资料数量不一致，请检查');
        return;
      }
    }

    // // 使用form表单的数据格式
    const params = new FormData();
    if (dataTo.taskName == '立项审批') {
      if (await validateApprovalMoneyForm()) {
        const approvalMoneyFieldsValue = getApprovalMoneyFieldsValue();
        const {
          approvalTotalMoney,
          approvalCentralMoney,
          approvalProvincialMoney,
          approvalCityMoney,
          approvalCountyMoney,
          approvalSelfMoney,
        } = approvalMoneyFieldsValue;

        // 计算其他金额之和
        const sumOfOtherAmounts =
          approvalCentralMoney +
          approvalProvincialMoney +
          approvalCityMoney +
          approvalCountyMoney +
          approvalSelfMoney;
        // 校验总金额是否等于其他金额之和
        if (Math.abs(approvalTotalMoney - sumOfOtherAmounts) < Number.EPSILON) {
          approvalMoneyFieldsValue['id'] = projectId.value;
          params.append('approvalMoneyFieldsValue', JSON.stringify(approvalMoneyFieldsValue));
        } else {
          message.error('总金额与其他金额之和不相等，请重新输入！');
          return;
        }
      } else {
        return;
      }
    } else if (dataTo.taskName == '合同签订') {
      if (await validateContractMoneyForm()) {
        const contractMoneyFieldsValue = getContractMoneyFieldsValue();
        const {
          contractTotalMoney,
          contractCentralMoney,
          contractProvincialMoney,
          contractCityMoney,
          contractCountyMoney,
          contractSelfMoney,
        } = contractMoneyFieldsValue;

        // 计算其他金额之和
        const sumOfOtherAmounts =
          contractCentralMoney +
          contractProvincialMoney +
          contractCityMoney +
          contractCountyMoney +
          contractSelfMoney;

        // 校验总金额是否等于其他金额之和，使用Number.EPSILON进行比较
        if (Math.abs(contractTotalMoney - sumOfOtherAmounts) < Number.EPSILON) {
          contractMoneyFieldsValue['id'] = projectId.value;
          params.append('contractMoneyFieldsValue', JSON.stringify(contractMoneyFieldsValue));
        } else {
          message.error('总金额与其他金额之和不相等，请重新输入！');

          return;
        }
      } else {
        return;
      }
    }
    // 将上传文件数组依次添加到参数paramsData中
    fileList.forEach((x) => {
      console.log('xxxxxxxxxx', x, x.file);
      params.append('file', x.file);
    });
    params.append('planinfoid', dataTo.planinfoid);
    isSubmitting.value = true;
    if (dataTo.type == 0) {
      planUploadFile(params)
        .then(() => {
          emit('close');
        })
        .catch(() => {
          isSubmitting.value = false;
        });
    } else if (dataTo.type == 1) {
      planUploadModifyFile(params)
        .then(() => {
          emit('close');
        })
        .catch(() => {
          isSubmitting.value = false;
        });
    } else {
      planREUploadFile(params)
        .then(() => {
          emit('close');
        })
        .catch(() => {
          isSubmitting.value = false;
        });
    }
  }
  function dialogVisible() {
    emit('close');
  }
</script>

<style></style>
