<template>
  <div class="detail-block" v-loading="loading">
    <baseTitle title="需求上报"></baseTitle>
    <el-form :model="formData" ref="summaryForm" :rules="rules">
      <el-row gutter="15">
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName" label-width="125">
            <el-input v-model="formData.projectName" placeholder="请输入项目名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="startTime" label-width="145">
            <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%"
              />
            </el-config-provider>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endTime"
                        :title="!formData.startTime?'请先选择开始时间!':''" label-width="134">
            <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"
              />
            </el-config-provider>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目类型" prop="projectType" label-width="125">
            <el-select v-model="formData.projectType" placeholder="请选择项目类型" clearable filterable>
              <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="8">
          <el-form-item label="研发主体" prop="rdSubject" label-width="145">
            <el-select v-model="formData.rdSubject" placeholder="请选择研发主体" clearable filterable>
              <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="8">
          <el-form-item label="出资类型" prop="investmentType" label-width="134">
            <el-select v-model="formData.investmentType" placeholder="请选择出资类型" clearable filterable>
              <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="8">
          <el-form-item label="项目影响" prop="projectImpact" label-width="125">
            <el-select v-model="formData.projectImpact" placeholder="请选择项目影响" clearable filterable>
              <el-option
                  v-for="item in cacheStore.getDict('project_impact')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属业务板块" prop="businessSegment" label-width="145">
            <el-select v-model="formData.businessSegment" placeholder="请选择所属业务板块" clearable filterable>
              <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="8">
          <el-form-item label="预期技术标准制定" prop="technicalStandard">
            <el-select v-model="formData.technicalStandard" placeholder="请选择预期技术标准制定" clearable filterable>
              <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="route.query.id && formData.isSpecialFund?8:!formData.isSpecialFund?!route.query.id?6:8:6">
          <el-form-item label="产学研联合" prop="industryUniversityResearch" label-width="125">
            <el-radio-group v-model="formData.industryUniversityResearch">
              <el-radio v-for="item in cacheStore.getDict('industry_university')"
                        :key="item.value"
                        :label="item.value">{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="route.query.id && formData.isSpecialFund?8:!formData.isSpecialFund?route.query.id?8:6:6">
          <el-form-item label="开展政府申报" prop="governmentDeclaration" :label-width="route.query.id && formData.isSpecialFund?145:!formData.isSpecialFund?145:145">
            <el-radio-group v-model="formData.governmentDeclaration">
              <el-radio v-for="item in cacheStore.getDict('government_declaration')"
                        :key="item.value"
                        :label="item.value">{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="!route.query.id && formData.isSpecialFund?4:!route.query.id?12:12" v-if="!route.query.id">
          <el-form-item label="是否专项资金" prop="isSpecialFund" >
            <el-radio-group v-model="formData.isSpecialFund" @change="specialFundChange">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="route.query.id && formData.isSpecialFund">
          <el-form-item label="专项资金名称" prop="specialFundId" :label-width="route.query.id && formData.isSpecialFund?135:''">
            <span>{{ formData.specialFund }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!route.query.id && formData.isSpecialFund" >
          <el-form-item label="专项资金名称" prop="specialFundId" label-width="135">
            <el-select v-model="formData.specialFundId" placeholder="请选择专项资金名称" clearable filterable>
              <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="8" style="margin-bottom: -18px">
          <el-form-item label="知识产权状况" prop="intellectualProperty" :label-width="!formData.isSpecialFund?!route.query.id?125:135:125">
            <el-select v-model="formData.intellectualProperty" placeholder="请选择知识产权状况" clearable filterable>
              <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="16" style="margin-bottom: -18px">
          <el-form-item label="预期成果形式" prop="resultForm" label-width="145">
            <el-select v-model="formData.resultForm" placeholder="请选择预期成果形式" clearable filterable multiple>
              <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="24">
          <baseTitle title="预期知识产权"></baseTitle>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发明专利(项)" prop="inventionPatent" label-width="125">
            <el-input-number v-model="formData.inventionPatent" placeholder="请输入发明专利" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实用性新型专利(项)" prop="newPatent" label-width="145">
            <el-input-number v-model="formData.newPatent" placeholder="请输入实用性新型专利" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="软件著作权(项)" prop="softwareCopyright" label-width="135">
            <el-input-number v-model="formData.softwareCopyright" placeholder="请输入软件著作权" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="著作权(项)" prop="copyright" label-width="125">
            <el-input-number v-model="formData.copyright" placeholder="请输入著作权" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其他(项)" prop="other" label-width="145">
            <el-input-number v-model="formData.other" placeholder="请输入其他" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="经济概算(元)" prop="economicEstimate" label-width="135">
            <el-input-number v-model="formData.economicEstimate" placeholder="请输入经济概算" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="16" v-if="formData.isSpecialFund">
          <el-form-item label="其中申请公司总部科技创新专项资金(元)">
            <el-input-number v-model="formData.specialFundAmount" placeholder="请输入专项资金" :controls="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="现有业务描述" prop="serviceDescription" label-width="125">
            <el-input v-model="formData.serviceDescription" placeholder="请输入现有业务描述" rows="4" type="textarea"
                      clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="研发项目关键内容描述" prop="contentDescription" label-width="125">
            <el-input v-model="formData.contentDescription" placeholder="请输入研发项目关键内容描述" rows="4" type="textarea"
                      clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <AttachmentUpload ref="attachment" label="需求申请书附件" :showTable="showTable" :otherFileList="otherFileList"
                      @getAttachment="getAttachment" :singleList="singleList" :showSingleTable="showSingleTable"
                      @getOtherFile="getOtherFile" :showFileList="true" :formData="formData"
                      :preview="name === 'Summary/edit'"/>
    <div class="approval-record" style="margin-left: 70px">
      <div style="display: flex;align-items: center;justify-content: flex-start;">
        <div class="base-title">流程图</div>
        <el-switch
            v-model="changeDiagram"
            style="--el-switch-on-color:#BEA266; --el-switch-off-color:#cecdcd;margin-left: 10px"
        />
      </div>
      <process-diagram-viewer mode="view" v-if="processDiagramViewer&&changeDiagram"/>
    </div>
    <div class="oper-page-btn">
      <!--      <el-button type="info" @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">重新发布</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import {debounce} from 'lodash'
import {getDetail, getProcessInfo, requirementReported, resubmitReported} from "@/api/project-demand/summary";
import {ElNotification} from "element-plus";
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} from "@/api/project-demand";
import {getFundOption} from "@/api/special-fund";

const changeDiagram = ref(false)
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 specialFundOption = ref([])
const showTable = ref(false)
const showSingleTable = ref(false)
const otherFileList = ref([])
const singleList = ref([])
const formData = ref({
  isSpecialFund: true,
  industryUniversityResearch: '0',
  governmentDeclaration: '0',
  resultForm:[]
})

const rules = reactive({
  projectName: [{required: true, message: '请输入项目名称', trigger: 'blur'}],
  // specialFundId: [{required: true, message: '请选择专项资金', trigger: 'blur'}],
  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'}],
  newPatent: [{required: true, message: '请输入实用性新型专利', trigger: 'blur'}],
  softwareCopyright: [{required: true, message: '请输入软件著作权', trigger: 'blur'}],
  copyright: [{required: true, message: '请输入著作权', trigger: 'blur'}],
  other: [{required: true, message: '请输入其他', trigger: 'blur'}],
  economicEstimate: [{required: true, message: '请输入经济概算', trigger: 'blur'}],
  specialFundAmount: [{required: true, message: '请输入专项资金', trigger: 'blur'}],
  serviceDescription: [{required: true, message: '请输入现有业务描述', trigger: 'blur'}],
  contentDescription: [{required: true, message: '请输入研发项目关键内容描述', trigger: 'blur'}]
})

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

const getIsFund = async () => {
  if (!route.query.id) return;
  // loading.value = true
  await getFormInfo(route.query.id).then(res => {
    if (res.code === 1000) {
      // 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 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
  })
}
const getOtherFile = (val) => {
  // console.log('上传文件getOtherFile', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  otherFileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
}
watch(() => otherFileList.value, (newVal) => {
  showTable.value = newVal.length !== 0;
}, {deep: true})
watch(() => singleList.value, (newVal) => {
  showSingleTable.value = newVal.length !== 0;
}, {deep: true})
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) {
      return ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
    }
    let otherFiles = []
    otherFileList.value.forEach(item => {
      otherFiles.push(getFileParam(item))
    })
    if (formData.value.singleFile !== undefined) {
      formData.value.singleFile = getFileParam(formData.value.singleFile)
    }
    // formData.value.resultForm=formData.value.resultForm?.map(item=>item).join(',')
    let params = {
      ...formData.value,
      deploymentId: deploymentId.value,
      fileList: otherFiles,
      requirementId: route.query.id ? route.query.id : '-1'
    }
    console.log('params', params)
    if (!attachment.value.isSingleFile) {
      attachment.value.validate()
      ElNotification({
        title: '提示',
        message: '请上传附件',
        type: 'error'
      })
      return;
    } else {
      attachment.value.clearValidate()
    }
    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'
      })
    }
  })
})
const handleResubmit = debounce(() => {
  let otherFiles = []
  if (name.value === 'Summary/edit') {
    attachment.value.allFileList.forEach(item => {
      otherFiles.push(getFileParam(item))
    })
  }
  if (attachment.value.singleFile == null) {
    attachment.value.validate()
    ElNotification({
      title: '提示',
      message: '请上传附件',
      type: 'error'
    })
    return;
  } else {
    attachment.value.clearValidate()
  }
  if (formData.value.isSpecialFund && formData.value.specialFund === null) {
    formData.value.specialFund = getFundName(formData.value.specialFundId)
  }
  // formData.value.resultForm=formData.value.resultForm?.map(item=>item).join(',')
  let params = {
    ...formData.value,
    deploymentId: deploymentId.value,
    fileList: otherFiles,
    requirementId: route.query.id ? route.query.id : '-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'
      })
    }
  })
})

const getDetailInfo = async () => {
  loading.value = true
  getDetail(route.query.projectId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      res.data.formData.specialFundId = res.data.formData.specialFundId === 0 ? null : res.data.formData.specialFundId
      formData.value = res.data.formData
      loading.value = false
    }
  })
}
const specialFundChange = () => {
  processInfo()
}
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
  getProcessInfo(formData.value.isSpecialFund).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 () => {
}
</script>
<style lang="scss" scoped>
.detail-block {
  overflow: hidden;
  padding-bottom: 30px;

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

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