<script name="projectCollectionEnter" setup>
import BasicInfo from './components/basicInfo.vue'
import { getCurrentInstance, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { changFilesParam } from '@/utils/uploadAction'
import ProjectDeclareInfo from './components/projectDeclareInfo.vue'
import ApplicationInfo from './components/applicationInfo.vue'
import CoreBusiness from './components/coreBusiness.vue'
import ProjectApprovalInfo from './components/projectApprovalInfo.vue'
import PurchaseInfo from './components/purchaseInfo.vue'
import EmpMaterials from './components/empMaterials.vue'
import { dictionary } from '@/http/apis/projectCollection/projectCollectionEnter'
import { detail, save, draftSave } from '@/http/apis/declareMange/operationProjectRecord'

const { proxy } = getCurrentInstance(),
  route = useRoute(),
  router = useRouter(),
  collapseModal = ['1', '2', '3', '4', '5', '6', '7'],
  formRefs = {},
  submitLoading = ref(false),
  dictionaryList = ref(),
  detailData = ref(),
  getDetail = async () => {
    const id = route.query.type === '1' ? route.query.id : route.query.draftId
    const res = await detail(route.query.type, id)
    detailData.value = res.data
  },
  submit = async () => {
    submitLoading.value = true
    try {
      const arr = Object.values(formRefs).map(async i => i?.formRef && await i.formRef.validate())
      await Promise.all(arr)
      const postData = changePostData()
      // const postData = changePostData()
      // console.log(postData)
      // const formData = formRefs.map(i => i.formData).reduce((result, obj) => ({ ...result, ...obj }), {})
      await save(postData)
      submitLoading.value = false
      proxy.$message.success('提交成功！')
      router.go(-1)
    } catch (e) {
      submitLoading.value = false
    }
  },
  basicInfoData = ref(),
  getBasicInfoData = (data) => {
    basicInfoData.value = data
  },
  baseProjSetYear = ref(),
  getProYear = (data) => {
    baseProjSetYear.value = data
  },
  approvalInfoData = ref(),
  getApprovalInfoData = (data) => {
    approvalInfoData.value = data
  },

  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: route.query.id || '',
      draftId: route.query.draftId * 1 || '',
      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 ? '' : apply?.baseHistorProjs?.map(i => i.baseProjId)?.join('；'),
        baseHistorProjName: apply?.missing ? '' : apply?.baseHistorProjs?.map(i => i.baseProjName)?.join('；'),
        baseHistorProjYear: apply?.missing ? '' : 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)) : '',
        baseOperatMaintenFile: apply?.baseOperatMaintenFile?.length ? JSON.stringify(changFilesParam(apply?.baseOperatMaintenFile)) : '',
        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
      },
      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)) : ''
        }
      }) || [],
      mimplement: {
        ...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) && 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)) : '',
        baseOperatMaintenSummFile: (['05', '06', '07', '00'].includes(baseinfo?.baseProjSetProg) || apply?.baseProjSetYear * 1 < 2023) && cimplement?.baseOperatMaintenSummFile?.length ? JSON.stringify(changFilesParam(cimplement.baseOperatMaintenSummFile)) : '',
        baseFinalExpertOpinionFile: baseinfo?.baseProjSetProg === '07' && cimplement.baseFinalExpertOpinionFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseFinalExpertOpinionFile)) : '',
        baseEngineerPostpoFile: cimplement?.baseEngineerPostpoFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseEngineerPostpoFile)) : '',
        baseEngineerAlterFile: cimplement?.baseEngineerAlterFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseEngineerAlterFile)) : '',
        baseChanFile: cimplement?.baseChanFile?.length ? JSON.stringify(changFilesParam(cimplement?.baseChanFile)) : '',
        baseBusinessMetrics: cimplement?.baseBusinessMetrics?.length ? JSON.stringify(cimplement?.baseBusinessMetrics) : ''
      }
    }
  },
  // 暂存
  saveLoading = ref(false),
  saveDraft = async () => {
    saveLoading.value = true
    const postData = changePostData()
    try {
      await draftSave(postData)
      saveLoading.value = false
      proxy.$message.success('暂存成功！')
      router.go(-1)
    } catch (e) {
      saveLoading.value = false
    }
  }
onMounted(async () => {
  dictionaryList.value = (await dictionary()).data
  if (route.query.id) getDetail()
})

</script>

<template>
  <div class="footerPage">
    <div>
      <el-collapse v-model="collapseModal">
        <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"
              @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"
              @get-pro-year="getProYear"
            />
          </div>
        </el-collapse-item>
        <el-collapse-item v-if="!(basicInfoData?.baseConstructionType?.length===1&&basicInfoData?.baseConstructionType.includes('02'))" 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" />
          </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" :basic-info-data="basicInfoData" />
          </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"
              @get-approval-info-data="getApprovalInfoData"
            />
          </div>
        </el-collapse-item>
        <el-collapse-item 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"
            />
          </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"
            />
          </div>
        </el-collapse-item>
        <div class="footer">
          <el-button @click="$router.go(-1)"> 返回 </el-button>
          <el-button
            v-if="route.query.type!=='1'"
            type="primary"
            :loading="saveLoading"
            plain
            @click="saveDraft"
          > 暂存 </el-button>
          <el-button type="primary" :loading="submitLoading" @click="submit"> 提交 </el-button>
        </div>
      </el-collapse></div>
  </div>
</template>
