<template>
  <div class="detail-block" v-loading="loading" :style="{padding:!formData.isSpecialFund?'0  30px':'0 0 0 30px'}">
    <baseTitle title="项目基本信息"></baseTitle>
    <el-form :model="formData" ref="summaryForm" :rules="rules" :label-width="!formData.isSpecialFund?130:160"
             :scroll-to-error="true">
      <el-row gutter="30" style="margin-bottom: -18px;"
              :style="{marginLeft:!formData.isSpecialFund?'-8.5px':'-48.5px'}">
        <el-col :span="6">
          <el-form-item label="承办单位">
            <Tooltip :content="authStore.userinfo?.subCompanyName" placement="bottom-start" width="240"
                     textAlign="left">
            </Tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'0':route.query.id?'':'-40px'}">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" placeholder="请输入项目名称" clearable
                      @change="changeCollectData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':route.query.id?'-40px':'0'}">
          <el-form-item label="开始时间" prop="startTime">
            <el-config-provider>
              <el-date-picker
                  v-model="formData.startTime"
                  type="date"
                  placeholder="开始时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%" @change="changeCollectData"
              />
            </el-config-provider>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':'-40px'}">
          <el-form-item label="结束时间" prop="endTime"
                        :title="!formData.startTime?'请先选择开始时间!':''">
            <el-config-provider>
              <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  placeholder="结束时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  :disabled="!formData.startTime"
                  :disabled-date="disabledDate" @change="changeCollectData"
              />
            </el-config-provider>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="formData.projectType" placeholder="请选择项目类型" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('project_type')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'0':route.query.id?'':'-40px'}">
          <el-form-item label="研发主体" prop="rdSubject">
            <el-select v-model="formData.rdSubject" placeholder="请选择研发主体" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('rd_subject')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':route.query.id?'-40px':'0'}">
          <el-form-item label="出资类型" prop="investmentType">
            <el-select v-model="formData.investmentType" placeholder="请选择出资类型" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('invest_type')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':'-40px'}">
          <el-form-item label="业务板块" prop="businessSegment">
            <el-select v-model="formData.businessSegment" placeholder="请选择所属业务板块" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('business_segment')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准制定" prop="technicalStandard">
            <el-select v-model="formData.technicalStandard" placeholder="请选择预期技术标准制定" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('technical_standard')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'0':route.query.id?'':'-40px'}">
          <el-form-item label="预估经费预算(元)" prop="economicEstimate">
            <el-input
                v-model="formData.economicEstimate"
                placeholder="请输入预估经费预算"
                clearable
                :formatter="(value) => value.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)+[^0-9.]/g, '')" @change="changeCollectData"
            />
            <!--            <el-input-number v-model="formData.economicEstimate" placeholder="请输入预估经费预算" :controls="false"/>-->
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':route.query.id?'-40px':'0'}">
          <el-form-item label="产学研联合" prop="industryUniversityResearch">
            <el-select v-model="formData.industryUniversityResearch" clearable placeholder="请选择产学研联合"
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('industry_university')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':'-40px'}">
          <el-form-item label="开展政府申报" prop="governmentDeclaration">
            <el-select v-model="formData.governmentDeclaration" clearable placeholder="请选择开展政府申报"
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('government_declaration')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="6" v-if="!route.query.id">
          <el-form-item label="是否专项资金" prop="isSpecialFund" required>
            <el-select v-model="formData.isSpecialFund" clearable @change="specialFundChange"
                       placeholder="请选择是否为专项资金">
              <el-option label="是" :value="true"/>
              <el-option label="否" :value="false"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="route.query.id && formData.isSpecialFund">
          <el-form-item label="专项资金名称" prop="specialFundId">
            <span>{{ formData.specialFund }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!route.query.id && formData.isSpecialFund"
                :style="{marginLeft:!formData.isSpecialFund?'0':route.query.id?'':'-40px'}">
          <el-form-item label="所属专项资金" prop="specialFundId">
            <el-select v-model="formData.specialFundId" placeholder="请选择专项资金名称" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in specialFundOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="formData.isSpecialFund">
          <el-form-item label="预估专项资金(元)" prop="forecastSpecialFundAmount">
            <el-input
                v-model="formData.forecastSpecialFundAmount"
                placeholder="请输入预估专项资金"
                clearable
                :formatter="(value) => value.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)+[^0-9.]/g, '')" @change="changeCollectData"
            />
            <!--            <el-input-number v-model="formData.forecastSpecialFundAmount" placeholder="请输入预估专项资金" :controls="false"/>-->
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'0':'-40px'}">
          <el-form-item label="是否在预算内" prop="isWithinBudget" required>
            <el-select v-model="formData.isWithinBudget" clearable placeholder="请选择是否在预算内"
                       @change="changeCollectData">
              <el-option label="是" :value="true"/>
              <el-option label="否" :value="false"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6"
                :style="{marginLeft:!formData.isSpecialFund?route.query.id?'0':'-10px':route.query.id?'-40px':'0'}">
          <el-form-item label="部门分管领导" prop="">
            <el-button color="#DED0B2" style="margin-right: 10px" @click="handleShowOptionalChargeLeadershipPicker">
              {{ optionalChargeLeadershipList.length !== 0 ? '更改' : '请选择' }}
            </el-button>
            <div v-for="(item,index) in optionalChargeLeadershipList" :key="item.id" style="margin-right: 5px">
              {{ item.name }}{{ index != optionalChargeLeadershipList?.length - 1 ? '，' : '' }}
            </div>
            <user-picker :multiple="true" ref="optionalChargeLeadershipPickerRef" title="请选择分管领导"
                         @cancelOrClear="optionalChargeLeaderPickerOkOrCancel"
                         v-model:value="optionalChargeLeadershipList" @ok="optionalChargeLeaderPickerOkOrCancel"/>
          </el-form-item>
        </el-col>
        <el-col :span="6"
                :style="{marginLeft:!formData.isSpecialFund?route.query.id?'-10px':'-10px':route.query.id?'0':'-40px'}">
          <el-form-item label="主项目" prop="masterProjectId">
            <el-select v-model="formData.masterProjectId" clearable placeholder="请选择主项目"
                       @change="changeCollectData">
              <el-option
                  v-for="item in masterProjectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?route.query.id?'-10px':'0':'0'}">
          <el-form-item label="需求征集" prop="" required>
            <template v-if="formData.requirementDefaultName">{{ formData.requirementDefaultName }}</template>
            <el-select v-else v-model="formData.requirementId" clearable placeholder="请选择需求征集"
                       @change="changeCollectData();changeRequirement()">
              <el-option
                  v-for="item in requirementList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <baseTitle title="预期知识产权"></baseTitle>
      <el-row gutter="30" style="margin-bottom: -18px;"
              :style="{marginLeft:!formData.isSpecialFund?'-8.5px':'-48.5px'}">
        <el-col :span="12">
          <el-form-item label="预期成果形式" prop="resultForm"
                        :style="{marginRight:!formData.isSpecialFund?'0':route.query.id?'':'40px'}">
            <el-select v-model="formData.resultForm" placeholder="请选择预期成果形式" clearable filterable multiple
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('result_form')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':'-40px'}">
          <el-form-item label="知识产权状况" prop="intellectualProperty">
            <el-select v-model="formData.intellectualProperty" placeholder="请选择知识产权状况" clearable filterable
                       @change="changeCollectData">
              <el-option
                  v-for="item in cacheStore.getDict('intellectual_property')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':'-40px'}">
          <el-form-item label="发明专利(项)" prop="inventionPatent">
            <el-input-number v-model="formData.inventionPatent" placeholder="请输入发明专利数量" :controls="false"
                             @change="changeCollectData"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="新型专利(项)" prop="newPatent">
            <el-input-number v-model="formData.newPatent" placeholder="请输入实用性新型专利数量" :controls="false"
                             @change="changeCollectData"
                             style="width: 100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'0':route.query.id?'':'-40px'}">
          <el-form-item label="软件著作权(项)" prop="softwareCopyright">
            <el-input-number v-model="formData.softwareCopyright" placeholder="请输入软件著作权数量" :controls="false"
                             @change="changeCollectData"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':route.query.id?'-40px':'0'}">
          <el-form-item label="著作权(项)" prop="copyright">
            <el-input-number v-model="formData.copyright" placeholder="请输入著作权数量" :controls="false"
                             @change="changeCollectData"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" :style="{marginLeft:!formData.isSpecialFund?'-10px':'-40px'}">
          <el-form-item label="其他(项)" prop="other">
            <el-input-number v-model="formData.other" placeholder="请输入其他数量" :controls="false"
                             @change="changeCollectData"/>
          </el-form-item>
        </el-col>
      </el-row>
      <baseTitle title="项目描述"></baseTitle>
      <el-row gutter="30" style="margin-bottom: -18px;"
              :style="{marginLeft:!formData.isSpecialFund?'-8.5px':'-48.5px'}">
        <el-col :span="24">
          <el-form-item label="现有业务描述" prop="serviceDescription">
            <el-input v-model="formData.serviceDescription" placeholder="请输入现有业务描述" rows="4" type="textarea"
                      :style="{marginRight:!formData.isSpecialFund?'20px':'80px'}" @change="changeCollectData"
                      clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="建设目标描述" prop="contentDescription">
            <el-input v-model="formData.contentDescription" placeholder="请输入研发项目关键内容描述" rows="4"
                      type="textarea"
                      :style="{marginRight:!formData.isSpecialFund?'20px':'80px'}" @change="changeCollectData"
                      clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <baseTitle title="附件文件"></baseTitle>
    <div :style="{marginRight:!formData.isSpecialFund?'20px':'80px'}">
      <AttachmentUpload ref="attachment" label="需求申请书附件"
                        :showTable="showTable" templateName="科技创新项目需求申请书" :templateDownloadBtnShow="true"
                        v-model:otherFileList="otherFileList"
                        @getOtherFile="getOtherFile"
                        :showSingleTable="showSingleTable" @getAttachment="getAttachment"
                        v-model:singleList="singleList"
                        :showFileList="true" :formData="formData" tag="需求上报"
                        :preview="name === 'Summary/edit'"/>
    </div>
    <div class="approval-record">
      <div class="approval-title" style="margin-top: -15px">
        <baseTitle title="审批记录"></baseTitle>
        <div class="diagram">
          <div class="base-title">流程图</div>
          <el-switch
              v-model="changeDiagram"
              style="--el-switch-on-color:#BEA266; --el-switch-off-color:#cecdcd;"
          />
        </div>
      </div>
      <el-empty :image-size="100" description="暂无审批记录"
                v-if="processDiagramViewer&& !opentionData?.operationList&&!changeDiagram"/>
      <!--      <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>-->
      <div class="process">
        <operation-render
            v-if="processDiagramViewer&& opentionData?.operationList && opentionData?.operationList.length > 0&&!changeDiagram"
            :operation-list="opentionData?.operationList"
            :state="opentionData.state"/>
        <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>
      </div>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" @click="staging">保存</el-button>
      <el-button color="#DED0B2" v-if="name==='Summary/add'" @click="handleSubmit(summaryForm)">发布</el-button>
      <el-button color="#DED0B2" v-else @click="handleResubmit(summaryForm)">重新发布</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import OperationRender from '@/views/workflow/common/OperationRender.vue'
import {debounce} from 'lodash'
import {
  getDetail,
  getProcessInfo,
  requirementReported,
  resubmitReported,
  getProjectOption,
  getRequirementOption
} from "@/api/project-demand/summary";
import {ElNotification} from "element-plus";
import {useAuthStore} from '@/stores/userstore.js'
import {useTagsView} from '@/stores/tagsview.js'
import {useCacheStore} from '@/stores/cache.js'
import {useProcessStore} from '@/stores/processStore.js';
import {getSubCompOpt} from "@/api/user/user";
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import {getFormInfo, getInfo} from "@/api/project-demand";
import {getFundOption} from "@/api/special-fund";
import UserPicker from "@/views/workflow/process/common/UserPicker.vue";

const authStore = useAuthStore()
const changeDiagram = ref(false)
const opentionData = ref({})
const cacheStore = useCacheStore()
const processStore = useProcessStore()
const router = useRouter()
const route = useRoute()
const attachment = ref()
const name = ref(router.currentRoute.value.name)
const loading = ref(false)
const processDiagramViewer = ref(false)
const tagsViewStore = useTagsView()
const companyOption = ref([])
const summaryForm = ref()
const deploymentId = ref()
const optionalChargeLeadershipPickerRef = ref()
const optionalChargeLeadershipList = ref([])
const masterProjectList = ref([])
const specialFundOption = ref([])
const requirementList = ref([])
const showTable = ref(true)
const showSingleTable = ref(false)
const otherFileList = ref([])
const singleList = ref([])
const formData = ref({
  isWithinBudget: false,
  isSpecialFund: false,
  industryUniversityResearch: '1',
  governmentDeclaration: '1',
  resultForm: []
})

const rules = reactive({
  projectName: [{required: true, message: '请输入项目名称', trigger: ['blur', 'change']}],
  specialFundId: [{required: true, message: '请选择专项资金名称', trigger: ['blur', 'change']}],
  startTime: [{required: true, message: '请选择开始时间', trigger: ['blur', 'change']}],
  endTime: [{required: true, message: '请选择结束时间', trigger: ['blur', 'change']}],
  rdSubject: [{required: true, message: '请选择研发主体', trigger: ['blur', 'change']}],
  projectType: [{required: true, message: '请选择项目类型', trigger: ['blur', 'change']}],
  investmentType: [{required: true, message: '请选择出资类型', trigger: ['blur', 'change']}],
  projectImpact: [{required: true, message: '请选择项目影响', trigger: ['blur', 'change']}],
  businessSegment: [{required: true, message: '请选择所属业务板块', trigger: ['blur', 'change']}],
  resultForm: [{required: true, message: '请选择预期成果形式', trigger: ['blur', 'change']}],
  technicalStandard: [{required: true, message: '请选择预期技术标准制定', trigger: ['blur', 'change']}],
  industryUniversityResearch: [{required: true, message: '请选择产学研联合', trigger: ['blur', 'change']}],
  governmentDeclaration: [{required: true, message: '请选择开展政府申报', trigger: ['blur', 'change']}],
  intellectualProperty: [{required: true, message: '请选择知识产权状况', trigger: ['blur', 'change']}],
  inventionPatent: [{required: true, message: '请输入发明专利数量', trigger: ['blur', 'change']}],
  newPatent: [{required: true, message: '请输入实用性新型专利数量', trigger: ['blur', 'change']}],
  softwareCopyright: [{required: true, message: '请输入软件著作权数量', trigger: ['blur', 'change']}],
  copyright: [{required: true, message: '请输入著作权数量', trigger: ['blur', 'change']}],
  other: [{required: true, message: '请输入其他数量', trigger: ['blur', 'change']}],
  economicEstimate: [{required: true, message: '请输入预估经费预算', trigger: ['blur', 'change']}],
  isSpecialFund: [{required: true, message: '请选择是否为专项资金', trigger: ['blur', 'change']}],
  isWithinBudget: [{required: true, message: '请选择是否在预算内', trigger: ['blur', 'change']}],
  forecastSpecialFundAmount: [{required: true, message: '请输入专项资金', trigger: ['blur', 'change']}],
  serviceDescription: [{required: true, message: '请输入现有业务描述', trigger: ['blur', 'change']}],
  contentDescription: [{required: true, message: '请输入研发项目关键内容描述', trigger: ['blur', 'change']}]
})
// watch(() => otherFileList.value, (newVal) => {
//   console.log('newVal',newVal)
//   otherFileList.value=newVal
//   changeCollectData()
// }, {deep: true})
watch(() => singleList.value, (newVal) => {
  showSingleTable.value = newVal.length !== 0;
}, {deep: true})
localStorage.removeItem('originallySelectedList')
if (name.value === 'Summary/edit') {
} else {
  if (localStorage.getItem('collectData')) {
    let collectData = JSON.parse(localStorage.getItem('collectData'))
    if (collectData.fileList) {
      otherFileList.value = collectData.fileList
    }
    if (collectData.optionalChargeLeadership) {
      optionalChargeLeadershipList.value = collectData.optionalChargeLeadership
    }
    formData.value = collectData
  }
}
const changeRequirement=async ()=>{
  await getInfo(formData.value.requirementId).then(res => {
    if (res.code === 1000) {

      console.log('formData.requirementId',formData.value.requirementId,res)
      formData.value.isSpecialFund =  res.data.formData.isSpecialFund
      if ( res.data.formData.isSpecialFund) {
        formData.value.specialFundId =  res.data.formData.specialFundId
        formData.value.specialFund =  res.data.formData.specialFund
      }
    }
  })
}
const changeCollectData = () => {
  if (name.value === 'Summary/edit') {
    // params.fileList= attachment.value.allFileList
  } else {
    let params = {
      ...formData.value,
      deploymentId: deploymentId.value,
      fileList: [],
      requirementId: route.query.id ? route.query.id : formData.value.requirementId ? formData.value.requirementId : null
    }
    params.fileList = otherFileList.value
    localStorage.setItem('collectData', JSON.stringify(params))
  }
}
const handleShowOptionalChargeLeadershipPicker = () => {
  optionalChargeLeadershipPickerRef.value.showUserPicker()
}

const optionalChargeLeaderPickerOkOrCancel = (userList) => {
  optionalChargeLeadershipList.value = userList
  formData.value.optionalChargeLeadership = optionalChargeLeadershipList.value
  changeCollectData()
}

const handleBack = () => {
  history.back()
}
const disabledDate = (time) => {
  return time.getTime() < new Date(formData.value.startTime).getTime();
}

const getProjectList = () => {
  getProjectOption().then(res => {
    if (res.code === 1000) {
      masterProjectList.value = res.data
    }
  })
}
getProjectList()
const getRequirementList = () => {
  getRequirementOption().then(res => {
    if (res.code === 1000) {
      requirementList.value = res.data
    }
  })
}
getRequirementList()
const getIsFund = async () => {
  if (!route.query.id) return;
  // loading.value = true
  await getFormInfo(route.query.id).then(res => {
    if (res.code === 1000) {
      formData.value.requirementDefaultName = res.data.requirementName
      // loading.value = false
      formData.value.isSpecialFund = res.data.isSpecialFund
      if (res.data.isSpecialFund) {
        formData.value.specialFundId = res.data.specialFundId
        formData.value.specialFund = res.data.specialFund
      }
    }
  })
}
const getFundName = (id) => {
  let label = ''
  specialFundOption.value.forEach(item => {
    if (item.value == id) {
      label = item.label
    }
  })
  return label
}
const getProjectName = (id) => {
  let label = ''
  masterProjectList.value.forEach(item => {
    if (item.value == id) {
      label = item.label
    }
  })
  return label
}
const getRequirementName = (id) => {
  let label = ''
  requirementList.value.forEach(item => {
    if (item.value == id) {
      label = item.label
    }
  })
  return label
}
const compositeParam = (item, type) => {
  let tag = ''
  if (name.value === 'Summary/add' || name.value === 'Summary/edit') {
    tag = '需求上报'
  }
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: true,
    tag: tag
  }
}

const getAttachment = (val) => {
  // console.log('上传文件getAttachment', val)
  showSingleTable.value = false
  formData.value.singleFile = compositeParam(val)
  singleList.value.push(compositeParam(val))
  nextTick(() => {
    showSingleTable.value = true
    if (attachment.value.singleFile == null) {
      attachment.value.validate()
      ElNotification({
        title: '提示',
        message: '请上传附件',
        type: 'error'
      })
      return;
    } else {
      attachment.value.clearValidate()
    }
  })
}
const getOtherFile = (val) => {
  // console.log('上传文件getOtherFile', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  otherFileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
  changeCollectData()
}

const getFileParam = (item) => {
  if (item === undefined) return;
  return {
    fileId: item.fileId,
    tag: item.tag
  }
}

const handleSubmit = debounce(async (instance) => {
  if (!instance) return
  instance.validate(async (valid, fields) => {
    if (!valid) {
      ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
      return;
    }
    let otherFiles = []
    otherFileList.value.forEach(item => {
      otherFiles.push(getFileParam(item))
    })
    formData.value.optionalChargeLeadership = optionalChargeLeadershipList.value
    if (formData.value.singleFile !== undefined) {
      formData.value.singleFile = getFileParam(formData.value.singleFile)
    }
    if (formData.value.isSpecialFund && !formData.value.specialFund) {
      formData.value.specialFund = getFundName(formData.value.specialFundId)
    }
    if (formData.value.masterProjectId) {
      formData.value.masterProjectName = getProjectName(formData.value.masterProjectId)
    }
    if (formData.value.requirementId) {
      formData.value.requirementName = getRequirementName(formData.value.requirementId)
    }
    if (!attachment.value.isHaveOneFile) {
      attachment.value.validate()
      ElNotification({
        title: '提示',
        message: '请上传附件',
        type: 'error'
      })
      return;
    } else {
      attachment.value.clearValidate()
    }
    let params = {
      ...formData.value,
      deploymentId: deploymentId.value,
      fileList: otherFiles,
      requirementId: route.query.id ? route.query.id : formData.value.requirementId ? formData.value.requirementId : '-1'
    }
    console.log('params', params)
    let res = await requirementReported(params)
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      await router.push({
        name: 'Summary'
      })
      localStorage.removeItem('collectData')
    }
  })
})
const handleResubmit = debounce((instance) => {
  if (!instance) return
  instance.validate(async (valid, fields) => {
    if (!valid) {
      ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
      return;
    }
    let otherFiles = []
    if (name.value === 'Summary/edit') {
      attachment.value.allFileList.forEach(item => {
        otherFiles.push(getFileParam(item))
      })
    }
    formData.value.optionalChargeLeadership = optionalChargeLeadershipList.value
    if (formData.value.isSpecialFund && !formData.value.specialFund) {
      formData.value.specialFund = getFundName(formData.value.specialFundId)
    }
    if (formData.value.masterProjectId) {
      formData.value.masterProjectName = getProjectName(formData.value.masterProjectId)
    }
    if (formData.value.requirementId) {
      formData.value.requirementName = getRequirementName(formData.value.requirementId)
    }
    if (!attachment.value.isHaveOneFile) {
      attachment.value.validate()
      ElNotification({
        title: '提示',
        message: '请上传附件',
        type: 'error'
      })
      return;
    } else {
      attachment.value.clearValidate()
    }
    let params = {
      ...formData.value,
      deploymentId: deploymentId.value,
      fileList: otherFiles,
      requirementId: route.query.id ? route.query.id : formData.value.requirementId ? formData.value.requirementId : '-1'
    }
    // console.log('重新提交params', params, formData.value.specialFund, formData.value.specialFundId)
    resubmitReported(params).then(res => {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: res.code === 1000 ? 'success' : 'error'
      })
      if (res.code === 1000) {
        tagsViewStore.delVisitedViews(router.currentRoute.value.path)
        router.push({
          name: 'Summary'
        })
        // localStorage.removeItem('collectData')
      }
    })
  })
})

const getDetailInfo = async () => {
  loading.value = true
  await getDetail(route.query.projectId).then(res => {
    if (res.code === 1000) {
      res.data.formData.specialFundId = res.data.formData.specialFundId === 0 ? null : res.data.formData.specialFundId
      if (res.data.formData.requirementId == -1) {
        res.data.formData.requirementId = null
      }
      formData.value = res.data.formData
      opentionData.value = res.data
      optionalChargeLeadershipList.value = formData.value.optionalChargeLeadership
      loading.value = false
    }else{
      ElNotification({
        title: '提示',
        message: res.msg,
        type: res.code === 1000 ? 'success' : 'error'
      })
    }
  })
}
const specialFundChange = () => {
  processInfo()
  changeCollectData()
}
const init = async () => {
  await getIsFund()
  loading.value = true
  const resFund = await getFundOption()
  specialFundOption.value = resFund.data
  const res = await getSubCompOpt()
  companyOption.value = res.data
  await processInfo()
  loading.value = false
}
const processInfo = () => {
  processStore.setDesign(null)
  processDiagramViewer.value = false
  let isSpecialFundParam = false
  if (!formData.value.isSpecialFund) {
    isSpecialFundParam = false
  } else {
    isSpecialFundParam = formData.value.isSpecialFund
  }
  getProcessInfo(isSpecialFundParam).then(res => {
    if (res.code === 1000) {
      let data = res.data
      deploymentId.value = data.deploymentId
      processStore.setDesign(data)
      processStore.runningList.value = data.runningList;
      processStore.endList.value = data.endList;
      processStore.noTakeList.value = data.noTakeList;
      processStore.refuseList.value = data.refuseList;
      processStore.passList.value = data.passList;
      nextTick(() => {
        processDiagramViewer.value = true
      })
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}
onMounted(async () => {
  if (route.query.projectId) {
    await getDetailInfo()
  }
  await init()
})
const staging = async () => {
  ElNotification({
    title: '提示',
    message: '保存成功!',
    type: 'success'
  })
}
</script>
<style lang="scss" scoped>
.detail-block {
  overflow: hidden;
  padding: 0 0 0 40px;

  :deep(.el-input-number) {
    width: 100%;

    .el-input__inner {
      text-align: left;
    }
  }
}
</style>
