<template>
  <el-row justify="space-between">
    <el-col :span="22">
      <el-select v-model="scaleId" placeholder="请选择量表" size="large" style="width: 400px">
        <el-option v-for="item in scaleList" :key="item.scaleId" :label="item.scaleName" :value="item.scaleId" />
      </el-select>
    </el-col>
    <el-col :span="2">
      <el-radio-group v-model="radio">
        <el-radio-button :value="1">整体</el-radio-button>
        <el-radio-button :value="2">班级</el-radio-button>
      </el-radio-group>
    </el-col>
  </el-row>

  <el-row>
    <el-card style="width: 100%; min-height: 300px;margin-top: 10px;">
      <template #header>
        <div class="card-header">
          <span>完成情况</span>
        </div>
      </template>

      <el-row justify="space-between">
        <el-col :span="8">
          <v-chart class="h" :option="completePieOption" autoresize />
        </el-col>
        <el-col :span="16">
          <v-chart class="h" :option="completeBarOption" autoresize />
        </el-col>
      </el-row>

      <el-row justify="center">
        <el-table :data="completeTable" style="width: 100%">
          <el-table-column prop="name" :label="radio == 1 ? '年级' : '班级'" />
          <el-table-column prop="join" label="测评总数" />
          <el-table-column prop="finish" label="完成测评数" />
          <el-table-column prop="finishRate" label="完成率" />
        </el-table>
      </el-row>

    </el-card>
  </el-row>

  <el-row>
    <el-card style="width: 100%; min-height: 300px;margin-top: 10px;">
      <template #header>
        <div class="card-header">
          <span>风险情况</span>
        </div>
      </template>

      <el-row justify="space-between">
        <el-col :span="8">
          <v-chart class="h" :option="warnPieOption" autoresize />
        </el-col>
        <el-col :span="16">
          <v-chart class="h" :option="warBarOption" autoresize />
        </el-col>
      </el-row>

      <el-row justify="center">
        <el-table :data="warnTable" style="width: 100%;">
          <el-table-column prop="name" :label="radio == 1 ? '年级' : '班级'" />
          <el-table-column prop="noneNum" label="未见异常" />
          <el-table-column prop="lowNum" label="低风险" />
          <el-table-column prop="middleNum" label="中风险" />
          <el-table-column prop="highNum" label="高风险" />
          <el-table-column prop="majorNum" label="重大风险" />
        </el-table>
      </el-row>
    </el-card>
  </el-row>

  <el-row>
    <el-card style="width: 100%; min-height: 300px;margin-top: 10px;">
      <template #header>
        <div class="card-header">
          <span>预警因子类型</span>
        </div>
      </template>

      <div class="chart-grid">
        <v-chart v-for="item in factorDataList" style="height: 300px;" :option="item" autoresize />
      </div>

    </el-card>
  </el-row>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts';

import { getScalePublish } from '@/api/scale/scalePublish';
import { getCompleteAll, getCompleteClass, getWarnAll, getWarnClass, getFactorAll, getFactorClass } from '@/api/activity/statistics'

import { use } from 'echarts/core'
import { CanvasRenderer } from "echarts/renderers";
import { PieChart, BarChart } from "echarts/charts";
import { TitleComponent, TooltipComponent, LegendComponent } from "echarts/components";
import VChart from 'vue-echarts'

const props = defineProps({
  batchNo: {
    type: String,
    default: ''
  }
})

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
]);

const batchNo = props.batchNo
const radio = ref(1)

const scaleId = ref()
const scaleList = ref([])
async function getScalePublishList() {
  const res = await getScalePublish(batchNo)
  const scaleIds = res.data.scaleIds
  const scaleNames = res.data.scaleNames
  scaleIds.forEach((item, index) => {
    scaleList.value.push({ scaleId: item, scaleName: scaleNames[index] })
  })

  if (scaleIds.length) {
    scaleId.value = scaleIds[0]
  }
}

//完成情况
const completePieOption = ref(initPieOption('', []))
const completeBarOption = ref(initBarOption([], []))
const completeTable = ref([])
async function getCompleteData() {
  const query = { batchNo, scaleId: scaleId.value }
  let res = {}

  if (radio.value == 1) {
    res = await getCompleteAll(query)
  }

  if (radio.value == 2) {
    res = await getCompleteClass(query)
  }

  const completeList = res.data

  let finishNum = 0
  let noneNum = 0

  let xAxisData = []
  let seriesFinishData = []
  let seriesNoneData = []

  completeList.forEach(v => {
    finishNum += v.value
    noneNum += v.spareValue

    xAxisData.push(v.name)
    seriesFinishData.push(v.value)
    seriesNoneData.push(v.spareValue)

    completeTable.value.push({ name: v.name, join: v.value + v.spareValue, finish: v.value, finishRate: percentage(v.value, v.value + v.spareValue) })
  })

  const completePie = [{ name: '已测', value: finishNum }, { name: '未测', value: noneNum }]
  completePieOption.value.series[0].data = completePie

  const seriesData = [{
    name: '已测', data: seriesFinishData, type: 'bar', barWidth: '14%', label: {
      show: true,
      position: 'top'
    }
  }, {
    name: '未测', data: seriesNoneData, type: 'bar', barWidth: '14%', label: {
      show: true,
      position: 'top'
    }
  }]
  completeBarOption.value.xAxis.data = xAxisData
  completeBarOption.value.series = seriesData
}

//风险情况
const warnPieOption = ref(initPieOption('', []))
const warBarOption = ref(initBarOption([], []))
const warnTable = ref([])
async function getwarnData() {
  const query = { batchNo, scaleId: scaleId.value }
  let res = {}

  if (radio.value == 1) {
    res = await getWarnAll(query)
  }

  if (radio.value == 2) {
    res = await getWarnClass(query)
  }

  const warnList = res.data

  let noneNum = 0
  let lowNum = 0
  let middleNum = 0
  let highNum = 0
  let majorNum = 0

  warnList.forEach(v => {
    noneNum += v.noneNum
    lowNum += v.lowNum
    middleNum += v.middleNum
    highNum += v.highNum
    majorNum += v.majorNum

    warnTable.value.push({ name: v.name, noneNum: v.noneNum, lowNum: v.lowNum, middleNum: v.middleNum, highNum: v.highNum, majorNum: v.majorNum })
  })

  const warnPie = [
    { name: '未见异常', value: noneNum },
    { name: '低风险', value: lowNum },
    { name: '中风险', value: middleNum },
    { name: '高风险', value: highNum },
    { name: '重大风险', value: majorNum }
  ]
  warnPieOption.value.series[0].data = warnPie

  let xAxisData = ['未见异常', '低风险', '中风险', '高风险', '重大风险']
  let seriesList = [noneNum, lowNum, middleNum, highNum, majorNum]
  const seriesData = [{
    data: seriesList, type: 'bar', label: {
      show: true,
      position: 'top'
    }
  }]
  warBarOption.value.xAxis.data = xAxisData
  warBarOption.value.series = seriesData
}

// 预警因子
const factorDataList = ref([])
async function getFactoryData() {
  const query = { batchNo, scaleId: scaleId.value }
  let res = {}

  if (radio.value == 1) {
    res = await getFactorAll(query)
  }

  if (radio.value == 2) {
    res = await getFactorClass(query)
  }

  const factoryList = res.data

  factoryList.forEach(item => {
    const pieData = []
    item.numList.forEach(numItem => {
      pieData.push({
        name: numItem.name,
        value: numItem.value
      })
    })

    factorDataList.value.push(initPieOption(item.factorName, pieData))
  })
}

watch([scaleId, radio], ([newVal, oldVal]) => {
  completeTable.value = []
  getCompleteData()

  warnTable.value = []
  getwarnData()

  factorDataList.value = []
  getFactoryData()
})

onMounted(() => {
  getScalePublishList()
})

function initPieOption(name = '', data = []) {
  return {
    title: {
      text: name,
      subtext: '',
      x: 'center',
      y: '40',
      textStyle: {
        color: '#95989D',
        fontSize: 20,
        lineHeight: 10,
      },
      subtextStyle: {
        color: '#95989D',
        fontSize: 16,
        lineHeight: 10,
      },
    },
    tooltip: {  
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal',
    },
    series: [
      {
        name: name,
        type: 'pie',
        radius: '50%',
        color: ['#AED88F', '#91ACE0', '#FED961', '#FC7100', '#FF0000'],
        data: data,
        label: {
          normal: {
            formatter: ['{c|{c}}', '{b|{b}}'].join('\n'),
            rich: {
              c: {
                lineHeight: 5
              },
              b: {
                height: 44
              },
            },
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

function initBarOption(xAxisData, seriesData) {
  return {
    tooltip: {
      trigger: 'item'
    },
    legend: {},
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: seriesData
  }
}

function percentage(number1, number2) {
  // 小数点后两位百分比
  return (Math.round(number1 / number2 * 10000) / 100.00 + "%");
}
</script>

<style lang="scss" scoped>
.h {
  height: 300px;
}

.chart-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
</style>
