<script name="declarationFinal" setup>
import { onMounted, ref, nextTick, getCurrentInstance, reactive } from 'vue'
import { fileFormatVerification, handleFileSuccess, handleFilePreview, fileTypes } from '@/utils/uploadAction.js'
import store from '@/store'
import * as echarts from 'echarts'
import { useRoute, useRouter } from 'vue-router'
import { submitFinal } from '@/http/apis/declareMange/finalInspectionDeclare'
import { projectDetail } from '@/http/apis/projectStoreManage/projectStore'
import ActualPerformanceIndicatorsDialog
  from '@/pages/declareManage/initialInspectionRecord/uploadInitMaterials/components/actualPerformanceIndicatorsDialog.vue'
const uploadUrl = store.dictStore.uploadUrl,
  route = useRoute(),
  { proxy } = getCurrentInstance(),
  router = useRouter()
const collapseModal = ['1', '2', '3', '4', '5', '6', '7'],
  formRef = ref(),
  formData = ref({
    finalAcceptanceMaterials: [
      {
        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,
            required: true,
            files: [],
            reason: ''
          },
          {
            name: '历次多方讨论会议记录表、项目变更单等原始凭证',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '信息安全等级保护测评报告',
            isHave: true,
            required: 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,
            required: true,
            files: [],
            reason: ''
          },
          {
            name: 'IRS应用试运行报告',
            isHave: true,
            required: 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,
            required: true,
            files: [],
            reason: ''
          }
        ]
      }
    ]
  }),
  // 材料表格
  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'
    }
  ],
  applications = ref([
    {
      name: '应用1',
      status: '运行中',
      memoryRate: 11,
      cpuRate: 33,
      cpRate: 44
    },
    {
      name: '应用2',
      status: '运行中',
      memoryRate: 68,
      cpuRate: 43,
      cpRate: 30
    }
  ]),
  applicationData = ref({})
let chart1, chart2, chart3
const chart1Ref = ref(), chart2Ref = ref(), chart3Ref = ref(),
  getCirChartOptions = (precent, color, text) => {
    const colorList = [color, 'rgba(0, 0, 0, 0.1)']
    return {
      legend: {
        show: false
      },
      graphic: [
        {
          type: 'text',
          left: 'center',
          top: '48%',
          style: {
            text: `${precent}%`,
            fill: '#333333', // 文字的颜色
            fontSize: 16,
            fontWeight: 'bold',
            fontFamily: 'DINAlternate-Bold, DINAlternate'
          }
        },
        {
          type: 'text',
          left: 'center',
          bottom: '0',
          style: {
            text: `${text}`,
            fill: '#333333', // 文字的颜色
            fontSize: 12
          }
        }
      ],
      series: [
        {
          type: 'pie',
          radius: ['58%', '75%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          data: [
            {
              value: precent
            },
            {
              value: 100 - precent
            }
          ],
          itemStyle: {
            color: function (params) {
              return colorList[params.dataIndex]
            }
          },
          labelLine: {
            show: false
          }
        }
      ]
    }
  },
  initChart1 = () => {
    if (!chart1) chart1 = echarts.init(chart1Ref.value)
    const option = getCirChartOptions(applicationData.value.memoryRate, '#5ADE92',
      '近三个月内存平均使用率')
    chart1.setOption(option)
  },
  initChart2 = () => {
    if (!chart2) chart2 = echarts.init(chart2Ref.value)
    const option = getCirChartOptions(applicationData.value.cpuRate, '#0967FD',
      '近三个月CPU平均使用率')
    chart2.setOption(option)
  },
  initChart3 = () => {
    if (!chart3) chart3 = echarts.init(chart3Ref.value)
    const option = getCirChartOptions(applicationData.value.cpRate, '#ffae00',
      '近三个月磁盘平均使用率')
    chart3.setOption(option)
  },
  getChart = () => {
    initChart1()
    initChart2()
    initChart3()
  },
  // 切换应用
  tabName = ref(0),
  changeApp = (index) => {
    tabName.value = index
    applicationData.value = applications.value[index]
    getChart()
  },
  // 提交
  submitLoading = ref(false),
  submit = async (formEl) => {
    if (!formEl) {
      return
    }
    formEl.validate(async (valid, err) => {
      if (valid) {
        submitLoading.value = true
        const postData = {
          id: route.query.id,
          isCompletedLogCollection: formData.value.isCompletedLogCollection,
          finalAcceptanceMaterials: JSON.stringify(formData.value.finalAcceptanceMaterials),
          actualPerformanceIndicators: formData.value.actualPerformanceIndicators && JSON.stringify(formData.value.actualPerformanceIndicators) || undefined
        }
        try {
          await submitFinal(route.name === 'declarationFinal' ? 1 : 2, { projectInfo: postData })
          submitLoading.value = false
          proxy.$message.success('提交成功')
          router.go(-1)
        } catch (e) {
          submitLoading.value = false
        }
      } else {
        console.log(err)
      }
    })
  },
  getProjectDetail = async () => {
    const res = await projectDetail(route.query.id)
    formData.value = {
      isCompletedLogCollection: res.data.isCompletedLogCollection,
      finalAcceptanceMaterials: res.data.finalAcceptanceMaterials && JSON.parse(res.data.finalAcceptanceMaterials) || res.data.preliminaryInspectionMaterials && JSON.parse(res.data.preliminaryInspectionMaterials),
      actualPerformanceIndicators: res.data.actualPerformanceIndicators && JSON.parse(res.data.actualPerformanceIndicators) || res.data.actualPerformanceIndicators && JSON.parse(res.data.actualPerformanceIndicators)
    }
    formData.value.finalAcceptanceMaterials = formData.value.finalAcceptanceMaterials.map(i => {
      return {
        ...i,
        data: i.data.map(j => {
          return {
            ...j,
            isHave: ['软件类系统开发、部署等完成情况对照表', '信息安全等级保护测评报告', '用户使用报告', 'IRS应用试运行报告', '终验意见'].includes(j.name) ? true : j.isHave,
            required: ['软件类系统开发、部署等完成情况对照表', '信息安全等级保护测评报告', '用户使用报告', 'IRS应用试运行报告', '终验意见'].includes(j.name) ? true : j.required
          }
        })
      }
    })
    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.finalAcceptanceMaterials = formData.value.finalAcceptanceMaterials.map(i => {
          return {
            ...i,
            data: i.data.map(j => {
              return {
                ...j,
                isHave: ['商业密码应用评估报告'].includes(j.name) ? true : j.isHave,
                required: ['商业密码应用评估报告'].includes(j.name) ? true : j.required
              }
            })
          }
        })
      }
    }
    applications.value = res.data.projectApplications?.map((i, index) => {
      return {
        name: i.applicationName || i.relatedExistsApplication,
        status: '运行中',
        finalIrsApps: res.data.finalIrsApps[index]
      }
    }) || []
    applicationData.value = applications.value[0]
  },
  // 实际成效指标
  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?.length ? [...formData.value.actualPerformanceIndicators, ...data] : data
    } else {
      formData.value.actualPerformanceIndicators[projectContentIndex.value] = data[0]
    }
  },
  delProjectContent = (index) => {
    formData.value.actualPerformanceIndicators.splice(index, 1)
  }
onMounted(async () => {
  await nextTick()
  // getChart()
  getProjectDetail()
})

</script>

<template>
  <div class="uploadInitfinalAcceptanceMaterials 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 v-if="applications?.length" name="1" class="mb-16">
          <template #title>
            <div class="collapse-title">关联的应用信息</div>
          </template>
          <div class="pb-24">
            <el-tabs v-model="tabName" tab-position="left" @tab-change="changeApp">
              <el-tab-pane
                v-for="(item,index) in applications"
                :key="index"
                :label="item.name"
                :name="index"
              />
              <div class="pl-24">
                <p class="font-semibold text-14 mb-16">应用状态：<span class="text-primary">{{ applicationData.status }}</span></p>
                <p class="font-semibold text-14">资源概览</p>
                <div class="p-16">
                  <el-row class="mb-16">
                    <el-col :span="12">
                      <p class="mb-8">云资源使用情况</p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="云资源实例使用数">
                          {{ applicationData?.finalIrsApps?.cloudResourceUsage.instancesNum }}
                        </el-descriptions-item>
                        <el-descriptions-item label="云资源产品">
                          暂无
                        </el-descriptions-item>
                        <el-descriptions-item label="云资源利用率">
                          {{ applicationData?.finalIrsApps?.cloudResourceUsage.utilizationRate }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="12" class="mb-16">
                      <p class="mb-8">数据使用情况</p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="数据共享申请量">
                          {{ applicationData?.finalIrsApps?.dataUsage.sharedApplicationVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="数据共享使用量">
                          {{ applicationData?.finalIrsApps?.dataUsage.sharedUsage }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                    <el-col :span="12" class="mb-16">
                      <p class="mb-31"></p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="协同接口调用量">
                          {{ applicationData?.finalIrsApps?.dataUsage.collaborativeInterfaceCallVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="数据共享调用量">
                          {{ applicationData?.finalIrsApps?.dataUsage.sharedInterfaceCallVolume }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                    <el-col :span="12" class="mb-16">
                      <p class="mb-8">组件使用情况</p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="组件申请量">
                          {{ applicationData?.finalIrsApps?.componentUsage.applicationVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="组件调用量">
                          {{ applicationData?.finalIrsApps?.componentUsage.callVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="组件使用量">
                          {{ applicationData?.finalIrsApps?.componentUsage.useVolume }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                    <el-col :span="12" class="mb-16">
                      <p class="mb-31"></p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="统一组件调用量">
                          {{ applicationData?.finalIrsApps?.componentUsage.unifyCallolVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="使用组件">
                          暂无
                        </el-descriptions-item>
                        <el-descriptions-item label="使用强制类组件">
                          暂无
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                    <el-col :span="12" class="mb-16">
                      <p class="mb-8">产生数据</p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="产生数据量">
                          {{ applicationData?.finalIrsApps?.generateData.volume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="产生数据共享使用量">
                          {{ applicationData?.finalIrsApps?.generateData.sharedUseVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="数据接口被调用量">
                          {{ applicationData?.finalIrsApps?.generateData.dataInterfaceCallsVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="使用批量数据">
                          暂无
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                    <el-col :span="12" class="mb-16">
                      <p class="mb-31"></p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="产生数据共享申请量">
                          {{ applicationData?.finalIrsApps?.generateData.sharedApplicationVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="产生数据审批通过率">
                          {{ applicationData?.finalIrsApps?.generateData.approvalPassRate }}
                        </el-descriptions-item>
                        <el-descriptions-item label="协同接口被调用量">
                          {{ applicationData?.finalIrsApps?.generateData.collaborativeInterfaceCallVolume }}
                        </el-descriptions-item>
                        <el-descriptions-item label="使用共享接口">
                          暂无
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                    <el-col :span="12">
                      <p class="mb-8">试运行报告</p>
                      <el-descriptions :column="1" border>
                        <el-descriptions-item label="试运行报告通过率">
                          {{ applicationData?.finalIrsApps?.operationReport.passRate }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                  </el-row>
                </div>
                <template v-if="false">
                  <p class="font-semibold text-14">云资源利用率</p>
                  <el-row>
                    <el-col :span="8">
                      <div ref="chart1Ref" style="height: 200px"></div>
                    </el-col>
                    <el-col :span="8">
                      <div ref="chart2Ref" style="height: 200px"></div>
                    </el-col>
                    <el-col :span="8">
                      <div ref="chart3Ref" style="height: 200px"></div>
                    </el-col>
                  </el-row>
                </template>
              </div>
            </el-tabs>
          </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.finalAcceptanceMaterials"
          :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="`finalAcceptanceMaterials[${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="`finalAcceptanceMaterials[${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">
.uploadInitfinalAcceptanceMaterials{
  .table-form{
    .uploadFormItem{
      .el-form-item__error{
        position: absolute;
        left: 100px;
        top:16px;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
