<template>
  <div class="apply-block">
    <baseTitle :title="getTitleName(title)+'信息'"></baseTitle>
    <el-form :model="localFormData" ref="formRef" label-width="auto" v-if="step!=='50'" :rules="rules">
      <el-row v-if="title==='apply'">
        <el-col :span="6">
          <!--          label-width="106"-->
          <el-form-item label="实际经费预算(元)" prop="actualEconomicEstimate" label-width="130">
            <el-input v-model="localFormData.actualEconomicEstimate" placeholder="请输入实际经费预算">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" >
          <!--          label-width="106" v-if="isSpecialFund"-->
          <el-form-item label="实际专项资金(元)" prop="specialFundAmount" label-width="140">
            <el-input v-model="localFormData.specialFundAmount" placeholder="请输入实际专项资金">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="title==='check'">
        <el-col :span="6">
          <el-form-item label="实际专利(项)" prop="actualNewPatent" label-width="130">
            <el-input v-model="localFormData.actualNewPatent" placeholder="请输入实际专利数量" style="margin-right: 20px">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="margin-left: -10px">
          <el-form-item label="实际软件著作权(项)" prop="actualSoftwareCopyright" label-width="150">
            <el-input v-model="localFormData.actualSoftwareCopyright" placeholder="请输入实际软件著作权数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="margin-left: -5px">
          <el-form-item label="实际技术标准(项)" prop="actualTechnicalNorms" label-width="150">
            <el-input v-model="localFormData.actualTechnicalNorms" placeholder="请输入实际技术标准数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际新产品(项)" prop="actualNewProduct" label-width="160" style="margin-right: -10px">
            <el-input v-model="localFormData.actualNewProduct" placeholder="请输入实际新产品数量" >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际新工艺(项)" prop="actualNewProcess" label-width="130" >
            <el-input v-model="localFormData.actualNewProcess" placeholder="请输入实际新工艺数量" style="margin-right: 20px">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="margin-left: -10px">
          <el-form-item label="实际新装置(项)" prop="actualNewDevice" label-width="150">
            <el-input v-model="localFormData.actualNewDevice" placeholder="请输入实际新装置数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="margin-left: -5px">
          <el-form-item label="实际新材料(项)" prop="actualNewMaterials" label-width="150">
            <el-input v-model="localFormData.actualNewMaterials" placeholder="请输入实际新材料数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际计算机软件(项)" prop="actualComputerSoftware" label-width="160" style="margin-right: -10px">
            <el-input v-model="localFormData.actualComputerSoftware" placeholder="请输入实际计算机软件数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际论文论著(项)" prop="actualThesis" label-width="130" style="margin-right: 20px">
            <el-input v-model="localFormData.actualThesis" placeholder="请输入实际论文论著数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="margin-left: -10px">
          <el-form-item label="实际研究报告(项)" prop="actualResearchReport" label-width="150">
            <el-input v-model="localFormData.actualResearchReport" placeholder="请输入实际研究报告数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="margin-left: -5px">
          <el-form-item label="实际商标(项)" prop="actualTrademark" label-width="150">
            <el-input v-model="localFormData.actualTrademark" placeholder="请输入实际商标数量">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="实际其他(项)" prop="actualOther" label-width="130" style="margin-right: 10px">
            <el-input rows="4" type="textarea" v-model="localFormData.actualOther" placeholder="请输入实际其他项">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6" v-if="title==='apply'">
          <!--          label-width="106"-->
          <el-form-item label="项目负责人" :required="true" prop="" label-width="130">
            <el-button style="margin-right: 10px" color="#DED0B2" @click="handleShowProjectChargePersonTable">
              {{ projectChargePersonUserList?.length !== 0 ? '更改' : '请选择' }}
            </el-button>
            <div v-for="item in projectChargePersonUserList" :key="item.id" style="margin-right: 5px">
              {{ item.name }}
            </div>
            <user-picker :multiple="false" ref="projectChargePersonUserPicker" title="请选择项目负责人"
                         v-model:value="projectChargePersonUserList" @ok="projectChargePersonUserPickerOk"
                         @cancelOrClear="projectChargePersonUserPickerCancel"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="title==='apply'">
          <el-form-item label="项目成员" :required="true" prop="" label-width="140"
          >
            <el-button color="#DED0B2" style="margin-right: 10px" @click="handleShowProjectPersonTable">
              {{
                projectPersonUserList?.length !== 0 ? '更改' : getProjectPerson(projectPersonUserList) ? '更改' : '请选择'
              }}
            </el-button>
            <div v-for="(item,index) in getProjectPerson(projectPersonUserList)" :key="item.id">
              {{ item.name }}{{ index != getProjectPerson(projectPersonUserList)?.length - 1 ? '，' : '' }}
            </div>
            <user-picker :multiple="true" ref="projectPersonUserPicker" title="请选择项目成员"
                         v-model:value="projectPersonUserList" @ok="projectPersonUserPickerOk"
                         @cancelOrClear="projectPersonUserPickerCancel"/>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="title==='apply'||title==='check'">
          <el-form-item label="部门分管领导" :label-width="title==='check'?130:115">
            <el-button color="#DED0B2" style="margin-right: 10px" @click="handleShowOptionalChargeLeadershipPicker">
              {{
                optionalChargeLeadershipList?.length !== 0 ? '更改' : getOptionalChargeLeadershipList(optionalChargeLeadershipList) ? '更改' : '请选择'
              }}
            </el-button>
            <div v-for="(item,index) in getOptionalChargeLeadershipList(optionalChargeLeadershipList)" :key="item.id">
              {{
                item.name
              }}{{ index != getOptionalChargeLeadershipList(optionalChargeLeadershipList)?.length - 1 ? '，' : '' }}
            </div>
            <user-picker :multiple="true" ref="optionalChargeLeadershipPickerRef" title="请选择部门分管领导"
                         v-model:value="optionalChargeLeadershipList" @ok="optionalChargeLeaderPickerOk"
                         @cancelOrClear="optionalChargeLeaderPickerCancel"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="preProcessShow === 'EDIT'||title==='apply'">
          <el-form-item label="前置流程" :required="preProcessRequired" prop="preProcess" :label-width="title==='apply'?130:125">
            <el-button color="#DED0B2" @click="handleShowPreTable" style="margin-right: 10px">
              {{
                localFormData.preProcess && localFormData.preProcess?.length > 0 ? '更改' : sessionParams.preProcess && sessionParams.preProcess?.length > 0 ? '更改' : '请选择'
              }}
            </el-button>
            <div v-for="(item,index) in getRequestName(localFormData.preProcess)" :key="item.requestId">
              <a :href="item.baseUrl" target="_blank"
                 style="color: #2a99ff;cursor: pointer">{{ item.requestName }}<span
                  v-if="index != localFormData.preProcess?.length -1">，</span>
              </a>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--    v-if="showAttachment"-->
    <AttachmentUpload ref="attachment" :label="getTitleName(title)+'附件'" :showTable="showTable"
                      v-model:otherFileList="otherFileList" :tag="getTitleName(props.title)"
                      :templateName="getTemplateName(props.title)"
                      :templateDownloadBtnShow="props.title==='apply'?true:props.title==='check'"
                      @getAttachment="getAttachment" v-model:singleList="singleList" :showSingleTable="showSingleTable"
                      @getOtherFile="getOtherFile" :showFileList="true" :formData="localFormData"
                      :preview="mode == 'resubmit'"/>
    <div>
      <div class="approval-record">
        <div class="approval-title" style="margin-top: -15px">
          <!--          <baseTitle title="审批记录" v-if="mode === 'resubmit'"></baseTitle>-->
          <!--          <div v-else></div>-->
          <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="!data?.operationList&&!changeDiagram"/>
        <div class="process">
          <operation-render
              v-if="mode === 'resubmit'&&processDiagramViewer&& data?.operationList && data?.operationList.length > 0&&!changeDiagram"
              :operation-list="data.operationList"
              :state="data.state"/>
          <process-diagram-viewer mode="view" :idName="title" v-if="processDiagramViewer&&changeDiagram"/>
        </div>
      </div>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" v-if="mode === 'submit'" @click="handleSubmit(formRef)">提交</el-button>
      <el-button color="#DED0B2" v-else-if="mode === 'resubmit'" @click="handleSubmit(formRef)">重新提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>

    <file-preview ref="filePreviewRef" v-if="filePreviewShow" :fileName="filePreviewParam.fileName"
                  :fileUrl="filePreviewParam.fileUrl"
                  :fileType="filePreviewParam.fileType"/>
    <el-dialog v-if="showPreTable" title="前置流程" v-model="showPreTable" width="80%">
      <el-form :model="preProcessForm" inline @submit.prevent="searchPreProcess">
        <el-form-item label="请求名称">
          <el-input v-model="preProcessForm.requestName" placeholder="请输入请求名称" clearable>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button color="#DED0B2" @click="searchPreProcess">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="preProcessList" v-loading="loading"
                @select="handleSelect" @select-all="handleSelect" row-key="requestId" ref="preProcessTable">
        <el-table-column type="selection" width="55" :reserve-selection="true"/>
        <el-table-column prop="requestId" label="请求id"></el-table-column>
        <el-table-column prop="requestName" label="请求名称"></el-table-column>
        <el-table-column prop="lastOperatorName" label="最后操作人名称"></el-table-column>
        <el-table-column prop="lastOperateTime" label="最后操作时间"></el-table-column>
        <el-table-column prop="currentNodeName" label="当前节点"></el-table-column>
        <el-table-column prop="creatorName" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <!--              <el-button type="primary" @click="choosePreProcess(scope.row)" link>选择</el-button>-->
            <a :href="scope.row.baseUrl" target="_blank" style="color: #2a99ff;margin-left: 10px">查看流程</a>
          </template>
        </el-table-column>
      </el-table>
      <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
              :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
      <div class="oper">
        <el-button color="#DED0B2" @click="choosePreProcess">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="jsx">
import OperationRender from '@/views/workflow/common/OperationRender.vue'
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import {ElLoading, ElNotification} from "element-plus";
import {
  getApplyProcess,
  getPreProcess,
  getProjectCheckProcess,
  getProjectConclusionProcess,
  projectApply,
  projectCheck,
  projectConclusion,
  resubmitApply,
  resubmitCheck,
  resubmitConclusion
} from "@/api/project-manage";
import {useProcessStore} from '@/stores/processStore.js';
import {useTagsView} from '@/stores/tagsview.js'
import Paging from "@/components/pagination/index.vue";
import UserPicker from "@/views/workflow/process/common/UserPicker.vue";
import {getBaseInfoApi, getMapProjectStateInfo} from "@/components/steps/api";

const router = useRouter()
const route = useRoute()
const formRef = ref()
const changeDiagram = ref(false)
const showSingleTable = ref(false)
const projectChargePersonUserList = ref([])
const projectChargePersonUserPicker = ref()
const projectPersonUserList = ref([])
const projectPersonUserPicker = ref()
const singleList = ref([])

const emit = defineEmits(["getAttachment", "getOtherFile"])
const props = defineProps({
  title: {
    type: String,
    default: 'apply'
  },
  showTable: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: "view"
  },
  data: {
    type: Object,
    default: {}
  },
  formData: {
    type: Object,
    default: {}
  },
  step: {
    type: String,
    default: "20"
  },
  preProcessShow: {
    type: String,
    default: "READ"
  }
})
const preProcessList = ref([])
//暂存数据
const currentList = ref([])
const preProcessRequired = ref(false)
const total = ref(0)
const preProcessForm = reactive({
  requestName: ''
})
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const rules = reactive({
  actualEconomicEstimate: [{required: true, message: '请输入实际经费预算', trigger: ['blur', 'change']}],
  specialFundAmount: [{required: true, message: '请输入实际专项资金', trigger: 'blur'}],
  // projectPerson: [{required: true, message: '请选择项目成员', trigger: 'blur'}],
  actualNewPatent: [{required: true, message: '请输入实际专利数量', trigger: ['blur', 'change']}],
  actualTechnicalNorms: [{required: true, message: '请输入实际技术标准数量', trigger: ['blur', 'change']}],
  actualSoftwareCopyright: [{required: true, message: '请输入实际软件著作权数量', trigger: ['blur', 'change']}],
  actualNewProduct: [{required: true, message: '请输入实际新产品数量', trigger: ['blur', 'change']}],
  actualNewProcess: [{required: true, message: '请输入实际新工艺数量', trigger: ['blur', 'change']}],
  actualNewMaterials: [{required: true, message: '请输入实际新材料数量', trigger: ['blur', 'change']}],
  actualNewDevice: [{required: true, message: '请输入实际新装置数量', trigger: ['blur', 'change']}],
  actualComputerSoftware: [{required: true, message: '请输入实际计算机软件数量', trigger: ['blur', 'change']}],
  actualThesis: [{required: true, message: '请输入实际论文论著数量', trigger: ['blur', 'change']}],
  actualResearchReport: [{required: true, message: '请输入实际研究报告数量', trigger: ['blur', 'change']}],
  actualTrademark: [{required: true, message: '请输入实际商标数量', trigger: ['blur', 'change']}],
  actualOther: [{required: true, message: '请输入实际其他项数量', trigger: ['blur', 'change']}],

})
const tagsViewStore = useTagsView()
const processStore = useProcessStore()
const localProjectPerson = ref([])
const otherFileList = ref([])
const localFormData = ref({
  projectPersonIds: [],
  projectChargePerson: null,
  preProcess: [
    // {
    //   requestId: null,
    //   requestName: '',
    //   baseUrl: ''
    // }
  ]
})
const attachment = ref()
const deploymentData = ref({})
const showPreTable = ref(false)
const showTable = ref(true)
const loading = ref(false)
const processDiagramViewer = ref(false)
const name = ref(router.currentRoute.value.name)
const deploymentId = ref()
const selectRows = ref([])
const projectId = ref(route.query.projectId)
const sessionParams = ref({})
const optionalChargeLeadershipPickerRef = ref()
const isSpecialFund = ref(false)
const optionalChargeLeadershipList = ref([])
const filePreviewParam = ref({
  fileUrl: '',
  fileName: '',
  fileType: 'pdf'
})
const filePreviewShow = ref(false)

const getSummaryInfo = async () => {
  if (props.mode === 'resubmit') return;
  if(props.title === 'check'){
    const loading = ElLoading.service({fullscreen: true})
    try {
      const projectId = route.query.projectId
      const {code, data, msg} = await getMapProjectStateInfo(projectId, '10')
      if (code === 1000) {
        localFormData.value.actualNewPatent= data.formData.newPatent
        localFormData.value.actualSoftwareCopyright= data.formData.softwareCopyright
        localFormData.value.actualTechnicalNorms= data.formData.technicalNorms
        localFormData.value.actualNewProduct= data.formData.newProduct
        localFormData.value.actualNewProcess= data.formData.newProcess
        localFormData.value.actualNewDevice= data.formData.newDevice
        localFormData.value.actualNewMaterials= data.formData.newMaterials
        localFormData.value.actualComputerSoftware= data.formData.computerSoftware
        localFormData.value.actualThesis= data.formData.thesis
        localFormData.value.actualResearchReport= data.formData.researchReport
        localFormData.value.actualTrademark= data.formData.trademark
        localFormData.value.actualOther= data.formData.other

        loading.close()
      } else {
        ElNotification({
          title: '提示',
          message: msg,
          type: 'error'
        })

        loading.close()
      }
    } catch {
      loading.close()
    }
  }
}
getSummaryInfo()

const getInfo = async () => {

  const {code, data} = await getBaseInfoApi(route.query.projectId)
  isSpecialFund.value = data.isSpecialFund
}
getInfo()
const getTemplateName = (type) => {
  switch (type) {
    case 'apply':
      return '科技创新项目立项模板'
    case 'check':
      return '科技创新项目验收申请表'
  }
}

const handleShowOptionalChargeLeadershipPicker = () => {
  optionalChargeLeadershipPickerRef.value.showUserPicker()
}

const optionalChargeLeaderPickerOk = (userList) => {
  optionalChargeLeadershipList.value = userList
  if (userList?.length > 0) {
    localStorage.setItem('optionalChargeLeadershipList', JSON.stringify(optionalChargeLeadershipList.value))
  } else {
    localStorage.removeItem('optionalChargeLeadershipList')
  }
}
const optionalChargeLeaderPickerCancel = (userList) => {
  optionalChargeLeadershipList.value = userList
}

const clickToPreview = (row) => {
  filePreviewShow.value = false
  filePreviewParam.value = {
    fileUrl: row.url,
    fileName: row.originalFileName,
    fileType: row.fileType
  }
  nextTick(() => {
    filePreviewShow.value = true
  })
}

const getOptionalChargeLeadershipList = (list) => {
  if (!list || list && list.length === 0) {
    if (localStorage.getItem('optionalChargeLeadershipList')) {
      let param = JSON.parse(localStorage.getItem('optionalChargeLeadershipList'))
      optionalChargeLeadershipList.value = param
      return optionalChargeLeadershipList.value
    }
  } else {
    return list
  }
}
const getProjectPerson = (list) => {
  if (!list || list && list.length === 0) {
    if (localStorage.getItem('projectPersonUserList')) {
      let param = JSON.parse(localStorage.getItem('projectPersonUserList'))
      projectPersonUserList.value = param
      return projectPersonUserList.value
    }
  } else {
    return list
  }
}
const getRequestName = (list) => {
  if (!list || (list && list.length === 0)) {
    if (sessionParams.value.preProcess) {
      return sessionParams.value.preProcess
    }
  } else {
    return list
  }
}
const getProjectChargePersonUser = () => {
  if (projectChargePersonUserList.value.length !== 0) {
    return projectChargePersonUserList.value.map(item => item.name).join()
  }
}
const handleSelect = async (selection) => {
  selectRows.value = selection
}
const handleCancel = () => {
  showPreTable.value = false
}
const searchPreProcess = () => {
  getPreProcessList()

}
const handleReset = () => {
  preProcessForm.requestName = ''
  getPreProcessList()
}
const handleShowPreTable = () => {
  showPreTable.value = true
  getPreProcessList()
}
const handleShowProjectChargePersonTable = () => {
  projectChargePersonUserPicker.value.showUserPicker()
}
const projectChargePersonUserPickerOk = (userList) => {
  projectChargePersonUserList.value = userList
  if (userList?.length > 0) {
    localStorage.setItem('projectChargePersonUserList', JSON.stringify(projectChargePersonUserList.value))
  } else {
    localStorage.removeItem('projectPersonUserList')
  }
}
const handleShowProjectPersonTable = () => {
  projectPersonUserPicker.value.showUserPicker()
}
const projectChargePersonUserPickerCancel = (userList) => {
  projectChargePersonUserList.value = userList
}
const projectPersonUserPickerCancel = (userList) => {
  projectPersonUserList.value = userList
}

const projectPersonUserPickerOk = (userList) => {
  projectPersonUserList.value = userList
  if (userList?.length > 0) {
    localStorage.setItem('projectPersonUserList', JSON.stringify(userList))
  } else {
    localStorage.removeItem('projectPersonUserList')
  }
}
const getPreProcessList = () => {
  loading.value = true
  getPreProcess().then(res => {
    loading.value = false
    let searchArray = []
    let regexPattern = ("%" + preProcessForm.requestName + "%").replace(/%/g, '.*').replace(/_/g, '.');
    let regex = new RegExp('^' + regexPattern + '$');
    res.data.filter((item) => {
      if (regex.test(item.requestName)) {
        searchArray.push(item)
      }
    })
    // res.data.forEach((item) => {
    //   localFormData.value.preProcess.forEach((item1) => {
    //     if (item.requestId == item1.requestId) {
    //       preProcessTable.value.toggleRowSelection(item)
    //     }
    //   })
    // })
    total.value = searchArray.length
    currentList.value = searchArray
    preProcessList.value = currentList.value.slice(0, 10)
  })
}
const choosePreProcess = () => {
  let preProcessObj = {}
  let preProcessArray = []
  selectRows.value.forEach((item) => {
    preProcessObj = {
      requestId: item.requestId,
      requestName: item.requestName,
      baseUrl: item.baseUrl
    }
    preProcessArray.push(preProcessObj)
  })
  localFormData.value.preProcess = preProcessArray
  showPreTable.value = false
  localStorage.setItem('preProcess', JSON.stringify(preProcessArray))
}

//切换每页显示条数
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  preProcessList.value = currentList.value.slice((pageInfo.pageNum - 1) * val, pageInfo.pageNum * val)
};

//点击页码进行分页功能
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val;
  preProcessList.value = currentList.value.slice((val - 1) * pageInfo.pageSize, val * pageInfo.pageSize)
};
const getTitleName = (type) => {
  switch (type) {
    case 'apply':
      return '项目立项'
    case 'check':
      return '项目验收'
    case 'filing':
      return '项目归档'
  }
}
const handleBack = () => {
  history.back()
}
const compositeParam = (item) => {
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: true,
    tag: getTitleName(props.title)
  }
}
const getAttachment = (val) => {
  // console.log('上传文件getAttachment', val)
  showSingleTable.value = false
  localFormData.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()
    }
  })

  localStorage.setItem('singleFile', JSON.stringify(compositeParam(val)))
}
watch(() => singleList.value, (newVal) => {
  showSingleTable.value = newVal.length !== 0;
}, {deep: true})
const getOtherFile = (val) => {
  // console.log('上传文件getOtherFile', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  otherFileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })

  // localFormData.value.otherFileList = otherFileList.value
  localStorage.setItem('otherFileList', JSON.stringify(otherFileList.value))
}
const getFileParam = (item) => {
  return {
    fileId: item.fileId,
    tag: item.tag
  }
}
const handleSubmit = async (instance) => {
  if (props.step == 50) {
    let files = []
    if (props.mode === 'resubmit') {
      attachment.value.allFileList.forEach(item => {
        files.push(getFileParam(item))
      })
    } else {
      otherFileList.value.forEach(item => {
        files.push(getFileParam(item))
      })
    }
    // console.info("🚀 ~method:handleSubmit -----", files,attachment.value.isHaveOneFile)
    if (!attachment.value.isHaveOneFile) {
      attachment.value.validate()
      ElNotification({
        title: '提示',
        message: '请上传附件',
        type: 'error'
      })
      return;
    } else {
      attachment.value.clearValidate()
    }
    let projectPersonIds = []
    for (const item of projectPersonUserList.value) {
      projectPersonIds.push(parseInt(item.id))
    }
    let params = {
      deploymentId: deploymentId.value,
      requirementId: route.query.id,
      fileList: files,
      // singleFile: attachment.value.singleFile,
      projectId: route.query.projectId,
      ...localFormData.value,
      actualEconomicEstimate: parseFloat(localFormData.value.actualEconomicEstimate),
      specialFundAmount: parseFloat(localFormData.value.specialFundAmount),
      preProcess: JSON.stringify(localFormData.value.preProcess)
    }
    if (sessionParams.value.preProcess && !localFormData.value.preProcess) {
      params.preProcess = JSON.stringify(sessionParams.value.preProcess)
    }
    console.log('params', params)
    let res
    if (props.mode === 'resubmit') {
      res = await resubmitConclusion(params)
    } else {
      res = await projectConclusion(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: 'Filing'
      })
    }
  } else {
    if (!instance) return
    instance.validate(async (valid) => {
      if (!valid) {
        ElNotification({
          title: '提示',
          message: '请完善数据,再提交!',
          type: 'error'
        })
        return;
      }
      let files = []
      if (props.mode === 'resubmit') {
        attachment.value.allFileList.forEach(item => {
          files.push(getFileParam(item))
        })
      } else {
        otherFileList.value.forEach(item => {
          files.push(getFileParam(item))
        })
      }
      // console.info("🚀 ~method:handleSubmit -----", files,attachment.value.isHaveOneFile)
      if (!attachment.value.isHaveOneFile) {
        attachment.value.validate()
        ElNotification({
          title: '提示',
          message: '请上传附件',
          type: 'error'
        })
        return;
      } else {
        attachment.value.clearValidate()
      }
      let projectPersonIds = []
      for (const item of projectPersonUserList.value) {
        projectPersonIds.push(parseInt(item.id))
      }
      let params = {
        // singleFile: attachment.value.singleFile,
        ...localFormData.value,
        projectId: route.query.projectId,
        deploymentId: deploymentId.value,
        requirementId: route.query.id,
        fileList: files,
        actualEconomicEstimate: parseFloat(localFormData.value.actualEconomicEstimate)||null,
        specialFundAmount: parseFloat(localFormData.value.specialFundAmount)||null,
        preProcess: JSON.stringify(localFormData.value.preProcess)
      }
      if (sessionParams.value.preProcess && !localFormData.value.preProcess) {
        params.preProcess = JSON.stringify(sessionParams.value.preProcess)
      }
      console.log('params', params)
      let res
      if (props.step === '20') {
        if (projectChargePersonUserList.value && projectChargePersonUserList.value.length === 0) {
          ElNotification({
            title: '提示',
            message: '请选择项目负责人!',
            type: 'error'
          })
          return;
        }
        if (projectPersonUserList.value && projectPersonUserList.value.length === 0) {
          ElNotification({
            title: '提示',
            message: '请选择项目成员!',
            type: 'error'
          })
          return;
        }
        params.projectChargePerson = parseInt(projectChargePersonUserList.value[0].id)
        params.projectPersonIds = projectPersonIds
        params.optionalChargeLeadership = optionalChargeLeadershipList.value
        if (props.mode === 'resubmit') {
          res = await resubmitApply(params)
        } else {
          res = await projectApply(params)
        }
      } else if (props.step === '40') {
        params.optionalChargeLeadership = optionalChargeLeadershipList.value
        if (props.mode === 'resubmit') {
          res = await resubmitCheck(params)
        } else {
          res = await projectCheck(params)
        }
      }
      ElNotification({
        title: '提示',
        message: res.msg,
        type: res.code === 1000 ? 'success' : 'error'
      })
      if (res.code === 1000) {
        tagsViewStore.delVisitedViews(router.currentRoute.value.path)
        if (props.step === '20') {
          await router.push({
            name: 'Initiation'
          })
        } else if (props.step === '40') {
          await router.push({
            name: 'Implementation'
          })
        }
      }
    })
  }
}
const init = async () => {
  let id = route.query.projectId
  if (!id) return;
  processDiagramViewer.value = false
  let res
  if (props.step === '20') {
    res = await getApplyProcess(id)
  } else if (props.step === '40') {
    res = await getProjectCheckProcess(id)
  } else if (props.step === '50') {
    res = await getProjectConclusionProcess(id)
  }
  if (res.code === 1000) {
    let data = res.data
    deploymentId.value = data.deploymentId
    deploymentData.value = data
    console.log('data,',data)
    preProcessRequired.value = data.deploymentName === '重大项目立项' || data.deploymentName === '重大项目验收';
    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'
    })
  }
}

watchEffect(() => {
  // console.info("🚀 ~method:;props.formData.projectChargePerson -----", props.formData.projectChargePerson)
  if (props.formData.projectChargePerson == null) {
    projectChargePersonUserList.value = []
  } else {
    projectChargePersonUserList.value = [props.formData.projectChargePerson]
  }
  if (props.formData.optionalChargeLeadership == null) {
    optionalChargeLeadershipList.value = []
  } else {
    optionalChargeLeadershipList.value = props.formData.optionalChargeLeadership
  }
  projectPersonUserList.value = props.formData.projectPersonList ? props.formData.projectPersonList : []
  let flag = Object.keys(props.formData).length && (localFormData.value = props.formData)
  // if (props.formData.projectChargePerson != null) {
  //   localFormData.value.projectChargePerson = props.formData.projectChargePerson.id
  // }

  if (localStorage.getItem('preProcess')) {
    let param = JSON.parse(localStorage.getItem('preProcess'))
    localFormData.value.preProcess = param
    sessionParams.value.preProcess = param
    localStorage.setItem('preProcess', JSON.stringify(param))
  }
  if (localStorage.getItem('singleFile')) {
    let param = JSON.parse(localStorage.getItem('singleFile'))
    localFormData.value.singleFile = param
    singleList.value = [param]
    localStorage.setItem('singleFile', JSON.stringify(param))
    showSingleTable.value = false
    nextTick(() => {
      showSingleTable.value = true
    })
  }
  if (localStorage.getItem('otherFileList')) {
    let param = JSON.parse(localStorage.getItem('otherFileList'))
    localFormData.value.otherFileList = param
    otherFileList.value = param
    localStorage.setItem('otherFileList', JSON.stringify(param))
    showTable.value = false
    nextTick(() => {
      showTable.value = true
    })
  }

  if (localStorage.getItem('projectChargePersonUserList')) {
    let param = JSON.parse(localStorage.getItem('projectChargePersonUserList'))
    projectChargePersonUserList.value = param
    localStorage.setItem('projectChargePersonUserList', JSON.stringify(param))
  }
  if (localStorage.getItem('projectPersonUserList')) {
    let param = JSON.parse(localStorage.getItem('projectPersonUserList'))
    projectPersonUserList.value = param
    localProjectPerson.value = param
    localStorage.setItem('projectPersonUserList', JSON.stringify(param))
  }
  if (localStorage.getItem('optionalChargeLeadershipList')) {
    let param = JSON.parse(localStorage.getItem('optionalChargeLeadershipList'))
    optionalChargeLeadershipList.value = param
    // localProjectPerson.value = param
    localStorage.setItem('optionalChargeLeadershipList', JSON.stringify(param))
  }

  return flag
})
onActivated(() => {
  init()
})
onMounted(async () => {
  await init()
})
</script>

<style scoped lang="scss">
.oper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

</style>
