<template>
  <div class="personnel-compare-view full">
    <div class="p-l-base p-r-base p-t-medium-base fill-blank filter-form" style="padding-bottom: 10px">
      <base-form size="small" :label-width="'88px'" :model="model" :items="items">
        <template #form-item-button-group>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </template>
      </base-form>
    </div>
    <div v-loading="loading" class="p-small">
      <el-radio-group v-model="dataType">
        <el-radio-button v-for="type in dataTypeValues" :key="type" :label="type">
          {{ dataTypeLabelMap[type] }}
        </el-radio-button>
      </el-radio-group>
      <div class="m-t-small">
        <base-table
          v-if="dataType !== 'segmentScores'"
          ref="tableRef1"
          border
          stripe
          size="small"
          :columns="columns"
          :data="allTableData"
          :height="'calc(100vh - 575px)'"
          highlight-current-row
          @row-dblclick="onDbClick"
        >
        </base-table>
        <base-table
          v-else
          ref="tableRef2"
          border
          stripe
          size="small"
          :columns="columns2"
          :data="allTableData"
          :height="multipleSelection.length || curRow ? 'calc(100vh - 575px)' : 'auto'"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-dblclick="onDbClick"
        >
        </base-table>
      </div>
      <div v-if="allTableData.length" class="m-t-small out-chart-box">
        <div v-if="dataType !== 'segmentScores'" class="chart-box">
          <vue-e-charts class="full" :option="lineChartOptions"></vue-e-charts>
          <div class="right-box">
            <div class="legend-item">
              <div class="color" style="background-color: red"></div>
              <div class="label">总体{{ dataTypeLabelMap[dataType] }}</div>
            </div>
            <div v-for="(item, index) in filterAverageDatas" :key="index" class="legend-item">
              <div class="color" :style="{ backgroundColor: myColorList[index] }"></div>
              <div class="label">
                {{ `小组${item.markingGroupNumber}` + dataTypeLabelMap[dataType] }}
              </div>
            </div>
          </div>
        </div>
        <div v-else-if="multipleSelection.length" class="chart-box">
          <vue-e-charts class="full" :option="multLineChartOptions"></vue-e-charts>
        </div>
        <div v-if="curRow" class="row-chart">
          <vue-e-charts class="full" :option="rowChartOptions"></vue-e-charts>
          <el-icon class="close-icon" @click="curRow = null"><circle-close /></el-icon>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="PersonnelCompare">
import { ref, reactive, computed, watch } from 'vue'
import BaseForm from '@/components/element/BaseForm.vue'
import useFetch from '@/hooks/useFetch'
import BaseTable from '@/components/element/BaseTable.vue'
import { ElButton, ElRadioButton, ElRadioGroup, ElIcon } from 'element-plus'
import useCompareFilter from './hooks/useCompareFilter'
import VueECharts from 'vue-echarts'
import { CircleClose } from '@element-plus/icons-vue'
import { myColorList } from '@/utils/common'
import { cloneDeep } from 'lodash-es'
import useMainStore from '@/store/main'
const mainStore = useMainStore()
const curRow = ref<any>(null)
const onDbClick = (row: any) => {
  curRow.value = row
}
const dataType = ref('avg')
const dataTypeValues = ['avg', 'std', 'segmentScores', 'markingCount', 'xyRelate']
const dataTypeLabelMap = reactive<any>({
  avg: '平均分',
  std: '标准差',
  segmentScores: '给分分布',
  markingCount: '工作量',
  xyRelate: '相关系数',
})
const multLineXdatas = ref([])
const { model, fetchModel, items, onOptionInit, changeModelValue, groupListWithAll } = useCompareFilter()

const { fetch, result: allResult2, loading } = useFetch('getCompareList')
const allResult = computed(() => {
  if (allResult2.value) {
    if (mainStore.myUserInfo?.role === 'DEPUTY') {
      let markingGroupNumber = mainStore.myUserInfo.markingGroupNumber
      let target = allResult2.value.groups.find((item: any) => item.markingGroupNumber == markingGroupNumber)
      let zeroGroup = cloneDeep(target)
      zeroGroup.markingGroupNumber = 0
      zeroGroup.markerCompares = []
      return { columns: allResult2.value.columns, groups: [target, zeroGroup] }
    } else {
      return allResult2.value
    }
  } else {
    return { columns: [], groups: [] }
  }
})
const result = computed(() => {
  let groups = (allResult.value?.groups || []).filter((item: any) => {
    if (
      !fetchModel.value.markingGroupNumber ||
      fetchModel.value.markingGroupNumber?.length === 0 ||
      (Array.isArray(fetchModel.value.markingGroupNumber) && fetchModel.value.markingGroupNumber.includes(undefined))
    ) {
      return item
    } else {
      return fetchModel.value.markingGroupNumber.includes(item.markingGroupNumber) || item.markingGroupNumber == 0
    }
  })
  return { columns: allResult.value?.columns || [], groups }
})
const averageDatas = computed(() => {
  if (result.value) {
    let data = result.value.groups.map((item: any) => {
      return {
        markingGroupNumber: item.markingGroupNumber,
        avg: item.avg,
        avgMarkingCount: item.avgMarkingCount,
        std: item.std,
        xyRelate: item.xyRelate,
      }
    })
    return data
  } else {
    return []
  }
})
const filterAverageDatas = computed(() => {
  return averageDatas.value.filter((item: any) => {
    return item.markingGroupNumber != 0
  })
})
const allTableData = computed(() => {
  if (result.value) {
    let groups = cloneDeep(result.value.groups)
    let arr = []
    for (let i = 0; i < groups.length; i++) {
      let g = groups[i]
      arr.push(...g.markerCompares)
    }
    console.log('allTableData', arr)
    return arr
  } else {
    return []
  }
})

watch(dataType, () => {
  multipleSelection.value = []
  curRow.value = null
})
watch(allTableData, () => {
  if (!multLineXdatas.value.length && allTableData.value.length) {
    multLineXdatas.value = allTableData.value[0].segmentScores.map((item: any) => {
      return item.scoreStart
    })
  }
})
const columns = computed(() => {
  return [
    {
      label: '评卷员',
      prop: 'loginName',
      align: 'center',
      minWidth: 90,
      fixed: 'left',
      formatter(row: any) {
        return `${row.loginName}-${row.markerName}`
      },
    },
    // { label: '姓名', prop: 'markerName', align: 'center', minWidth: 120, fixed: 'left' },
    {
      label: dataTypeLabelMap[dataType.value],
      align: 'center',
      minWidth: 80,
      sortable: true,
      formatter(row: any) {
        return row[dataType.value]
      },
      sortMethod: function (a: any, b: any) {
        let aValue = a[dataType.value] || 0
        let bValue = b[dataType.value] || 0
        return aValue - bValue
      },
    },
    ...(result.value || { columns: [] }).columns.map((d: any) => {
      return {
        label: d,
        align: 'center',
        formatter(row: any) {
          let find = row.dateItems.find((v: any) => v.date === d)
          return find ? find[dataType.value] : ''
        },
        sortMethod: function (a: any, b: any) {
          let aValue = a.dateItems.find((v: any) => v.date === d)[dataType.value] || 0
          let bValue = b.dateItems.find((v: any) => v.date === d)[dataType.value] || 0
          return aValue - bValue
        },
        minWidth: 100,
        sortable: true,
      }
    }),
  ]
})
const columns2: any = computed(() => {
  let initColumns = [
    { type: 'selection', width: 55 },
    {
      label: '评卷员',
      prop: 'loginName',
      align: 'center',
      minWidth: 90,
      fixed: 'left',
      formatter(row: any) {
        return `${row.loginName}-${row.markerName}`
      },
    },
    // { label: '姓名', prop: 'markerName', align: 'center', minWidth: 120, fixed: 'left' },
  ]
  if (allTableData.value.length) {
    let pushColumns = allTableData.value[0].segmentScores.map((item: any) => {
      return {
        label: item.scoreStart,
        align: 'center',
        minWidth: 50,
        sortable: true,
        formatter(row: any) {
          return row.segmentScores.find((v: any) => v.scoreStart == item.scoreStart).rate
        },
        sortMethod: function (a: any, b: any) {
          let aRate = a.segmentScores.find((v: any) => v.scoreStart === item.scoreStart)?.rate
          let bRate = b.segmentScores.find((v: any) => v.scoreStart === item.scoreStart)?.rate
          return aRate - bRate
        },
      }
    })
    initColumns.push(...pushColumns)
  }
  return initColumns
})
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const rowChartOptions = computed(() => {
  if (!curRow.value) {
    return {}
  } else {
    if (dataType.value !== 'segmentScores') {
      const { dateItems } = curRow.value
      const xData = dateItems.map((v: any) => v.date)
      const yData = dateItems.map((v: any) => v[dataType.value])
      return {
        grid: {
          left: 60,
          right: 240,
          bottom: 40,
        },
        tooltip: { show: true, trigger: 'axis' },
        legend: { show: true },
        xAxis: {
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
          data: xData,
        },
        yAxis: {
          type: 'value',
        },
        series: [{ name: dataTypeLabelMap[dataType.value], type: 'line', data: yData }],
      }
    } else {
      const { dateItems, segmentScores } = curRow.value
      const xData = segmentScores.map((v: any) => v.scoreStart)

      return {
        grid: {
          left: 60,
          right: 60,
          bottom: 40,
        },
        tooltip: { show: true, trigger: 'axis' },
        legend: { show: true },
        xAxis: {
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
          data: xData,
        },
        yAxis: {
          type: 'value',
        },
        series: dateItems.map((item: any) => {
          return {
            name: item.date,
            type: 'line',
            data: item.segmentScores.map((v: any) => v.rate),
          }
        }),
      }
    }
  }
})
const lineChartOptions = computed(() => {
  let xData = allTableData.value.map((item) => item.loginName)
  // console.log('xData:', xData)
  // console.log('allTableData.value:', allTableData.value)
  // console.log(
  //   'allTableData.value.map((item) => item[dataType.value])',
  //   allTableData.value.map((item) => item[dataType.value])
  // )
  console.log(
    'yAxis',
    averageDatas.value,
    averageDatas.value.find((item: any) => {
      return item.markingGroupNumber == 0
    }),
    dataType.value,
    averageDatas.value.find((item: any) => {
      return item.markingGroupNumber == 0
    })?.[dataType.value === 'markingCount' ? 'avgMarkingCount' : dataType.value]
  )
  return {
    grid: {
      left: 60,
      right: 240,
      bottom: 40,
    },
    tooltip: { show: true, trigger: 'axis' },
    legend: { show: true },
    xAxis: {
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      data: xData,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: dataTypeLabelMap[dataType.value],
        type: 'line',
        // itemStyle: {
        // color: '#3AD500',
        // },
        data: allTableData.value.map((item) => item[dataType.value]),
        markLine: {
          data: [
            {
              name: '总体' + dataTypeLabelMap[dataType.value],
              yAxis: averageDatas.value.find((item: any) => {
                return (
                  item.markingGroupNumber ==
                  (mainStore.myUserInfo?.role === 'DEPUTY' ? mainStore.myUserInfo.markingGroupNumber : 0)
                )
              })?.[dataType.value === 'markingCount' ? 'avgMarkingCount' : dataType.value],
              label: {
                show: true,
                position: 'end',
              },
              lineStyle: {
                color: 'red',
                width: 3,
                type: 'solid',
              },
            },
            ...filterAverageDatas.value.map((item: any, index: number) => {
              return {
                name: `小组${item.markingGroupNumber}` + dataTypeLabelMap[dataType.value],
                // name:
                //   item.markingGroupNumber == 0
                //     ? '总体' + dataTypeLabelMap[dataType.value]
                //     : `小组${item.markingGroupNumber}` + dataTypeLabelMap[dataType.value],
                yAxis: item[dataType.value === 'markingCount' ? 'avgMarkingCount' : dataType.value],
                label: {
                  show: true,
                  position: 'end',
                },
                lineStyle: {
                  color: myColorList[index % myColorList.length],
                },
              }
            }),
          ],
        },
      },
    ],
  }
})
const multLineChartOptions = computed(() => {
  return {
    grid: {
      left: 60,
      right: 60,
      bottom: 40,
    },
    // tooltip: { show: true, trigger: 'axis' },
    legend: {
      show: true,
      type: 'scroll',
      animationDurationUpdate: 300,
      icon: 'circle',
      itemWidth: 10,
      itemGap: 20,
      textStyle: {
        // color: '#556677'
      },
    },
    xAxis: {
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      data: multLineXdatas.value,
    },
    yAxis: {
      type: 'value',
    },
    series: multipleSelection.value.map((item: any) => {
      return {
        name: item.loginName,
        type: 'line',
        // itemStyle: {
        //   color: '#3AD500',
        // },
        data: item.segmentScores.map((v: any) => v.rate),
      }
    }),
  }
})
const onSearch = () => {
  fetch({ ...fetchModel.value, markingGroupNumber: undefined }).then((res) => {
    console.log('rrr', allResult.value, result.value)
  })
}
onOptionInit(onSearch)
watch(groupListWithAll, () => {
  if (mainStore.myUserInfo && mainStore.myUserInfo.role === 'DEPUTY') {
    setTimeout(() => {
      changeModelValue('group')([mainStore.myUserInfo?.markingGroupNumber])
    }, 0)
  }
})
</script>
<style scoped lang="scss">
.personnel-compare-view {
  background-color: #fff;
  .out-chart-box {
    position: relative;
  }
  // .out-chart-box {
  //   height: 300px;
  // }
  .row-chart {
    position: absolute;
    top: 0;
    left: 0;
    height: 260px;
    width: 100%;
    z-index: 101;
    background-color: #fff;
    .close-icon {
      position: absolute;
      right: 20px;
      top: 10px;
      z-index: 1;
      font-size: 26px;
      color: #666;
      cursor: pointer;
      &:hover {
        color: $color--primary;
      }
    }
  }
  .chart-box {
    height: 260px;
    position: relative;
    .right-box {
      position: absolute;
      right: 0;
      top: 0;
      width: 180px;
      height: 100%;
      z-index: 100;
      overflow: auto;
      .legend-item {
        display: flex;
        margin-bottom: 5px;
        align-items: flex-start;
        font-size: 12px;
        .color {
          width: 12px;
          height: 12px;
          border-radius: 2px;
          margin-top: 2px;
          margin-right: 5px;
        }
        .label {
          flex: 1;
          color: #666;
        }
      }
    }
  }
}
</style>
