<template>
  <!-- 自定义表单 -->
  <BasicModal v-bind="$attrs" @register="registerModal" title="项目合同信息详情" width="1200px" :showOkBtn="false"
    :showCancelBtn="false">
    <el-divider content-position="left">项目信息</el-divider>
    <BasicForm @register="registerMoneyForm" />
    <el-divider content-position="left">合同信息</el-divider>
    <BasicForm @register="registerContractForm" />
    <el-button type="primary" @click="addFrom">
      <template #icon>
        <PlusCircleOutlined />
      </template>
    </el-button>
    <el-button type="primary" @click="minusFrom">
      <template #icon>
        <MinusCircleOutlined />
      </template>
    </el-button>
    <el-divider content-position="left">上传合同文件</el-divider>
    <el-form ref="importFormRef">

      <el-form-item label="上传文件:">
        <el-upload class="upload-demo" ref="upload" action :http-request="httpRequest" :before-upload="beforeUpload"
          :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">文件大小且不超过10M</div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitImportForm">上传</el-button>
        <el-button type="info" @click="dialogVisible">关闭窗口</el-button>
      </el-form-item>
    </el-form>
  </BasicModal>
</template>
<script lang="ts" name="addAndModify" setup>
import { ref, reactive, onMounted } from 'vue'
import { useForm, BasicForm } from '@/components/Form';
import { contractformSchemas, MoneyFormSchemas } from './projectContract.data';
import { modifyContractinfo, addContractinfo, getContractinfoByProjectId } from './projectContract.api';
import { queryProjectInfoNewDataById } from '@/views/projectLib/projectInfo/projectInfo.api'
import { ElMessage } from 'element-plus'
import { useModalInner, BasicModal } from '@/components/Modal';
import { FormSchema } from '@/components/Form';
import { message } from 'ant-design-vue';
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
import { cloneDeep } from 'lodash-es';

const [registerModal, { closeModal }] = useModalInner(init);


let fileList = reactive<Array<any>>([]);
let isModify = ref()
let projectid = ref()
let payNum = ref(1)
let resMoney = ref()
let tempSchemas = cloneDeep(contractformSchemas) as Array<FormSchema>
const emit = defineEmits(['close']);

async function init(data) {
  payNum.value = 1
  tempSchemas = cloneDeep(contractformSchemas) as Array<FormSchema>
  console.log("datadatadata", data, tempSchemas)
  projectid.value = data.projectid
  let parammoney: any = {
    projectid: data.projectid
  }
  resMoney.value = await queryProjectInfoNewDataById(parammoney)
  setFieldsValueMoneyForm(resMoney.value)
  fileList.pop()
  if (data.isModify != null) {
    isModify.value = data.isModify
    let param: any = {
      projectid: data.projectid
    }
    let res = await getContractinfoByProjectId(param) as Array<any>
    let obj = new Object()
    //记录一共有几次支付
    let num = res.length
    //把数组变成对象
    for (let i = 1; i <= num; i++) {

      if (i == 1) {
        obj = res[i - 1]
      } else {
        Object.keys(res[i - 1]).forEach(key => {
          obj[key + i] = res[i - 1][key]
        })
      }
    }

    if (num > 1) {
      payNum.value = num
      for (let i = 2; i <= num; i++) {
        contractformSchemas.forEach(item => {
          let tempitem = cloneDeep(item)
          if (tempitem.field == "payDate") {
            tempitem.label = "第" + i + "次支付"
          }
          if (tempitem.field == "totalMoney") {
            tempitem.label = "第" + i + "支付总金额"
          }
          tempitem.field = tempitem.field + i
          tempSchemas.push(tempitem)
        })
      }
      resetSchema(tempSchemas)
    }
    console.log("结果是", res, obj)
    obj["id"] = data.projectid
    setFieldsValue(obj)
  } else {
    //需要项目id 组件需要这个id去查询属性名称是否正确
    setFieldsValue({ id: data.projectid })
  }
}
onMounted(async () => {

})

//项目金额相关信息
const [registerMoneyForm, { setFieldsValue: setFieldsValueMoneyForm }] = useForm({
  //注册表单列
  schemas: MoneyFormSchemas,
  showActionButtonGroup: false,
  //回车提交
  // autoSubmitOnEnter: true,
  // //不显示重置按钮
  // showResetButton: false,
  //自定义提交按钮文本和图标
  // submitButtonOptions: { text: '提交', preIcon: '' },
  //查询列占比 24代表一行 取值范围 0-24
  // actionColOptions: { span: 17 },
  disabled: true,
  size: "small",
  // labelCol: { style: { width: '120px' } },
  wrapperCol: { style: { width: 'auto' } },
});



//项目入库详情
const [registerContractForm, { setFieldsValue: setFieldsValue, getFieldsValue, validate, resetSchema, removeSchemaByField }] = useForm({
  //注册表单列
  schemas: contractformSchemas,
  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' } },
});

async function addFrom() {
  let a = await validate()
  if (a) {
    payNum.value += 1
    contractformSchemas.forEach(item => {
      let tempitem = cloneDeep(item)
      if (tempitem.field == "payDate") {
        tempitem.label = "第" + payNum.value + "次支付"
      }
      if (tempitem.field == "totalMoney") {
        tempitem.label = "第" + payNum.value + "支付总金额"
      }
      tempitem.field = tempitem.field + payNum.value
      tempSchemas.push(tempitem)
    })
    //  console.log("temp222222",tempSchemas,tempSchemas.length)
    resetSchema(tempSchemas)
  }
}
function minusFrom() {
  if (payNum.value == 1) {
    message.warning("至少保留一个支付项");
    return
  }
  let last = cloneDeep(tempSchemas)
  last = last.slice(payNum.value * 9 - 9)
  last.forEach(element => {
    removeSchemaByField(element.field)
  });
  tempSchemas = tempSchemas.slice(0, payNum.value * 9 - 9)
  payNum.value -= 1
  resetSchema(tempSchemas)
}
// 覆盖默认的上传行为，可以自定义上传的实现，将上传的文件依次添加到fileList数组中,支持多个文件
function httpRequest(option) {
  fileList.push(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) {
  let fileSize = file.size
  const FIVE_M = 10 * 1024 * 1024;
  //大于5M，不允许上传
  if (fileSize > FIVE_M) {
    ElMessage.error("最大上传10M")
    return false
  }

  return true
}
// 文件数量过多时提醒
function handleExceed() {
  ElMessage.warning("最多只能上传一个文件")
}
//导入Excel病种信息数据
async function submitImportForm() {
  let res = []
  let data = await getFieldsValue()
  for (let i = 1; i <= payNum.value; i++) {
    let obj = new Object()
    contractformSchemas.forEach(item => {
      if (i == 1) {
        obj[item.field] = data[item.field]
      } else {
        obj[item.field] = data[item.field + i]
      }
      obj["projectId"] = projectid.value
      delete obj.id;
    })
    res.push(obj)
  }
  console.log("data", data, res)
  // if(checkForm()){
  //   ElMessage.success("新增成功")
  // }
  if (await validate() && checkForm()) {
    const params = new FormData()
    console.log("data", data)
    // 使用form表单的数据格式
    if (isModify.value != null) {
      if (fileList.length > 0) {
        params["file"] = fileList[0].file
      }
      //说明是修改
      params.append("contractinfoList", JSON.stringify(res))
      await modifyContractinfo(params)
    } else {
      if (fileList.length == 0) {
        ElMessage.warning("请上传文件")
        return;
      }
      params.append("file", fileList[0].file)
      params.append("contractinfoList", JSON.stringify(res))
      await addContractinfo(params)
    }
    dialogVisible()
  }

}
function dialogVisible() {
  closeModal()
  emit("close")
}

function checkForm() {   //校验表单
  let centralMoney = resMoney.value.centralMoney
  let data = getFieldsValue()
  let totalCentralMoney = 0
  let totalCountyMoney = 0
  let totalCityMoney = 0
  let totalProvincialMoney = 0
  let totalSelfMoney = 0
  let totalMoney = 0
  let showshoufu = false
  let showchuyan = false
  let showzhongyan = false
  let returnRes = true
  //校验首付和初验比例
  Object.keys(data).forEach(key => {
    if (key.indexOf("taskName") != -1 && data[key].indexOf("首付") != -1) {
      showshoufu = true
      if (key == "taskName") {
        if (Number(data["centralMoney"]) / Number(centralMoney) > 0.3) {
          ElMessage.error("首付的中央资金不能超过总中央资金的30%")
          returnRes = false

          return
        }
      } else {
        //首付之前有其他阶段，求和
        let num = key.replace("taskName", "")
        let total = Number(data["centralMoney"])
        for (let i = 2; i <= Number(num); i++) {
          total += Number(data[`centralMoney${i}`])
        }
        if (total / Number(centralMoney) > 0.3) {
          ElMessage.error("首付的中央资金不能超过总中央资金的30%")
          returnRes = false

          return
        }
      }
    }
    if (key.indexOf("taskName") != -1 && data[key].indexOf("初验") != -1) {
      showchuyan = true
      if (key == "taskName") {
        if (Number(data["centralMoney"]) / Number(centralMoney) > 0.6) {
          ElMessage.error("初验的中央资金不能超过总中央资金的60%")
          returnRes = false

          return
        }
      } else {
        //首付之前有其他阶段，求和
        let num = key.replace("taskName", "")
        let total = Number(data["centralMoney"])
        for (let i = 2; i <= Number(num); i++) {
          total += Number(data[`centralMoney${i}`])
        }
        if (total / Number(centralMoney) > 0.6) {
          ElMessage.error("初验的中央资金不能超过总中央资金的60%")
          returnRes = false

          return
        }
      }
    }
    if (key.indexOf("taskName") != -1 && data[key].indexOf("终验") != -1) {
      showzhongyan = true
    }
    //校验各项金额比例
    if (key.includes("centralMoney")) {
      totalCentralMoney += Number(data[key])
    }
    if (key.includes("countyMoney")) {
      totalCountyMoney += Number(data[key])
    }
    if (key.includes("cityMoney")) {
      totalCityMoney += Number(data[key])
    }
    if (key.includes("provincialMoney")) {
      totalProvincialMoney += Number(data[key])
    }
    if (key.includes("selfMoney")) {
      totalSelfMoney += Number(data[key])
    }
    if (key.includes("totalMoney")) {
      totalMoney += Number(data[key])
    }
  })
  if(!returnRes){
    return false
  }
  if (totalCentralMoney != Number(resMoney.value.centralMoney)) {
    ElMessage.error("中央资金总额不匹配")
    return false
  }
  if (totalCountyMoney != Number(resMoney.value.countyMoney)) {
    ElMessage.error("县级资金总额不匹配")
    return false
  }
  if (totalCityMoney != Number(resMoney.value.cityMoney)) {
    ElMessage.error("市级资金总额不匹配")
    return false
  }
  if (totalProvincialMoney != Number(resMoney.value.provincialMoney)) {
    ElMessage.error("省级资金总额不匹配")
    return false
  }
  if (totalSelfMoney != Number(resMoney.value.selfMoney)) {
    ElMessage.error("自筹资金总额不匹配")
    return false
  }
  if (totalMoney != Number(resMoney.value.totalMoney)) {
    ElMessage.error("总资金总额不匹配")
    return false
  }
  if (!showshoufu) {
    ElMessage.error("请添加首付任务")
    return false
  }
  if (!showchuyan) {
    ElMessage.error("请添加初验任务")
    return false
  }
  if (!showzhongyan) {
    ElMessage.error("请添加终验任务")
    return false
  }
  console.log("data", data)
  return true
}


</script>
<style scoped></style>
