<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 ProjectContentDialog from '@/pages/projectCollection/projectCollectionEnter/components/projectContentDialog.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: 'IRS应用试运行报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '信息安全等级保护测试报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '项目总结报告',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '建设核查表',
            isHave: true,
            files: [],
            reason: ''
          },
          {
            name: '其他附件',
            isHave: 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),
          beseExpectedResults: formData.value.beseExpectedResults && JSON.stringify(formData.value.beseExpectedResults) || 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) : formData.value.finalAcceptanceMaterials,
      beseExpectedResults: res.data.beseExpectedResults && JSON.parse(res.data.beseExpectedResults) || res.data.beseExpectedResults && JSON.parse(res.data.beseExpectedResults)
    }
    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
            required: true
          }
        })
      }
    })
    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: 'mainContent',
      key: 'mainContent'
    },
    {
      label: '业务对象',
      prop: 'businessObject',
      key: 'businessObject'
    },
    {
      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.beseExpectedResults.push(data)
    } else {
      formData.value.beseExpectedResults[projectContentIndex.value] = data
    }
  },
  delProjectContent = (index) => {
    formData.value.beseExpectedResults.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="beseExpectedResults"
            :rules="[{required:true,message:'请选择'}]"
          >
            <table-list
              :pagination="false"
              style="width: 100%"
              :column="column1"
              :data="formData.beseExpectedResults"
              :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>

  <project-content-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>
