<script name="uploadInitpreliminaryInspectionMaterials" setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { fileFormatVerification, handleFileSuccess, handleFilePreview, fileTypes } from '@/utils/uploadAction.js'
import store from '@/store'
import { preInsDetail, submitPreIns } from '@/http/apis/declareMange/initialInspectionRecord'
import { useRoute, useRouter } from 'vue-router'
import ActualPerformanceIndicatorsDialog
  from '@/pages/declareManage/initialInspectionRecord/uploadInitMaterials/components/actualPerformanceIndicatorsDialog.vue'
import { projectDetail } from '@/http/apis/projectStoreManage/projectStore'
const uploadUrl = store.dictStore.uploadUrl,
  route = useRoute(),
  { proxy } = getCurrentInstance(),
  router = useRouter()
const collapseModal = ['1', '2', '3', '4', '5', '6', '7'],
  formRef = ref(),
  formData = ref({
    acceptancePersons: [
      {
        personName: '',
        unit: ''
      }
    ],
    actualPerformanceIndicators: [],
    preliminaryInspectionMaterials: [
      {
        title: '一、项目前期材料',
        data: [
          {
            name: '信息化项目立项批复文件',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '市政府采购计划表',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '采购需求',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '中标通知书',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '技术（软件、系统等）开发合同（协议）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '设备采购合同（协议）含采购内容清单、以及合同上规定交付的所有文档',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '第三方监理合同（协议）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '其他前期资料（含中标单位营业执照、工程相关资质等）',
            isHave: true,
            files: [],
            reason: ''
          }
        ]
      },
      {
        title: '二、项目开工资料',
        data: [
          {
            name: '工程开工报告单（工程名称、建设单位、承建单位、施工单位、计划开工和完工日期、工程实施主要内容、建设单位审批意见及盖章日期，承建单位、施工单位盖章日期）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '软件类系统开发、部署等功能介绍',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '隐蔽工程类设计图、材料选材、施工计划等（可另作图册）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '购置到位的设备产品证书、开箱证明、序列号等（可另附成册）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '项目组名单及人员介绍资料',
            isHave: true,
            files: [],
            reason: ''
          }
        ]
      },
      {
        title: '三、项目实施过程资料',
        data: [
          {
            name: '设备安装时间、位置一览表等',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '软件类系统开发、部署等完成情况对照表',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '历次多方讨论会议记录表、项目变更单等原始凭证',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '信息安全等级保护测评报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '商业密码应用评估报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '财务审计报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '变更申请单',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '变更批复文件',
            isHave: true,
            files: [],
            reason: ''
          }
        ]
      },
      {
        title: '四、项目试运行资料',
        data: [
          {
            name: '试运行报告及整改情况（建设单位）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '试运行情况业主单位意见（领导签字、单位盖章）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '历次巡检流程及记录表等原始凭证',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '用户使用报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: 'IRS应用试运行报告',
            isHave: true,
            files: [],
            reason: ''
          }
        ]
      },
      {
        title: '五、项目完工资料',
        data: [
          {
            name: '工程类竣工报告（建设单位）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '完工整体运行情况报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '监理总结报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '第三方项目评测报告（另册）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '业主单位组织的初验专家意见及名单，整改情况',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '各类系统、场地、设备使用的管理手册、操作手册、维护手册（可另册）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '售后服务承诺等（建设单位）',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '终验意见',
            isHave: true,
            files: [],
            reason: ''
          }
        ]
      }
    ]
  }),
  // 增加验收人员
  add = () => {
    formData.value.acceptancePersons.push({})
  },
  // 删除验收人员
  del = (index) => {
    formData.value.acceptancePersons.splice(index, 1)
  },
  // 材料表格
  column = [
    {
      label: '序号',
      type: 'index',
      width: '60'
    },
    {
      label: '材料名称',
      key: 'name',
      prop: 'name'
    },
    {
      label: '是否有材料',
      key: 'isHave',
      slot: 'isHave',
      width: 100
    },
    {
      label: '附件/说明（支持扩展名：.doc .docx .pdf）',
      key: 'files',
      slot: 'files'
    }
  ],
  // 获取详情
  getDetail = async () => {
    const res = await preInsDetail(route.query.id)
    if (res.data) {
      formData.value = {
        ...res.data,
        acceptancePersons: res.data.acceptancePersons ? res.data.acceptancePersons : [
          {
            personName: '',
            unit: ''
          }
        ],
        actualPerformanceIndicators: res.data.actualPerformanceIndicators && JSON.parse(res.data.actualPerformanceIndicators)?.length ? JSON.parse(res.data.actualPerformanceIndicators) : formData.value.actualPerformanceIndicators,
        preliminaryInspectionMaterials: res.data.preliminaryInspectionMaterials && JSON.parse(res.data.preliminaryInspectionMaterials)?.length ? JSON.parse(res.data.preliminaryInspectionMaterials) : formData.value.preliminaryInspectionMaterials
      }
    }
  },
  // 提交
  submitLoading = ref(false),
  submit = async (formEl) => {
    if (!formEl) {
      return
    }
    formEl.validate(async (valid, err) => {
      if (valid) {
        submitLoading.value = true
        const postData = {
          ...formData.value,
          actualPerformanceIndicators: formData.value.actualPerformanceIndicators && JSON.stringify(formData.value.actualPerformanceIndicators),
          preliminaryInspectionMaterials: JSON.stringify(formData.value.preliminaryInspectionMaterials)
        }
        try {
          await submitPreIns(postData)
          submitLoading.value = false
          proxy.$message.success('提交成功')
          router.go(-1)
        } catch (e) {
          submitLoading.value = false
        }
      } else {
        console.log(err)
      }
    })
  },
  // 实际成效指标
  column1 = [
    {
      label: '核心业务',
      prop: 'businessName',
      key: 'businessName'
    },
    {
      label: '实际成效指标',
      prop: 'name',
      key: 'name'
    },
    {
      label: '数值',
      prop: 'nums',
      key: 'nums'
    },
    {
      label: '单位',
      prop: 'unit',
      key: 'unit'
    },
    {
      label: '操作',
      slot: 'action',
      key: 'action'
    }
  ],
  projectContentDialogData = reactive({
    visible: false,
    data: undefined
  }),
  projectContentIndex = ref(),
  showProjectContentDialog = (data, index) => {
    projectContentDialogData.data = data
    projectContentDialogData.visible = true
    projectContentIndex.value = index
  },
  setContent = (data) => {
    if (projectContentIndex.value === undefined) {
      formData.value.actualPerformanceIndicators = [...formData.value.actualPerformanceIndicators, ...data]
    } else {
      formData.value.actualPerformanceIndicators[projectContentIndex.value] = data[0]
    }
  },
  delProjectContent = (index) => {
    formData.value.actualPerformanceIndicators.splice(index, 1)
  },
  getProjectDetail = async () => {
    const res = await projectDetail(route.query.id)
    if (res.data.projectApplications?.length) {
      if (res.data.projectApplications.map(i => i.secrecyGrade).includes(3) || res.data.projectApplications.map(i => i.secrecyGrade).includes(4) || res.data.projectApplications.map(i => i.secrecyGrade).includes(5)) {
        formData.value.preliminaryInspectionMaterials = formData.value.preliminaryInspectionMaterials.map(i => {
          return {
            ...i,
            data: i.data.map(j => {
              return {
                ...j,
                required: j.name === '商业密码应用评估报告' ? true : j.required
              }
            })
          }
        })
      }
    }
  }
onMounted(() => {
  getDetail()
  getProjectDetail()
})
</script>

<template>
  <div class="uploadInitpreliminaryInspectionMaterials footerPage">
    <el-form
      ref="formRef"
      :model="formData"
      label-position="right"
      label-width="90px"
      label-suffix=":"
      scroll-to-error
      class="table-form"
    >
      <el-collapse v-model="collapseModal">
        <el-collapse-item name="1" class="mb-16">
          <template #title>
            <div class="collapse-title">验收人员信息</div>
          </template>
          <div class="p-24">
            <el-row v-for="(item,index) in formData.acceptancePersons" :key="index" :gutter="40">
              <el-col :span="12">
                <el-form-item
                  label="验收人员"
                  :prop="`acceptancePersons[${index}].personName`"
                  :rules="[{ required: true, message: '请输入' }]"
                >
                  <el-input v-model="item.personName" placeholder="请填写姓名" maxlength="50" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="所在单位"
                  :prop="`acceptancePersons[${index}].unit`"
                  :rules="[{ required: true, message: '请输入' }]"
                >
                  <el-input v-model="item.unit" placeholder="请填写单位" maxlength="50" />
                </el-form-item>
              </el-col>
              <a
                v-if="formData.acceptancePersons?.length>1"
                class="text-danger absolute top-4"
                style="right: -12px"
                @click="del(index)"
              >删除</a>
            </el-row>
            <el-button
              type="primary"
              plain
              icon="Plus"
              size="small"
              @click="add"
            >增加</el-button>
          </div>
        </el-collapse-item>
        <el-collapse-item name="7" class="mb-16">
          <template #title>
            <div class="collapse-title">实施信息</div>
          </template>
          <el-form-item
            label="是否完成日志数据归集"
            label-width="170"
            prop="isCompletedLogCollection"
            :rules="[{required:true,message:'请选择'}]"
          >
            <el-radio-group v-model="formData.isCompletedLogCollection">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="实际成效指标"
            label-width="170"
            prop="actualPerformanceIndicators"
            :rules="[{required:true,message:'请选择'}]"
          >
            <table-list
              :pagination="false"
              style="width: 100%"
              :column="column1"
              :data="formData.actualPerformanceIndicators"
              :empty-temp="false"
            >
              <template #action="{scope}">
                <a @click="showProjectContentDialog(scope.row,scope.$index)">编辑</a>
                <a class="text-danger" @click="delProjectContent(scope.$index)">删除</a>
              </template>
            </table-list>
            <p class="text-right w-full mt-8">
              <el-button
                type="primary"
                class="w-full"
                plain
                icon="Plus"
                @click="()=>showProjectContentDialog()"
              >添加</el-button>
            </p>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item
          v-for="(item,index) in formData.preliminaryInspectionMaterials"
          :key="index"
          :name="index+2+''"
          class="mb-16"
        >
          <template #title>
            <div class="collapse-title">{{ item.title }}</div>
          </template>
          <table-list
            ref="tableListRef"
            :column="column"
            :data="item.data"
            :pagination="false"
            :empty-temp="false"
          >
            <template #isHave="{scope}">
              <el-switch v-model="scope.row.isHave" :disabled="scope.row.required" />
            </template>
            <template #files="{scope}">
              <template v-if="scope.$index>=0">
                <el-form-item
                  v-if="scope.row.isHave"
                  :prop="`preliminaryInspectionMaterials[${index}].data[${scope.$index}].files`"
                  :rules="[{ required: true, message: '请上传' }]"
                  label-width="0"
                  style="margin-bottom: 0"
                  class="uploadFormItem"
                >
                  <el-upload
                    v-model:file-list="scope.row.files"
                    class="w-full table-upload"
                    :action="uploadUrl"
                    :on-success="res => handleFileSuccess(res, scope.row.files)"
                    :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
                    :accept="fileTypes.map(i=>`.${i}`).join(',')"
                    :on-preview="handleFilePreview"
                  >
                    <el-button type="primary" plain size="small">选择文件</el-button>
                  </el-upload>
                </el-form-item>
                <el-form-item
                  v-else
                  :prop="`preliminaryInspectionMaterials[${index}].data[${scope.$index}].reason`"
                  :rules="[{ required: true, message: '请输入' }]"
                  label-width="0"
                  style="margin-bottom: 0"
                >
                  <el-input v-model="scope.row.reason" placeholder="请填写缺少该材料的原因" maxlength="50" />
                </el-form-item>
              </template>
            </template>
          </table-list>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <div class="footer">
      <el-button @click="router.go(-1)"> 返回 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit(formRef)"> 提交 </el-button>
    </div>
  </div>
  <actual-performance-indicators-dialog
    :visible="projectContentDialogData.visible"
    :data="projectContentDialogData.data"
    @set-content="setContent"
    @close="projectContentDialogData.visible=false"
  />
</template>
<style lang="less">
.uploadInitpreliminaryInspectionMaterials{
  .table-form{
    .uploadFormItem{
      .el-form-item__error{
        position: absolute;
        left: 100px;
        top:16px;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
