<script setup name='renewalCapitalDeclare'>
import { reactive, ref, onMounted, h, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import store from '@/store'
import {
  convertToCollection,
  renewalDeclared,
  renewalDeclaredDetail,
  libAllList
} from '@/http/apis/declareMange/renewalProjectCapitalDeclare'
import { detail } from '@/http/apis/projectCollection/projectCollectionEnter'
import { storeToRefs } from 'pinia'
import { dictionary, save } from '@/http/apis/projectCollection/projectCollectionEnter'
import BasicInfo from '@/pages/projectCollection/projectCollectionEnter/components/basicInfo.vue'
import ProjectDeclareInfo from '@/pages/projectCollection/projectCollectionEnter/components/projectDeclareInfo.vue'
import ApplicationInfo from '@/pages/projectCollection/projectCollectionEnter/components/applicationInfo.vue'
import CoreBusiness from '@/pages/projectCollection/projectCollectionEnter/components/coreBusiness.vue'
import ProjectApprovalInfo from '@/pages/projectCollection/projectCollectionEnter/components/projectApprovalInfo.vue'
import PurchaseInfo from '@/pages/projectCollection/projectCollectionEnter/components/purchaseInfo.vue'
import EmpMaterials from '@/pages/projectCollection/projectCollectionEnter/components/empMaterials.vue'
import { contractDetail } from '@/http/apis/declareMange/contractRecord'
import { changFilesParam } from '@/utils/uploadAction'
const { proxy } = getCurrentInstance(),
  { statusOptions, statusGjOptions, projectTypeOptions } = store.dictStore.globalDicts || {},
  userInfo = storeToRefs(store.userStore).userInfo || {},
  router = useRouter(),
  route = useRoute(),
  // 列表
  column = reactive([
    {
      type: 'radio',
      key: 'id',
      width: '50'
    },
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '项目类型',
      key: 'projectType',
      prop: 'projectType',
      minWidth: '80',
      render: row => h('span', projectTypeOptions[row.projectType] || '-')
    },
    {
      label: '批复总金额（万元）',
      key: 'approvedAmount',
      prop: 'approvedAmount',
      width: '180'
    },
    {
      label: '累计年度投资资金',
      key: 'annualAccumulateAmountList',
      slot: 'annualAccumulateAmountList',
      width: '180'
    },
    {
      label: '项目状态',
      key: 'status',
      prop: 'status',
      width: '180',
      render: row => [
        h('span', {
          class: ['dot mr-4', `bg-${statusOptions[row.status]?.color || statusGjOptions[row.status]?.color}`]
        }),
        h(
          'span',
          {
            class: `text-${statusOptions[row.status]?.color || statusGjOptions[row.status]?.color}`
          },
          row.status && statusOptions[row.stage]?.name ? `${statusOptions[row.stage]?.name}-${statusOptions[row.status]?.name}` : statusGjOptions[row.status]?.name || '-'
        )
      ]
    }
  ]),
  column1 = reactive([
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '项目类型',
      key: 'projectType',
      prop: 'projectType',
      minWidth: '80',
      render: row => h('span', projectTypeOptions[row.projectType] || '-')
    },
    {
      label: '批复总金额（万元）',
      key: 'approvalAmount',
      prop: 'approvalAmount',
      width: 150
    },
    {
      label: '累计年度投资资金',
      key: 'annualAccumulateAmountList',
      slot: 'annualAccumulateAmountList',
      width: 150
    },
    {
      label: '项目状态',
      key: 'status',
      prop: 'status',
      width: '120',
      render: row => [
        h('span', {
          class: ['dot mr-4', `bg-${statusOptions[row.status]?.color || statusGjOptions[row.status]?.color}`]
        }),
        h(
          'span',
          {
            class: `text-${statusOptions[row.status]?.color || statusGjOptions[row.status]?.color}`
          },
          row.status && statusOptions[row.stage]?.name ? `${statusOptions[row.stage]?.name}-${statusOptions[row.status]?.name}` : statusGjOptions[row.status]?.name || '-'
        )
      ]
    }
  ]),
  total = ref(0),
  data = ref([]),
  tableListRef = ref(),
  maxYear = ref(),
  totalAmount = ref(0),
  approvedAmount = ref(),
  radioChange = (val) => {
    ruleForm.value.projectId = val.id
    ruleForm.value.projectCode = val.projectCode
    maxYear.value = val.annualAccumulateAmountList?.length > 1 && val.annualAccumulateAmountList.reduce((acc, cur) => Math.max(acc.projectYear, cur.projectYear)) || val.annualAccumulateAmountList[0].projectYear
    totalAmount.value = val.annualAccumulateAmountList?.map(i => i.annualAmount)?.reduce((acc, cur) => { return acc + cur }, 0)
    approvedAmount.value = val.approvedAmount
    getPayInfo(val.id)
    getProjectDetail(val.projectCode, val.fromType)
  },
  searchForm = reactive({
    projectName: undefined
  }),
  search = () => {
    tableListRef.value.pageParams.pageNumber = 1
    getTableData()
  },
  getTableData = async (pageParams = tableListRef.value.pageParams) => {
    const res = await libAllList({
      ...pageParams,
      projectName: searchForm.projectName
    })
    data.value = res.data.records.map(i => {
      return {
        ...i,
        isRadioDisabled: i.annualAccumulateAmountList?.map(i => i.annualAmount)?.reduce((acc, cur) => { return acc + cur }, 0) === i.approvedAmount
      }
    })
    total.value = res.data.total
  },
  // 表单
  ruleFormRef = ref(),
  moneyValidator = (rule, value, callback) => {
    if (!value) callback()
    if (!/^\d+(\.\d{1,6})?$/.test(value)) {
      callback('请输入正确格式，最多保留六位小数')
    } else if (value * 1 >= 100000000) {
      callback('请输入正确格式，小于100000000')
    } else {
      callback()
    }
  },
  moneyValidator1 = (rule, value, callback) => {
    if (!value) callback()
    if (!/^\d+(\.\d{1,6})?$/.test(value)) {
      callback('请输入正确格式，最多保留六位小数')
    } else if (value * 1 >= 100000000) {
      callback('请输入正确格式，小于100000000')
    }
    let maxData = 0
    paymentsData.value.forEach(i => {
      if (new Date(i.paymentTime).getFullYear() < ruleForm.value.projectYear * 1) {
        maxData += i.paymentAmount - i.actualPaymentAmount
      }
    })
    maxData += paymentsData.value.find(i => new Date(i.paymentTime).getFullYear() === ruleForm.value.projectYear * 1)?.paymentAmount
    if (value > maxData) {
      callback(`支付金额最大不能超过${maxData}万元`)
    } else {
      callback()
    }
  },
  //  yearValidator = (rule, value, callback) => {
  //   if (!value) callback()
  //   if (!paymentsData.value?.length) {
  //     callback('未有支付信息，无法提交')
  //   }
  //   const years1 = paymentsData.value.map(i => new Date(i.paymentTime).getFullYear() + '')
  //   // const years2 = paymentsData.value.filter(i => i.actualPaymentAmount || i.actualPaymentAmount === 0).map(i => new Date(i.paymentTime).getFullYear() + '')
  //   if (!years1.includes(value)) {
  //     callback('未有所选年度的支付计划，无法提交')
  //   } else {
  //     callback()
  //   }
  //   // else if (!years2.includes(value)) {
  //   //   callback('未填写当年度的实际支付金额，请去合同备案补充”')
  //   // }
  // },
  disabledDate = (time) => {
    return new Date(time).getFullYear() <= new Date().getFullYear()
  },
  rules = reactive({
    projectId: [
      { required: true, message: '请选择关联项目', trigger: 'blur' }
    ],
    projectYear: [
      { required: true, message: '请选择预算年度', trigger: 'blur' }
      // { validator: yearValidator, trigger: 'blur' }
    ],
    annualPaymentAmount: [
      { required: true, message: '请输入年度支付金额', trigger: 'blur' },
      { validator: moneyValidator1, trigger: 'blur' }
    ],
    haveAmount: [
      { required: true, message: '请输入自有资金金额', trigger: 'blur' },
      { validator: moneyValidator, trigger: 'blur' }
    ],
    govOwnFinanceAmount: [
      { required: true, message: '请输入政府投资-本级财政资金金额', trigger: 'blur' },
      { validator: moneyValidator, trigger: 'blur' }
    ],
    govSuperiorFinanceAmount: [
      { required: true, message: '请输入政府投资-上级补助资金金额', trigger: 'blur' },
      { validator: moneyValidator, trigger: 'blur' }
    ],
    bankLendingAmount: [
      { required: true, message: '请输入银行贷款金额', trigger: 'blur' },
      { validator: moneyValidator, trigger: 'blur' }
    ],
    otherAmount: [
      { required: true, message: '请输入其他金额', trigger: 'blur' },
      { validator: moneyValidator, trigger: 'blur' }
    ]
  }),
  ruleForm = ref({
    id: route.query.id || undefined,
    orgCode: userInfo.empPosUnitCode,
    regionCode: userInfo.regionCode

  }),
  // floatAdd = (args) => {
  //   const data = []
  //   args.forEach(i => {
  //     try {
  //       data.push(i.toString().split('.')[1].length)
  //     } catch (e) {
  //       data.push(0)
  //     }
  //   })
  //   const m = Math.pow(10, Math.max(...data))
  //   let sum = 0
  //   args.forEach(item => {
  //     sum += item * m
  //   })
  //   return sum / m
  // },
  submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        // if (ruleForm.value.projectYear * 1 <= maxYear.value * 1) {
        //   proxy.$message.warning('预算年度必须大于累计投资的最大年度')
        //   return
        // }
        // if (floatAdd([ruleForm.value.annualPaymentAmount, totalAmount.value]) > approvedAmount.value) {
        //   proxy.$message.warning('累计年度投资金额必须小于等于批复总金额')
        //   return
        // }
        if (errorText.value) {
          proxy.$message.error(errorText.value)
          return
        }
        // const total = floatAdd([ruleForm.value.haveAmount, ruleForm.value.govOwnFinanceAmount, ruleForm.value.govSuperiorFinanceAmount, ruleForm.value.bankLendingAmount, ruleForm.value.otherAmount])
        // if (total !== ruleForm.value.annualPaymentAmount) {
        //   proxy.$message.warning('各资金来源的和必须等于年度支付金额')
        //   return
        // }
        if (!route.query.id) {
          const arr = Object.values(formRefs).map(async i => i?.formRef && await i.formRef.validate())
          await Promise.all(arr)
        }
        const postData = {
          ...ruleForm.value,
          projectYear: ruleForm.value.projectYear * 1
        }
        await renewalDeclared(postData)
        !route.query.id && submitProject()
      } else {
        console.log('error submit!', fields)
      }
    })
  },
  getDetail = async () => {
    const res = await renewalDeclaredDetail(route.query.id)
    ruleForm.value = { ...res.data, projectYear: res.data.projectYear + '' }
    data.value = [{ ...res.data }]
    maxYear.value = res.data.annualAccumulateAmountList?.length > 1 && res.data.annualAccumulateAmountList.reduce((acc, cur) => Math.max(acc.projectYear, cur.projectYear)) || res.data.annualAccumulateAmountList[0].projectYear
    totalAmount.value = res.data.annualAccumulateAmountList?.map(i => i.annualAmount)?.reduce((acc, cur) => { return acc + cur }, 0)
    approvedAmount.value = res.data.approvalAmount
    getPayInfo(res.data.projectId)
  },
  // 支付信息
  payColumn = [
    {
      label: '付款笔数',
      key: 'number',
      slot: 'number'
    },
    {
      label: '付款计划',
      key: 'planAmount',
      slot: 'planAmount'
    },
    {
      label: '付款比例（%）',
      key: 'ratio',
      slot: 'ratio'
    },
    {
      label: '付款金额（万元）',
      key: 'paymentAmount',
      slot: 'paymentAmount'
    },
    {
      label: '预计付款时间',
      key: 'paymentTime',
      slot: 'paymentTime'
    },
    {
      label: '实际支付金额（万元）',
      key: 'actualPaymentAmount',
      slot: 'actualPaymentAmount',
      width: 180
    }
  ],
  paymentsData = ref(),
  errorText = ref(''),
  getPayInfo = async (id) => {
    const res = await contractDetail(id)
    paymentsData.value = res?.data?.payments || []
    errorText.value = ''
    // if (!paymentsData.value?.length) {
    //   errorText.value = '该项目未有支付信息'
    //   proxy.$message.error(errorText.value)
    //   return
    // }
    // let count = 0
    // paymentsData.value.forEach(i => {
    //   if (new Date(i.paymentTime).getTime() < new Date().getTime() && !(i.actualPaymentAmount || i.actualPaymentAmount === 0)) {
    //     count++
    //   }
    // })
    // if (count > 0) {
    //   errorText.value = '超过预付款时间的支付计划未填写实际支付金额,请去合同备案补充'
    //   proxy.$message.error(errorText.value)
    //   return
    // }
    return
  },
  // 补充信息
  formRefs = {},
  detailData = ref(),
  basicInfoData = ref(),
  getBasicInfoData = (data) => {
    basicInfoData.value = data
  },
  dictionaryList = ref(),
  baseProjSetYear = ref(),
  getProYear = (data) => {
    baseProjSetYear.value = data
  },
  approvalInfoData = ref(),
  getApprovalInfoData = (data) => {
    approvalInfoData.value = data
  },
  baseProjName = ref(),
  getProjectDetail = async (projectCode, fromType) => {
    let res = {}
    // 归集项目详情使用detail 申报项目详情使用convertToCollection
    if (fromType === '2') {
      res = await detail('1', projectCode)
    } else {
      res = await convertToCollection(projectCode)
    }
    baseProjName.value = res.data.baseinfo.baseProjName
    detailData.value = {
      ...res.data,
      baseinfo: {
        ...res.data.baseinfo,
        baseProjType: '03'
      },
      cimplement: {
        ...res.data.cimplement,
        baseCheckFile: res.data.cimplement?.baseCheckFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseCheckFile))) || undefined,
        baseInitialOpinionFile: res.data.cimplement?.baseInitialOpinionFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseInitialOpinionFile))) || undefined,
        baseEstaSummFile: res.data.cimplement?.baseEstaSummFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseEstaSummFile))) || undefined,
        baseSummReportFile: res.data.cimplement?.baseEstaSummFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseSummReportFile))) || undefined,
        baseThirdAcceptFile: res.data.cimplement?.baseEstaSummFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseThirdAcceptFile))) || undefined,
        baseInforLevelFile: res.data.cimplement?.baseInforLevelFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseInforLevelFile))) || undefined,
        basePasswAssessFile: res.data.cimplement?.basePasswAssessFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.basePasswAssessFile))) || undefined,
        baseFinanlAuditFile: res.data.cimplement?.baseFinanlAuditFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseFinanlAuditFile))) || undefined,
        baseUserConsFile: res.data.cimplement?.baseUserConsFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseUserConsFile))) || undefined,
        baseFinalExpertOpinionFile: res.data.cimplement?.baseFinalExpertOpinionFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseFinalExpertOpinionFile))) || undefined,
        baseEngineerPostpoFile: res.data.cimplement?.baseEngineerPostpoFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseEngineerPostpoFile))) || undefined,
        baseChangeFormFile: res.data.cimplement?.baseChangeFormFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseChangeFormFile))) || undefined,
        baseChanFile: res.data.cimplement?.baseChanFile && JSON.stringify(changFilesParam(JSON.parse(res.data.cimplement?.baseChanFile))) || undefined
      }
    }
  },
  changeYear = () => {
    detailData.value.baseinfo.baseProjName = baseProjName.value + `（${ruleForm.value.projectYear}）`
  },
  changePostData = () => {
    const baseinfo = JSON.parse(JSON.stringify(formRefs['baseinfo'].formData))
    const apply = JSON.parse(JSON.stringify(formRefs['apply'].formData))
    const application = formRefs['application'] && JSON.parse(JSON.stringify(formRefs['application'].formData)) || {}
    const baseCore = formRefs['baseCore'] && JSON.parse(JSON.stringify(formRefs['baseCore'].formData)) || {}
    const approve = formRefs['approve'] && JSON.parse(JSON.stringify(formRefs['approve'].formData)) || {}
    const procures = formRefs['procures'] && JSON.parse(JSON.stringify(formRefs['procures'].formData)) || []
    const cimplement = formRefs['cimplement'] && JSON.parse(JSON.stringify(formRefs['cimplement'].formData)) || []
    return {
      baseProjId: '',
      baseinfo: {
        ...baseinfo,
        baseProvManDeprtType: baseinfo?.baseProvManDeprtType * 1 || undefined,
        baseConstructionType: baseinfo?.baseConstructionType?.join('；')
        // baseAreaCode: baseinfo?.baseArea?.baseAreaCode || undefined,
        // baseAreaName: baseinfo?.baseArea?.baseAreaName || undefined,
        // baseArea: undefined
      },
      apply: {
        ...apply,
        baseProjStartTime: apply?.baseProjTime?.length ? apply?.baseProjTime[0] + ' 00:00:00' : undefined,
        baseProjEndTime: apply?.baseProjTime?.length ? apply?.baseProjTime[1] + ' 00:00:00' : undefined,
        baseProjTime: undefined,
        baseHistorProjId: apply?.missing || baseinfo?.baseProjType === '01' ? '' : apply?.baseHistorProjs?.map(i => i.baseProjId)?.join('；'),
        baseHistorProjName: apply?.missing || baseinfo?.baseProjType === '01' ? '' : apply?.baseHistorProjs?.map(i => i.baseProjName)?.join('；'),
        baseHistorProjYear: apply?.missing || baseinfo?.baseProjType === '01' ? '' : apply?.baseHistorProjs?.map(i => i.baseProjSetYear)?.join('；'),
        baseProjAmountOri: apply?.baseProjAmountOri?.join('；') || undefined,
        baseProjBasis: apply?.baseProjBasis?.map(i => i.value)?.join('；') || undefined,
        baseProjBasisFile: apply?.baseProjBasis?.map(i => i.fileList && JSON.stringify(changFilesParam(i.fileList)))?.join('；') || '',
        beseExpectedResults: apply?.beseExpectedResults?.length && JSON.stringify(apply.beseExpectedResults) || '',
        baseProjApplyFile: ((['01', '02', '04', '05'].includes(baseinfo?.baseProjType) && apply?.baseProjSetYear * 1 >= 2023) || apply?.baseProjSetYear * 1 < 2023) && apply?.baseProjApplyFile?.length ? JSON.stringify(changFilesParam(apply?.baseProjApplyFile)) : '',
        baseResearchReportFile: (baseinfo?.baseProjType === '01' || baseinfo?.baseProjType === '02') && apply?.baseResearchReportFile?.length ? JSON.stringify(changFilesParam(apply?.baseResearchReportFile)) : '',
        baseProjOtherFile: apply?.baseProjOtherFile?.length ? JSON.stringify(changFilesParam(apply?.baseProjOtherFile)) : '',
        baseHistorProjs: undefined,
        ...application,
        baseProjSysCode: application?.applications?.map(i => i.application.applicationCode).join('；') || '',
        baseProjSys: application?.applications?.map(i => i.application.applicationName).join('；') || '',
        baseAccountAppName: application?.applications?.map(i => i.baseAccountAppName).join('；') || '',
        baseBrainName: application?.applications?.map(i => i.baseBrainName).join('；') || '',
        applications: undefined,
        ...baseCore,
        baseCoreBusinessCode: baseCore?.coreBusiness?.map(i => i.id).join('；') || '',
        baseCoreBusiness: baseCore?.coreBusiness?.map(i => i.matterName).join('；') || '',
        baseCoreBusinessOrg: baseCore?.coreBusiness?.map(i => i.orgName).join('；') || '',
        coreBusiness: undefined,
        baseProjId: ''
      },
      approve: {
        ...approve,
        baseReviewResults: baseinfo?.baseProjSetProg !== '01' ? approve?.baseReviewResults : '',
        baseReviewOpinion: baseinfo?.baseProjSetProg !== '01' ? approve?.baseReviewOpinion : '',
        baseReviewCommentsFile: baseinfo?.baseProjSetProg !== '01' ? approve?.baseReviewCommentsFile?.length && JSON.stringify(changFilesParam(approve?.baseReviewCommentsFile)) : '',
        equalProtectionLevel: baseinfo?.baseProjIsConfidentiality === '01' && !['01', '02', '03'].includes(baseinfo?.baseProjSetProg) ? approve?.equalProtectionLevel : '',
        approvalFile: !['01', '02', '03'].includes(baseinfo?.baseProjSetProg) ? approve?.approvalFile?.length && JSON.stringify(changFilesParam(approve?.approvalFile)) : '',
        baseExpertTotalMoney: !['01', '03'].includes(baseinfo?.baseProjSetProg) ? approve?.baseExpertTotalMoney : '',
        baseExpertYearMoney: !['01', '03'].includes(baseinfo?.baseProjSetProg) ? approve?.baseExpertYearMoney : '',
        baseInitialReviewTotalMoney: !['01', '02', '03'].includes(baseinfo?.baseProjSetProg) ? approve?.baseInitialReviewTotalMoney : '',
        baseProjReplyAmount: !['01', '02', '03'].includes(baseinfo?.baseProjSetProg) ? approve?.baseProjReplyAmount : '',
        releaseYearMoney: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) ? approve?.releaseYearMoney : '',
        preliminaryDesignScheme: approve?.baseProjReplyAmount >= 5000 && ['04', '05', '06', '07', '00'].includes(baseinfo.baseProjSetProg) ? approve?.preliminaryDesignScheme?.length && JSON.stringify(changFilesParam(approve.preliminaryDesignScheme)) : '',
        preliminaryDesignFile: approve?.baseProjReplyAmount >= 5000 && ['04', '05', '06', '07', '00'].includes(baseinfo.baseProjSetProg) ? approve?.preliminaryDesignFile?.length && JSON.stringify(changFilesParam(approve.preliminaryDesignFile)) : ''
      },
      procures: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && procures?.sections?.map(i => {
        return {
          ...i,
          baseBidName: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.baseBidName || '',
          baseProjPurchaseWay: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.baseProjPurchaseWay || '',
          basePurchaseCode: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.basePurchaseCode || '',
          basePurchasingAgencies: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && i.basePurchasingAgencies || '',
          baseUnifiedCreditCode: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && i.baseUnifiedCreditCode || '',
          baseWinningBidTime: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.baseWinningBidTime || '',
          baseProjPurchaseAmount: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.baseProjPurchaseAmount || '',
          baseConsDeprt: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.baseConsDeprt || '',
          baseConsDeprtUsci: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.baseConsDeprtUsci || '',
          basePaymentTime: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && i.basePaymentTime || '',
          paymentProgress: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && i.paymentProgress || '',
          purchaseFile: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.purchaseFile?.length ? JSON.stringify(changFilesParam(i.purchaseFile)) : '',
          biddingFile: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.biddingFile?.length ? JSON.stringify(changFilesParam(i.biddingFile)) : '',
          purchaseContract: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && i.purchaseContract?.length ? JSON.stringify(changFilesParam(i.purchaseContract)) : ''
        }
      }) || [],
      cimplement: {
        ...cimplement,
        baseInitialOpinionFile: cimplement?.baseInitialOpinionFile?.length ? JSON.stringify(changFilesParam(cimplement.baseInitialOpinionFile)) : '',
        baseInforLevelFile: ((['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && baseinfo?.baseConstructionType?.includes('01')) || !baseinfo?.baseConstructionType?.includes('01')) && cimplement?.baseInforLevelFile?.length ? JSON.stringify(changFilesParam(cimplement.baseInforLevelFile)) : '',
        basePasswAssessFile: (['04', '05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && cimplement?.basePasswAssessFile?.length ? JSON.stringify(changFilesParam(cimplement.basePasswAssessFile)) : '',
        baseThirdAcceptFile: cimplement.baseThirdAcceptFile?.length ? JSON.stringify(changFilesParam(cimplement.baseThirdAcceptFile)) : '',
        baseCheckFile: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && cimplement?.baseCheckFile?.length ? JSON.stringify(changFilesParam(cimplement.baseCheckFile)) : '',
        baseFinanlAuditFile: ['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) && approve?.releaseYearMoney * 1 >= 2000 && cimplement?.baseFinanlAuditFile?.length ? JSON.stringify(changFilesParam(cimplement.baseFinanlAuditFile)) : '',
        baseUserConsFile: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && cimplement?.baseUserConsFile?.length ? JSON.stringify(changFilesParam(cimplement.baseUserConsFile)) : '',
        baseEstaSummFile: cimplement?.baseEstaSummFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseEstaSummFile)) : '',
        baseSummReportFile: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && cimplement?.baseSummReportFile?.length ? JSON.stringify(changFilesParam(cimplement.baseSummReportFile)) : '',
        baseFinalExpertOpinionFile: baseinfo?.baseProjSetProg === '07' && cimplement.baseFinalExpertOpinionFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseFinalExpertOpinionFile)) : '',
        baseEngineerPostpoFile: cimplement?.baseEngineerPostpoFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseEngineerPostpoFile)) : '',
        baseChangeFormFile: cimplement?.baseChangeFormFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseChangeFormFile)) : '',
        baseChanFile: cimplement?.baseChanFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseChanFile)) : ''
      }
    }
  },
  submitProject = async () => {
    const postData = changePostData()
    await save(postData)
    proxy.$message.success('提交成功！')
    router.go(-1)
  }

onMounted(async () => {
  dictionaryList.value = (await dictionary()).data
  if (route.query.id) {
    getDetail()
  } else {
    getTableData()
  }
})
</script>

<template>
  <div class="footerPage">
    <el-alert
      v-if="ruleForm.approvalStatus==='NOT_PASS'"
      style="marginBottom:20px;"
      title="审核不通过"
      type="error"
      :description="`审核意见：${ruleForm.auditOpinion}`"
      show-icon
    />
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>申报信息</span>
        </div>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-input
          v-if="!$route.query.id"
          v-model="searchForm.projectName"
          placeholder="搜索项目名称"
          style="width: 200px;margin-left: 100px;"
          class="mb-8"
        >
          <template #append>
            <el-button icon="Search" @click="search" />
          </template>
        </el-input>
        <el-form-item
          label="关联项目"
          prop="projectId"
          :label-width="100"
          clas="mb-16"
        >
          <table-list
            v-if="!route.query.id"
            ref="tableListRef"
            :column="column"
            :height="350"
            :data="data"
            :total="total"
            class="w-full"
            row-key="id"
            @radio-change="radioChange"
            @get-table-data="getTableData"
          >
            <template #annualAccumulateAmountList="{scope}">
              <p v-for="(item,index) in scope.row.annualAccumulateAmountList" :key="index">{{ index+1 }}、{{ item.projectYear }}年投资{{ item.annualAmount }}万元</p>
            </template>
          </table-list>
          <table-list
            v-else
            ref="tableListRef"
            :column="column1"
            :data="data"
            :height="200"
            :pagination="false"
            class="flex-1"
          ><template #annualAccumulateAmountList="{scope}">
            <p v-for="(item,index) in scope.row.annualAccumulateAmountList" :key="index">{{ index+1 }}、{{ item.projectYear }}年投资{{ item.annualAmount }}万元</p>
          </template></table-list>
        </el-form-item>
        <p class="mb-16 flex items-center">
          <span class="mr-24">支付信息</span>
          <span class="text-danger text-14">温馨提示：实际支付金额请去合同信息填写</span>
        </p>
        <table-list
          ref="tableListRef"
          :column="payColumn"
          :data="paymentsData"
          :pagination="false"
          :empty-temp="false"
          class="mb-16"
        >
          <template #number="{scope}">
            <span>第{{ scope.$index+1 }}笔</span>
          </template>
          <template #planAmount="{scope}">
            {{ scope.row.planAmount }}
          </template>
          <template #ratio="{scope}">
            {{ scope.row.ratio }}
          </template>
          <template #paymentAmount="{scope}">
            {{ scope.row.paymentAmount }}
          </template>
          <template #paymentTime="{scope}">
            {{ scope.row.paymentTime }}
          </template>
          <template #actualPaymentAmount="{scope}">
            {{ scope.row.actualPaymentAmount }}
          </template>
        </table-list>
        <p style="margin-bottom: 16px;">申报续建资金信息</p>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="预算年度"
              prop="projectYear"
            >
              <el-date-picker
                v-model="ruleForm.projectYear"
                type="year"
                placeholder="请选择"
                format="YYYY"
                value-format="YYYY"
                :disabled-date="disabledDate"
                @change="changeYear"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="`${ruleForm.projectYear||''}支付金额`"
              prop="annualPaymentAmount"
            >
              <el-input-number
                v-model="ruleForm.annualPaymentAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="自有资金（万元）"
              prop="haveAmount"
            >
              <el-input-number
                v-model="ruleForm.haveAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="政府投资-本级财政资金（万元）"
              prop="govOwnFinanceAmount"
            >
              <el-input-number
                v-model="ruleForm.govOwnFinanceAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="政府投资-上级补助资金（万元）"
              prop="govSuperiorFinanceAmount"
            >
              <el-input-number
                v-model="ruleForm.govSuperiorFinanceAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="银行贷款（万元）"
              prop="bankLendingAmount"
            >
              <el-input-number
                v-model="ruleForm.bankLendingAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="其他"
              prop="otherAmount"
            >
              <el-input-number
                v-model="ruleForm.otherAmount"
                placeholder="请填写"
                :min="0"
                :controls="false"
                @mousewheel.prevent
              />
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="!route.query.id">
          <p style="margin-bottom: 16px;">补充项目信息</p>
          <el-collapse>
            <el-collapse-item name="1" class="mb-16">
              <template #title>
                <div class="collapse-title">项目基本信息</div>
              </template>
              <div class="pb-24">
                <basic-info
                  :ref="el=>formRefs['baseinfo']=el"
                  :detail="detailData"
                  :dictionary-list="dictionaryList"
                  :is-supplemented="true"
                  @get-basic-info-data="getBasicInfoData"
                />
              </div>
            </el-collapse-item>
            <el-collapse-item name="2" class="mb-16">
              <template #title>
                <div class="collapse-title">项目申报信息</div>
              </template>
              <div class="pb-24">
                <project-declare-info
                  :ref="el=>formRefs['apply']=el"
                  :detail="detailData"
                  :basic-info-data="basicInfoData"
                  :dictionary-list="dictionaryList"
                  :is-supplemented="true"
                  @get-pro-year="getProYear"
                />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="!(basicInfoData?.baseConstructionType?.length===1&&basicInfoData?.baseConstructionType.includes('01'))" name="3" class="mb-16">
              <template #title>
                <div class="collapse-title">项目关联信息</div>
              </template>
              <div class="pb-24">
                <application-info
                  :ref="el=>formRefs['application']=el"
                  :detail="detailData"
                  :basic-info-data="basicInfoData"
                  :is-supplemented="true"
                />
              </div>
            </el-collapse-item>
            <el-collapse-item name="4" class="mb-16">
              <template #title>
                <div class="collapse-title">核心业务</div>
              </template>
              <div class="pb-24">
                <core-business :ref="el=>formRefs['baseCore']=el" :detail="detailData" :is-supplemented="true" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="basicInfoData?.baseProjSetProg!=='01'" name="5" class="mb-16">
              <template #title>
                <div class="collapse-title">项目立项评审信息</div>
              </template>
              <div class="pb-24">
                <project-approval-info
                  :ref="el=>formRefs['approve']=el"
                  :detail="detailData"
                  :basic-info-data="basicInfoData"
                  :dictionary-list="dictionaryList"
                  :is-supplemented="true"
                  @get-approval-info-data="getApprovalInfoData"
                />
              </div>
            </el-collapse-item>
            <el-collapse-item v-show="['05','06','07','00'].includes(basicInfoData?.baseProjSetProg)||baseProjSetYear*1<2023" name="6" class="mb-16">
              <template #title>
                <div class="collapse-title">项目采购、资金支付信息</div>
              </template>
              <div class="pb-24">
                <purchase-info
                  :ref="el=>formRefs['procures']=el"
                  :detail="detailData"
                  :dictionary-list="dictionaryList"
                  :base-proj-set-year="baseProjSetYear"
                  :basic-info-data="basicInfoData"
                  :is-supplemented="true"
                />
              </div>
            </el-collapse-item>
            <el-collapse-item name="7" class="mb-16">
              <template #title>
                <div class="collapse-title">实施材料信息</div>
              </template>
              <div class="pb-24">
                <emp-materials
                  :ref="el=>formRefs['cimplement']=el"
                  :detail="detailData"
                  :basic-info-data="basicInfoData"
                  :base-proj-set-year="baseProjSetYear"
                  :approval-info-data="approvalInfoData"
                  :is-supplemented="true"
                />
              </div>
            </el-collapse-item>
          </el-collapse>
        </template>
      </el-form>
    </el-card>
  </div>
  <div class="footer">
    <el-button
      type="primary"
      @click="submitForm(ruleFormRef)"
    >
      提交
    </el-button>
    <el-button @click="router.go(-1)">返回</el-button>
  </div>
</template>

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