<script name="declarePage" setup>
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue'
import { getFormConfig } from '@/http/apis/systemManage/formConfiguration'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import store from '@/store'
import BasicInfo from './components/basicInfo.vue'
import FundsInfo from './components/fundsInfo.vue'
import FundsAllocation from './components/fundsAllocation.vue'
import AnnualPaymentPlan from './components/annualPaymentPlan.vue'
import CoreBusiness from './components/coreBusiness.vue'
import SafetyInput from './components/safetyInput.vue'
import ProjectImageProgress from './components/projectImageProgress.vue'
import Accessory from './components/accessory.vue'
import ProjectRemark from './components/projectRemark.vue'
import NewModuleForm from './components/newModuleForm.vue'
import Applications from './components/applications.vue'
import HiddenAppForm from './components/hiddenAppForm.vue'
import FlowRecordDialog from '@/pages/projectStoreManage/projectStore/projectDetail/components/flowRecordDialog.vue'
import { declareConstructionScheme, getDraftDetail, projectStart, saveDraft } from '@/http/apis/declareMange'
import { projectDetail } from '@/http/apis/projectStoreManage/projectStore'
import { annualPlanModify } from '@/http/apis/projectStoreManage/annualPlanStore'
import { adjustAndHandle, progressDetail } from '@/http/apis/toDoCenter/todoList'
import { changFilesParam, reviewFileParam } from '@/utils/uploadAction'
import { dictionary } from '@/http/apis/projectCollection/projectCollectionEnter'
import ReviewCheck from '@/pages/declareManage/projectDeclare/declarePage/components/reviewCheck.vue'
import { getIsShowReviewCheck } from '@/utils/getIsShowReviewCheck'
import ProvincialExamine from '@/pages/declareManage/projectDeclare/declarePage/components/provincialExamine.vue'

const { proxy } = getCurrentInstance(),
  route = useRoute(),
  router = useRouter(),
  userInfo = storeToRefs(store.userStore).userInfo || {},
  formConfig = ref({}),
  collapseModal = ref(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']),
  basicInfoRef = ref(), // 基本信息
  fundsInfoRef = ref(), // 资金申报情况
  fundsAllocationRef = ref(), // 资金分配情况
  provincialExamineRef = ref(), // 重大项目省级联审
  annualPaymentPlanRef = ref(), // 年度计划支付
  coreBusinessRef = ref(), // 核心业务
  safetyInputRef = ref(), // 安全投入
  projectImageProgressRef = ref(), // 工程形象进度
  accessoryRef = ref(), // 附件
  projectRemarkRef = ref(), // 备注
  newModuleformRef = ref({}), // 新增模块
  applicationsRef = ref(), // 应用
  hiddenAppFormRef = ref(),
  reviewCheckRef = ref(), // 审查清单
  // 提交
  submitAllForm = () => {
    const form = []
    if (basicInfoRef.value.formData?.baseProjIsConfidentiality === '02') {
      form.push(new Promise((resolve, reject) => {
        basicInfoRef.value.validForm((valid) => {
          if (valid) {
            resolve()
          }
        })
      }))
    } else {
      form.push(new Promise((resolve, reject) => {
        basicInfoRef.value.validForm((valid) => {
          if (valid) {
            if (fundsInfoRef.value.formData.declareAmount >= 1000 && basicInfoRef.value.formData.baseProvManDeprtType === '2') {
              basicInfoRef.value.formData.baseProvManDeprtType = ''
              reject('根据《浙江省电子政务重大应用项目联审》要求：大于1000万元的重大项目将由省级数改牵头部门及业务主管单位进行联审，请将上级主管单位修改为您对应条线的省级主管单位。')
            } else {
              resolve()
            }
          }
        })
      }))
      form.push(new Promise((resolve, reject) => {
        fundsInfoRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      form.push(new Promise((resolve, reject) => {
        fundsAllocationRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))

      form.push(new Promise((resolve, reject) => {
        annualPaymentPlanRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      formConfig.value.isCoreBusiness && form.push(new Promise((resolve, reject) => {
        coreBusinessRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      formConfig.value.isSafetyInput && form.push(new Promise((resolve, reject) => {
        safetyInputRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      formConfig.value.isProjectImageProgress && form.push(new Promise((resolve, reject) => {
        projectImageProgressRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      getIsShowReviewCheck() && formConfig.value.isReviewChecklist && (route.name === 'declarePlan' || [10012, 10013, 10016].includes(detailData.value?.status)) && form.push(new Promise((resolve, reject) => {
        reviewCheckRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      form.push(new Promise((resolve, reject) => {
        accessoryRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))
      for (const key in newModuleformRef.value) {
        form.push(new Promise((resolve, reject) => {
          newModuleformRef.value[key].validForm((valid) => {
            if (valid) resolve()
          })
        }))
      }
      applicationsRef.value && form.push(new Promise((resolve, reject) => {
        applicationsRef.value.validForm((valid) => {
          if (valid) resolve()
        })
      }))

      form.push(new Promise((resolve, reject) => {
        fundsInfoRef.value.validForm((valid) => {
          if (valid) {
            const total = floatAdd([fundsInfoRef.value.formData.declareHaveAmount, fundsInfoRef.value.formData.declareGovOwnFinanceAmount, fundsInfoRef.value.formData.declareGovSuperiorFinanceAmount, fundsInfoRef.value.formData.declareBankLendingAmount, fundsInfoRef.value.formData.declareOtherAmount])
            if (fundsInfoRef.value.formData.declareAmount > 0 && fundsInfoRef.value.formData.declareAmount === total) { resolve() } else {
              reject('资金申报情况：5类资金总和必须等于申报金额')
            }
          }
        })
      }))
      form.push(new Promise((resolve, reject) => {
        fundsAllocationRef.value.validForm(valid => {
          if (valid) {
            const total = floatAdd([fundsAllocationRef.value.formData.softwareDevelopmentAmount, fundsAllocationRef.value.formData.cloudHardwarePurchaseAmount, fundsAllocationRef.value.formData.thirdPartyAmount])
            if (fundsInfoRef.value.formData.declareAmount > 0 && fundsInfoRef.value.formData.declareAmount === total) { resolve() } else {
              reject('资金分配情况：3类资金总和必须等于申报金额')
            }
          }
        })
      }))
      applicationsRef.value?.formData.includeApplication === 1 && form.push(new Promise((resolve, reject) => {
        hiddenAppFormRef.value.validAllAppForm((valid) => {
          if (valid) {
            resolve()
          } else {
            reject('请完善已添加的应用信息')
          }
        })
      }))
    }
    Promise.all([...form]).then(async () => {
      if (basicInfoRef.value.formData?.baseProjIsConfidentiality === '02') {
        saveData(1)
      } else {
        if (formConfig.value.isSafetyInput) {
          const num = safetyInputRef.value?.formData.safetyInput.reduce((acc, cur) => acc + cur.safetyInputAmount, 0)
          const precent = (num / fundsInfoRef.value.formData.declareAmount) * 100
          if (precent < 5) {
            proxy.$messageBox
              .confirm(`当前安全投入占比低于5%，确认要提交吗?`, '确认要提交吗？', {
                type: 'warning'
              })
              .then(async () => {
                saveData(1)
              })
          } else {
            saveData(1)
          }
        } else {
          saveData(1)
        }
      }
    }).catch(err => {
      if (err) {
        proxy.$message.warning(err)
      }
    })
  },
  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
  },
  // 保存草稿
  toSaveDraft = async () => {
    saveData(2)
  },
  // 设置应用是否填写完全的值
  changeIsFirst = (val) => {
    if (applicationsRef.value?.formData && applicationsRef.value?.formData.includeApplication === 1 && applicationsRef.value?.formData?.applicationList?.length) {
      applicationsRef.value.formData.applicationList = applicationsRef.value.formData?.applicationList?.map(data => {
        return {
          ...data,
          applicationName: val ? data.applicationName : undefined,
          relatedExistsApplication: !val ? data.relatedExistsApplication : undefined,
          relatedExistsApplicationCode: !val ? data.relatedExistsApplication : undefined
        }
      })
    }
  },
  saveLoading = ref(false),
  submitLoading = ref(false),
  saveData = async (type) => {
    // const buildBasis = basicInfoRef.value.formData?.buildBasis?.map(i => {
    //   return {
    //     ...i,
    //     fileList: changFilesParam(i.fileList),
    //     fileName: i.fileList?.[0].name || ''
    //   }
    // })
    var postData = {}
    if (basicInfoRef.value.formData?.baseProjIsConfidentiality === '02') {
      postData = {
        isRemarks: formConfig.value.isRemarks,
        isOpenCoreBusiness: formConfig.value.isCoreBusiness,
        isOpenSafetyInput: formConfig.value.isSafetyInput,
        isEngineeringSpeed: formConfig.value.isProjectImageProgress,
        isReviewChecklist: formConfig.value.isReviewChecklist,
        id: route.query.id * 1 || undefined,
        baseProjIsConfidentiality: basicInfoRef.value.formData?.baseProjIsConfidentiality,
        projectName: basicInfoRef.value.formData?.projectName,
        projectType: basicInfoRef.value.formData?.projectType,
        baseConstructionType: basicInfoRef.value.formData?.baseConstructionType?.join('；') || '',
        responsibleMan: basicInfoRef.value.formData?.responsibleMan,
        responsibleManMobile: basicInfoRef.value.formData?.responsibleManMobile,
        contactName: basicInfoRef.value.formData?.contactName,
        contactPhone: basicInfoRef.value.formData?.contactPhone,
        buildOrgName: basicInfoRef.value.formData?.buildOrgName,
        orgCreditCode: basicInfoRef.value.formData?.orgCreditCode,
        baseProvManDeprtType: basicInfoRef.value.formData.baseProvManDeprtType * 1 || undefined,
        higherSuperOrg: basicInfoRef.value.formData?.higherSuperOrg,
        higherSuperOrgCode: basicInfoRef.value.formData?.higherSuperOrgCode,
        superOrg: basicInfoRef.value.formData?.superOrg,
        superOrgCode: basicInfoRef.value.formData?.superOrgCode,
        superOrgCreditCode: basicInfoRef.value.formData?.superOrgCreditCode,
        projectYear: basicInfoRef.value.formData?.projectYear * 1,
        declareAmount: basicInfoRef.value.formData?.declareAmount,
        annualPlanAmount: basicInfoRef.value.formData?.declareAmount
      }
    } else {
      postData = {
        isRemarks: formConfig.value.isRemarks,
        isOpenCoreBusiness: formConfig.value.isCoreBusiness,
        isOpenSafetyInput: formConfig.value.isSafetyInput,
        isEngineeringSpeed: formConfig.value.isProjectImageProgress,
        isReviewChecklist: formConfig.value.isReviewChecklist,
        id: route.query.id * 1 || undefined,
        ...basicInfoRef.value.formData,
        ...fundsInfoRef.value.formData,
        ...fundsAllocationRef.value.formData,
        bizDomain: basicInfoRef.value.formData?.isDigitalReform === 1 ? basicInfoRef.value.formData.bizDomain.join(',') : undefined,
        baseConstructionType: basicInfoRef.value.formData?.baseConstructionType?.join('；') || '',
        baseProvManDeprtType: basicInfoRef.value.formData.baseProvManDeprtType * 1 || undefined,
        projectYear: fundsInfoRef.value.formData?.projectYear * 1,
        beginTime: basicInfoRef.value.formData?.buildDuration?.length && basicInfoRef.value.formData.buildDuration[0],
        endTime: basicInfoRef.value.formData?.buildDuration?.length && basicInfoRef.value.formData.buildDuration[1],
        buildDuration: undefined,
        lowestLevel: !(basicInfoRef.value.formData?.baseConstructionType?.includes('03') && !basicInfoRef.value.formData?.baseConstructionType?.includes('01')) && basicInfoRef.value.formData?.lowestLevel || '',
        // buildBasis: buildBasis && JSON.stringify(buildBasis),
        baseProjBasis: basicInfoRef.value.formData?.baseProjBasis?.map(i => i.value)?.join('；') || undefined,
        baseProjBasisFile: basicInfoRef.value.formData?.baseProjBasis?.map(i => i.fileList && JSON.stringify(changFilesParam(i.fileList)))?.join('；') || '',
        cloudType: basicInfoRef.value.formData?.isCloud && basicInfoRef.value.formData?.cloudType?.length && basicInfoRef.value.formData.cloudType.join(',') || undefined,
        baseHistorProjId: basicInfoRef.value.formData?.baseHistorProjs?.map(i => i.baseProjId)?.join('；') || '',
        baseHistorProjName: basicInfoRef.value.formData?.baseHistorProjs?.map(i => i.baseProjName)?.join('；') || '',
        baseHistorProjYear: basicInfoRef.value.formData?.baseHistorProjs?.map(i => i.baseProjSetYear)?.join('；') || '',
        baseHistorProjs: undefined,
        beseExpectedResults: basicInfoRef.value.formData?.beseExpectedResults?.length && JSON.stringify(basicInfoRef.value.formData.beseExpectedResults) || '',
        baseBasisAmountOri: fundsInfoRef.value?.formData.declareOtherAmount > 0 && fundsInfoRef.value.formData?.baseBasisAmountOri || '',
        consultancy: fundsInfoRef.value?.formData.declareAmount > 400 && fundsInfoRef.value.formData?.consultancy || '',
        operationManageUnit: fundsInfoRef.value?.formData.declareAmount >= 1000 && provincialExamineRef.value.formData.operationManageUnit || undefined,
        ...applicationsRef.value?.formData,
        ...annualPaymentPlanRef.value.formData,
        ...accessoryRef.value.formData,
        constructionPlanFile: accessoryRef.value.formData?.constructionPlanFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.constructionPlanFile)),
        preliminaryPlanFile: accessoryRef.value.formData?.preliminaryPlanFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.preliminaryPlanFile)),
        mainResponsibilitiesApplicantFile: accessoryRef.value.formData?.mainResponsibilitiesApplicantFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.mainResponsibilitiesApplicantFile)),
        supportingMaterialsFile: accessoryRef.value.formData?.supportingMaterialsFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.supportingMaterialsFile)),
        calculationTotalInvestmentFile: accessoryRef.value.formData?.calculationTotalInvestmentFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.calculationTotalInvestmentFile)),
        projectApplicationForm: basicInfoRef.value.formData?.projectType !== '03' && accessoryRef.value.formData?.projectApplicationForm && JSON.stringify(changFilesParam(accessoryRef.value.formData.projectApplicationForm)) || '',
        baseResearchReportFile: basicInfoRef.value.formData?.projectType !== '03' && accessoryRef.value.formData?.baseResearchReportFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.baseResearchReportFile)) || '',
        baseProjOtherFile: accessoryRef.value.formData?.baseProjOtherFile && JSON.stringify(changFilesParam(accessoryRef.value.formData.baseProjOtherFile)),
        mainAccusationDoc: fundsInfoRef.value?.formData.declareAmount >= 1000 && accessoryRef.value.formData?.mainAccusationDoc && JSON.stringify(changFilesParam(accessoryRef.value.formData.mainAccusationDoc)) || '',
        reviewChecklist: reviewCheckRef.value?.formData?.reviewChecklist || undefined
      }
      if (formConfig.value.isCoreBusiness) {
        postData = Object.assign(postData, { ...coreBusinessRef.value.formData, coreBusiness: coreBusinessRef.value.formData.coreBusiness && JSON.stringify(coreBusinessRef.value.formData.coreBusiness) })
      }
      if (formConfig.value.isSafetyInput) {
        // ...safetyInputRef.value.formData
        postData = Object.assign(postData, {
          safetyInputDescribe: JSON.stringify(safetyInputRef.value.formData.safetyInput)
        })
      }
      if (formConfig.value.isProjectImageProgress) {
        postData = Object.assign(postData, { ...projectImageProgressRef.value.formData })
      }
      if (formConfig.value.isRemark) {
        postData = Object.assign(postData, { ...projectRemarkRef.value.formData })
      }
      if (applicationsRef.value?.formData?.includeApplication && applicationsRef.value?.formData.applicationList?.length) {
        postData.applicationList = applicationsRef.value.formData.applicationList.map(i => {
          return {
            ...i,
            isFirst: !basicInfoRef.value.formData?.isFirst ? 0 : 1,
            relatedExistsApplication: ((!basicInfoRef.value.formData?.isFirst && userInfo.value.regionCode === '331123') || userInfo.regionCode !== '331123') && i.relatedExistsApplication?.applicationName || undefined,
            relatedExistsApplicationCode: ((!basicInfoRef.value.formData?.isFirst && userInfo.value.regionCode === '331123') || userInfo.regionCode !== '331123') && i.relatedExistsApplicationCode || undefined,
            applicationName: (basicInfoRef.value.formData?.isFirst && userInfo.regionCode === '331123') && i.applicationName || undefined,
            coreBusinessList: i.coreBusinessList.map(j => {
              return {
                ...j,
                projectId: detailData.value?.projectId || undefined,
                projectCode: detailData.value?.projectCode || undefined
              }
            })
          }
        })
      }
      if (formConfig.value.safetyInputModular?.length) {
        postData.safetyInputModular = []
        for (const key in newModuleformRef.value) {
          postData.safetyInputModular.push(
            newModuleformRef.value[key].formData
          )
        }
        const safetyInputModular = postData.safetyInputModular.map(i => {
          return {
            ...i,
            formList: i.formList.map(j => {
              return {
                ...j,
                value: !j.value ? undefined : j.props.type === '文件上传' ? changFilesParam(j.value) : j.value
              }
            })
          }
        })
        postData.safetyInputModular = JSON.stringify(safetyInputModular)
      } else {
        postData.safetyInputModular = undefined
      }
    }

    if (type === 1) {
      submitLoading.value = true
      try {
        const data = {
          projectInfo: { ...postData, id: !route.query.isDraft ? postData.id : undefined, draftId: route.query.isDraft ? route.query.id * 1 : undefined }
        }

        if (route.name === 'declarePage') {
          await projectStart(!route.query.isDraft && route.query.id ? 2 : 1, data)// 申报
        } else if (route.name === 'planEdit') {
          await annualPlanModify(data.projectInfo) // 年度计划编辑
        } else if (route.name === 'handleAfterGiveBack') {
          await adjustAndHandle({
            ...data,
            projectId: route.query.id,
            instanceId: route.query.instanceId,
            taskId: route.query.taskId
          })
        } else if (route.name === 'declarePlan') {
          await declareConstructionScheme(data)
        }
        proxy.$message.success('提交成功')
        submitLoading.value = false
        if (route.name === 'projectDeclare') {
          router.push({ name: 'projectDeclare' })
        } else {
          router.go(-1)
        }
      } catch (e) {
        submitLoading.value = false
      }
    } else if (type === 2) {
      saveLoading.value = true
      try {
        await saveDraft({
          projectInfo: { ...postData },
          user: userInfo.value // 测试需要
        })
        proxy.$message.success('保存成功')
        saveLoading.value = false
        router.go(-1)
      } catch (e) {
        saveLoading.value = false
      }
    }
  },
  // 回显
  detailData = ref({}),
  // allApplicationsDone = ref(1), // 所有应用信息校验字段
  setData = () => {
    basicInfoRef.value.setFormData(detailData.value)
    if (detailData.value?.baseProjIsConfidentiality !== '02') {
      fundsInfoRef.value.setFormData(detailData.value)
      fundsAllocationRef.value.setFormData(detailData.value)
      annualPaymentPlanRef.value.setFormData(detailData.value)
      formConfig.value.isCoreBusiness && coreBusinessRef.value.setFormData(detailData.value)
      formConfig.value.isSafetyInput && safetyInputRef.value.setFormData(detailData.value)
      formConfig.value.isProjectImageProgress && projectImageProgressRef.value.setFormData(detailData.value)
      accessoryRef.value.setFormData(detailData.value)
      formConfig.value.isRemark && projectRemarkRef.value.setFormData(detailData.value)
      // detailData.value.safetyInputModular?.length && newModuleformRef.value.setFormData(detailData.value)
      applicationsRef.value?.setFormData(detailData.value)
      setTimeout(() => {
        provincialExamineRef.value?.setFormData(detailData.value)
      })
    }
  },
  // 被退回处理
  // 获取审核详情
  flowData = ref({
    processProgressVo: {
      progressInfo: [
      ]
    }
  }),
  lastData = ref(),
  getFlowData = async () => {
    const res = await progressDetail({ instanceId: route.query.instanceId, projectId: route.query.id, nodeId: route.query.nodeId })
    flowData.value = {
      ...res.data,
      processProgressVo: {
        ...res.data.processProgressVo,
        progressInfo: changeProgressInfo(res.data.processProgressVo.progressInfo)
      }
    }
    lastData.value = flowData.value.processProgressVo.progressInfo.slice(-1)[0]?.children?.slice(-1)[0] || flowData.value.processProgressVo.progressInfo.slice(-1)[0]
  },
  // 审核记录
  flowRecordDialogData = reactive({
    visible: false,
    flowData: undefined
  }),
  showFlowRecordDialog = (data) => {
    flowRecordDialogData.visible = true
    flowRecordDialogData.flowData = flowData.value.processProgressVo.progressInfo
  },
  changeProgressInfo = (data) => {
    data.forEach(res => {
      if (res.children) {
        const nodeIds = []
        const newChildren = []
        res.children.forEach(child => {
          if (!nodeIds.includes(child.nodeId)) {
            nodeIds.push(child.nodeId)
            newChildren.push({
              nodeId: child.nodeId,
              approvalMode: child.approvalMode,
              name: child.name,
              taskId: child.taskId,
              nodeType: child.nodeType,
              list: [{ ...child }],
              userIds: [child.userId]
            })
          } else {
            newChildren.find(i => i.nodeId === child.nodeId).list.push(child)
            newChildren.find(i => i.nodeId === child.nodeId).userIds.push(child.userId)
          }
        })
        res.children = newChildren
      } else {
        res['userIds'] = [res.userId]
      }
    })
    return data
  },
  closeFlowRecordDialog = () => {
    flowRecordDialogData.visible = false
  },
  dictionaryList = ref([]),
  basicInfoData = ref(),
  getBasicInfoData = (data) => {
    basicInfoData.value = data
  }
onMounted(async () => {
  dictionaryList.value = (await dictionary()).data
  if (!route.query.id) {
    const res = await getFormConfig({
      regionCode: userInfo.value.regionCode
    })
    formConfig.value = {
      isCoreBusiness: res.data.isCoreBusiness,
      isProjectImageProgress: res.data.isProjectImageProgress,
      isRemark: res.data.isRemark,
      isSafetyInput: res.data.isSafetyInput,
      safetyInputModular: res.data.safetyInputModular || []
    }
  } else {
    var res = {}, res1 = {}, reviewChecklist = [], isReviewChecklist = false
    if (route.query?.isDraft) {
      res = await getDraftDetail({ id: route.query.id })
    } else {
      res = await projectDetail(route.query.id)
      res1 = await getFormConfig({
        regionCode: userInfo.value.regionCode
      })
      if ((route.name === 'declarePlan' || [10012, 10013, 10016].includes(detailData.value?.status))) {
        isReviewChecklist = res.data.reviewChecklist && JSON.parse(res.data.reviewChecklist)?.length ? true : res1.data.isReviewChecklist
        reviewChecklist = res1.data.reviewChecklist && JSON.parse(res1.data.reviewChecklist) || []
      }
    }
    detailData.value = {
      ...res.data,
      reviewChecklist: res.data.reviewChecklist ? JSON.parse(res.data.reviewChecklist) : undefined
    }
    const safetyInputModular = res.data.safetyInputModular && JSON.parse(res.data.safetyInputModular).map(i => {
      return {
        ...i,
        formList: i.formList.map(j => {
          return {
            ...j,
            value: !j.value ? undefined : j.props.type === '文件上传' ? reviewFileParam(j.value) : j.value
          }
        })
      }
    })
    formConfig.value = {
      isCoreBusiness: res.data.isOpenCoreBusiness,
      isProjectImageProgress: res.data.isEngineeringSpeed,
      isRemark: res.data.isRemark,
      isSafetyInput: res.data.isOpenSafetyInput,
      safetyInputModular: safetyInputModular || [],
      isReviewChecklist,
      reviewChecklist
    }
    nextTick(() => {
      setData()
    })
    if (route.name === 'handleAfterGiveBack') {
      getFlowData()
    }
  }

  if (formConfig.value.safetyInputModular?.length) {
    let index = 11
    formConfig.value.safetyInputModular.forEach(i => {
      collapseModal.value.push(index++ + '')
    })
  }
})
</script>
<template>
  <div class="declarePage footerPage">
    <!--    退回编辑-->
    <div v-if="route.name==='handleAfterGiveBack'" class="errorTip mb-16">
      <el-icon class="icon"><Warning /></el-icon>
      <div>
        <p class="title">流程被退回</p>
        <p>
          <span>{{ detailData?.projectName }}的{{ flowData?.processProgressVo?.processDefName }}被退回，请根据审核记录调整项目信息</span>
          <el-button
            type="primary"
            plain
            size="small"
            class="ml-16"
            @click="showFlowRecordDialog"
          >查看审核记录</el-button>
        </p>
      </div>

    </div>

    <!--    建设方案申报-->
    <el-card v-if="route.name==='declarePlan'" shadow="never" class="mb-16">
      <div class="card-header">
        <div class="flex justify-between items-center">
          <div class="flex-1">
            <p class="font-bold">{{ detailData.projectName }}</p>
            <div class="mt-8 search">
              <el-form label-suffix=":">
                <el-row :gutter="24">
                  <el-col :span="6">
                    <el-form-item label="申报单位">{{ detailData.buildOrgName||'-' }}</el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="主管单位">{{ detailData.superOrg||'-' }}</el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="创建时间">{{ detailData.createOn||'-' }}</el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    <el-row>
      <el-col class="leftCol" :span="24">
        <el-collapse v-model="collapseModal">
          <el-collapse-item name="1" class="mb-16">
            <template #title>
              <div class="collapse-title">基本信息</div>
            </template>
            <div class="p-24">
              <basic-info
                ref="basicInfoRef"
                :detail-data="detailData"
                :dictionary-list="dictionaryList"
                :declare-amount="fundsInfoRef?.formData.declareAmount"
                @change-is-first="changeIsFirst"
                @get-basic-info-data="getBasicInfoData"
              />
            </div>
          </el-collapse-item>
          <template v-if="basicInfoRef?.formData?.baseProjIsConfidentiality==='01'">
            <el-collapse-item v-if="basicInfoRef?.formData?.baseProjIsConfidentiality==='01'" name="2" class="mb-16">
              <template #title>
                <div class="collapse-title">
                  <span>资金申报情况（单位：万元）</span>
                  <span class="text-info">申报金额 = 自有资金 + 政府投资-本级财政资金 + 政府投资-上级补助资金 + 银行贷款 + 其他资金</span>
                </div>
              </template>
              <div class="p-24">
                <funds-info ref="fundsInfoRef" :detail-data="detailData" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="basicInfoRef?.formData?.baseProjIsConfidentiality==='01'" name="3" class="mb-16">
              <template #title>
                <div class="collapse-title">
                  资金分配情况（单位：万元）
                  <span class="text-info">软件开发 + 云资源、硬件配置 + 第三方服务 = 申报金额</span>
                </div>
              </template>
              <div class="p-24">
                <funds-allocation ref="fundsAllocationRef" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="fundsInfoRef?.formData.declareAmount>=1000&&basicInfoRef?.formData?.baseProjIsConfidentiality==='01'" name="10" class="mb-16">
              <template #title>
                <div class="collapse-title">
                  重大项目省级联审信息
                </div>
              </template>
              <div class="p-24">
                <provincial-examine ref="provincialExamineRef" />
              </div>
            </el-collapse-item>
            <el-collapse-item
              v-if="basicInfoRef?.formData?.baseProjIsConfidentiality==='01'"
              name="4"
              class="mb-16"
            >
              <template #title>
                <div class="collapse-title">
                  年度支付计划（单位：万元）
                  <span class="text-info">年度支付金额 = 自有资金 + 政府投资-本级财政资金 + 政府投资-上级补助资金 + 银行贷款 + 其他资金</span>
                </div>
              </template>
              <div class="p-24">
                <annual-payment-plan ref="annualPaymentPlanRef" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="formConfig.isCoreBusiness" name="5" class="mb-16">
              <template #title>
                <div class="collapse-title">核心业务</div>
              </template>
              <div class="p-24">
                <core-business ref="coreBusinessRef" :basic-info-data="basicInfoRef?.formData" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="formConfig.isSafetyInput" name="6" class="mb-16">
              <template #title>
                <div class="collapse-title">安全投入</div>
              </template>
              <div class="p-24">
                <safety-input ref="safetyInputRef" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="formConfig.isProjectImageProgress" name="7" class="mb-16">
              <template #title>
                <div class="collapse-title">工程形象进度</div>
              </template>
              <div class="p-24">
                <projectImageProgress ref="projectImageProgressRef" />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="getIsShowReviewCheck()&&formConfig.isReviewChecklist&&($route.name==='declarePlan'||[10012,10013,10016].includes(detailData?.status))" name="8" class="mb-16">
              <template #title>
                <div class="collapse-title">审查清单</div>
              </template>
              <div class="p-24">
                <review-check ref="reviewCheckRef" :detail-data="detailData" :data="detailData.reviewChecklist||formConfig.reviewChecklist" />
              </div>
            </el-collapse-item>
            <el-collapse-item name="8" class="mb-16">
              <template #title>
                <div class="collapse-title">附件</div>
              </template>
              <div class="p-24">
                <accessory
                  ref="accessoryRef"
                  :detail-data="detailData"
                  :project-type="basicInfoRef?.formData?.projectType"
                  :declare-amount="fundsInfoRef?.formData.declareAmount"
                />
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="formConfig.isRemark" name="9" class="mb-16">
              <template #title>
                <div class="collapse-title">备注</div>
              </template>
              <div class="p-24">
                <projectRemark ref="projectRemarkRef" />
              </div>
            </el-collapse-item>
            <template v-if="formConfig.safetyInputModular?.length">
              <el-collapse-item
                v-for="(item,index) in formConfig.safetyInputModular"
                :key="index"
                :name="11+index+''"
                class="mb-16"
              >
                <template #title>
                  <div class="collapse-title">{{ item.moduleName }}</div>
                </template>
                <div class="p-24">
                  <newModuleForm :ref="el => {newModuleformRef[item.id] = el}" :data="item" />
                </div>
              </el-collapse-item>
            </template>
            <el-collapse-item
              v-if="($route.name==='declarePlan')||([10012,10016,10013].includes(detailData.status))"
              name="4"
              class="mb-16"
            >
              <template #title>
                <div class="collapse-title">应用信息</div>
              </template>
              <div class="p-24">
                <applications ref="applicationsRef" :is-first="basicInfoRef?.formData?.isFirst" :core-business="coreBusinessRef?.formData?.coreBusiness" />
              </div>
            </el-collapse-item>
          </template>
        </el-collapse>
      </el-col>
    </el-row>
    <hidden-app-form
      ref="hiddenAppFormRef"
      :application-list="applicationsRef?.formData?.applicationList"
      :is-first="basicInfoRef?.formData?.isFirst"
    />
    <div class="footer">
      <el-button @click="router.go(-1)"> 返回 </el-button>
      <el-button
        v-if="route.name==='declarePage'&&(!route.query.id||(route.query.id&&route.query.isDraft))"
        plain
        type="primary"
        :loading="saveLoading"
        @click="toSaveDraft"
      > 暂 存 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitAllForm"> 提交审核 </el-button>
    </div>
  </div>
  <flow-record-dialog :visible="flowRecordDialogData.visible" :flow-data="flowRecordDialogData.flowData" @close="closeFlowRecordDialog" />
</template>
<style lang="less" scoped>
.declarePage {
  //position: relative;

  .errorTip{
    background: #FFF0EF;
    border-radius: 4px;
    border: 1px solid #FF9E99;
    padding: 18px 24px;
    display: flex;
    font-size: 14px;
    color: rgba(0,0,0,0.85);
    .icon{
      color:#FF3B30;
      font-size: 24px;
      margin-right: 8px;
    }
    .title{
      font-size: 20px;
      font-weight: 500;
      color: rgba(0,0,0,0.85);
      line-height: 28px;
      margin-bottom: 17px;
    }
  }
}
:deep(.el-collapse) {
  .el-collapse-item__header {
    padding: 0px 16px;
    font-size: 14px;
  }
  .el-collapse-item__content {
    padding: 16px 16px 16px 0px;
  }
  .el-collapse-item__header.is-active {
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  }
  .collapse-title {
    flex: 1 0 90%;
    order: 1;
    .el-collapse-item__header {
      flex: 1 0 auto;
      order: -1;
    }
    .el-input-number {
      width: 150px !important;
    }
  }
}
.btnClass {
  :deep(.el-form-item__content) {
    line-height: 24px;
  }
}

.marginTop {
  margin-top: 16px;
}
.delClass {
  color: #e65151;
}
.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(0, 100, 235, 1);
  width: 100%;
  padding: 2px 0px;
  border-radius: 4px;
  border: 1px solid rgba(0, 100, 235, 1);
  cursor: pointer;
}
.bottomBtn {
  width: calc(100% - 201px);
  position: fixed;
  z-index: 999;
  right: 0px;
  bottom: 0px;
  background: #fff;
  padding: 10px 0px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.applyBottomBtn {
  width: 1000px;
  position: fixed;
  z-index: 999;
  right: 0px;
  bottom: 0px;
  background: #fff;
  padding: 10px 0px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.ocupation{
  height: 80px;
}
</style>
