<template>
  <ChartsContainer title="标准执行">
    <div style="height: 100%; flex-direction: column; display: flex;">
      <div class="cards-container">
        <div class="card-item" v-for=" item in cardData " :key="item.label">
          <div>{{ item.label }}</div>
          <div :style="'--color:' + item.color">{{ item.value }}</div>
        </div>
      </div>
      <div class="charts-container">
        <div class="charts-container-item">
          <div class="charts-container-name">问题分布项</div>
          <div class="charts-container-content" ref="problem" v-show="radarData.grounp.length > 1" />
          <div class="charts-container-content" v-show="radarData.grounp.length < 1" style="margin-top: 80px; text-align: center; color: #fff">
            {{ radarData.grounp.length < 1 ? '暂无数据' : '' }}
          </div>
        </div>
        <div class="charts-container-item">
          <div class="charts-container-name">测试总错题数</div>
          <div class="charts-container-content" ref="wrongAnswer"/>
        </div>
      </div>
    </div>
  </ChartsContainer>
</template>

<script setup>
import ChartsContainer from '../ChartsContainer.vue';
import { computed, ref, reactive } from 'vue';
import { useTimeOut } from './useTimeOut';
import { getSiteProfile, getDeptProfile, getUserProfile, getPortrait } from '@/api/item/items'
import { useECharts } from '@/hooks/useEcharts.js';
const props = defineProps({
  type: {
    type: String,
    default: '' // team, department, station
  }
})
const problem = ref(null)
const wrongAnswer = ref(null)
const portraitData = ref({
})
const profileData = ref({
  rankingStats: {}
})
const params = inject('provideParams')
const cardData = computed(() => {
  return [
    props.type ? { 
      label: '巡检排名', 
      value: `${portraitData.value.stationRanking || 0} / ${portraitData.value.stationTotal || 0}`, 
      color: '#35D8FF' 
    } : undefined,
    { label: '巡检总问题数', value: portraitData.value.sumCount || 0, color: '#35D8FF' },
    { label: '按期整改', value: portraitData.value.onTimeCompletedCount || 0, color: '#FFC061' },
    { label: '超期整改', value: portraitData.value.overTimeCompletedCount || 0, color: '#DD4D43' },
    props.type ? {
      label: '测试排名',
      value: `${profileData.value.rankingStats.siteRanking || 0} / ${profileData.value.rankingStats.siteTotalDepts || profileData.value.rankingStats.siteTotalUsers || 0 }`, 
      color: '#35D8FF'
    } : undefined,
    !props.type ? {
      label: '测试平均分',
      value: profileData.value.scoreStats && profileData.value.scoreStats.totalAvgScore
        || profileData.value.avgScore || 0, color: '#35D8FF'
    } : undefined,
    !props.type ? { label: '测试总错题数', value: profileData.value.totalErrors || 0, color: '#35D8FF' } : undefined,
  ].filter(Boolean)
})
const radarData = reactive({
  legend: [],
  grounp: [],
  data: []
})
const problemOption = computed(() => {
  return {

    legend: props.type ? {
      show: false
    } : {
      data: radarData.legend,
      top: 10,
      textStyle: {
        color: '#fff',
        fontSize: 12
      }
    },
    radar: {
      indicator: radarData.grounp,
      shape: 'polygon',
      splitNumber: 4,
      radius: '50%',
      center: [ '50%', radarData.legend.length ? '60%' : '50%' ], // 缩小雷达图并居中，为label留出空间
      axisName: {
        color: '#fff',
        fontSize: 12
      },
    },
    series: [ {
      type: 'radar',
      data: radarData.data,
      emphasis: {
        lineStyle: {
          width: 4
        }
      }
    } ],
    tooltip: {
      trigger: 'item'
    }
  };
})
useECharts(problem, problemOption)

const wrongAnswerData = reactive({
  legend: [],
  grounp: [
    { text: '操作执行' },
    { text: '传达学习' },
    { text: '班组管理' },
    { text: '工作纪律' },
    { text: '设施设备' },
    { text: '通道样貌' }
  ],
  data: []
})
const wrongAnswerOption = computed(() => {
  return {
    legend: {
      data: wrongAnswerData.legend,
      top: 15,
      textStyle: {
        color: '#fff',
        fontSize: 12
      }
    },
    radar: {
      indicator: wrongAnswerData.grounp,
      shape: 'polygon',
      splitNumber: 4,
      radius: '50%',
      center: [ '50%', wrongAnswerData.legend.length ? '60%' : '50%' ], // 缩小雷达图并居中，为label留出空间
      axisName: {
        color: '#fff',
        fontSize: 12
      },
    },
    series: [ {
      type: 'radar',
      data: wrongAnswerData.data,
      emphasis: {
        lineStyle: {
          width: 4
        }
      }
    } ],
    tooltip: {
      trigger: 'item'
    }
  };
})
useECharts(wrongAnswer, wrongAnswerOption)
const color = ['#408CFF', '#58A55C', '#DD4D43', '#FAC858']
const problemRadarDataHandler = (result = []) => {
  const grounpObj = result.reduce((cur, acc) => {
    if (cur[ acc.deptName ]) {
      cur[ acc.deptName ].push(acc)
    } else {
      cur[ acc.deptName ] = [ acc ]
    }
    return cur
  }, {})

  const grounp = Object.entries(grounpObj)

  radarData.legend =grounp.length > 1 ? grounp.map(item => {
    return item[ 0 ]
  }) : []


  radarData.grounp = grounp[ 0 ] && grounp[ 0 ][ 1 ] ? grounp[ 0 ][ 1 ].map(item => ({ text: item.name })) : []
  radarData.data = grounp.map((item, index) => {
    return {
      name: props.type === 'team' ? '问题分布项' : item[ 0 ],
      value: item[ 1 ].map(attr => attr.total),
      // // 为每个数据系列设置不同的颜色
      color: color[ index % color.length ],
      areaStyle: {
        opacity: 0.5,
        color: color[ index % color.length ],
      },
      lineStyle: {
        width: 2
      },
      itemStyle: {
        borderWidth: 2,
        color: color[ index % color.length ],
      }
    }
  })
}


useTimeOut(() => {
  if (!props.type) {
    params.value.deptId && getSiteProfile({ siteId: params.value.deptId }).then(res => {
      profileData.value = res.data
      const { deptCategoryErrors = [] } = res.data

      wrongAnswerData.legend = deptCategoryErrors.map(item => item.deptName)      
      wrongAnswerData.data = deptCategoryErrors.map((item, index) => {
        return {
          name: item.deptName,
          value: wrongAnswerData.grounp.map(attr => {
            const rowData = item.categoryErrors.find(row => row.categoryName === attr.text) || { errorCount: 0 }
            return rowData.errorCount
          }),
          areaStyle: {
            opacity: 0.5,
            color: color[ index % color.length ],
          },
          lineStyle: {
            width: 2
          },
          itemStyle: {
            borderWidth: 2,
            color: color[ index % color.length ],
          }
        }
      })
    })
  } else {
    const invokerApi = props.type === 'department' ? 
      params.value.deptId && getDeptProfile({ deptId: params.value.deptId || '' }) : 
      props.type === 'personal' ? getUserProfile({ userId: params.value.deptId || '' }) : getUserProfile({ deptId: params.value.deptId || '' }) 
    params.value.deptId  && invokerApi.then(res => {
      profileData.value = res.data
      const deptCategoryErrors = [res.data]

      wrongAnswerData.legend = []
      wrongAnswerData.data = deptCategoryErrors.map((item, index) => {
        return {
          name: item.deptName,
          value: wrongAnswerData.grounp.map((attr, index) => {
            const rowData = item.categoryErrors.find(row => row.categoryName === attr.text) || { errorCount: 0 }
            return rowData.errorCount
          }),
          color: color[ index % color.length ],
          areaStyle: {
            opacity: 0.5,
            color: color[ index % color.length ],
          },
          lineStyle: {
            width: 2
          },
          itemStyle: {
            borderWidth: 2,
            color: color[ index % color.length ],
          }
        }
      })
    })
  }
  const portraitParams = {}
 
   if (props.type === 'manager') {
    portraitParams.checkedDepartmentId = params.value.deptId
  } else if (props.type === 'brigade') {
    portraitParams.checkedBrigadeId = params.value.deptId
  } else if (props.type === 'team') {
    portraitParams.checkedTeamId = params.value.deptId
  } else if (props.type === 'personal') {
    portraitParams.checkedUserId = params.value.deptId
  } else {
    portraitParams.checkedSiteId = params.value.deptId
  }

  params.value.deptId && getPortrait(portraitParams).then(res => {
    portraitData.value = res.data || {}
    const { checkLargeScreenCommonDtoList = [] } = res.data || {}
    problemRadarDataHandler(checkLargeScreenCommonDtoList.filter(item => item && item.deptName !== '总数'))
  })
}, [ params ])

</script>

<style lang="scss" scoped>
.cards-container {
  display: flex;
  align-items: center;
  column-gap: 15px;
  padding-bottom: 15px;

  .card-item {
    flex: 1;
    color: #fff;
    font-weight: bold;
    font-size: 18px;
    text-align: center;
    background: url('../../../../../assets/images/cardBg.png') no-repeat;
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    row-gap: 10px;
    border-radius: 5px;
    font-weight: bold;
    padding: 10px 5px;

    div:nth-child(1) {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      min-width: 0;
    }

    div:nth-child(2) {
      font-size: 20px;
      color: var(--color)
    }
  }
}

.charts-container {
  display: flex;
  flex: 1;

  .charts-container-item {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .charts-container-name {
    color: #fff;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;

    &::before {
      content: '';
      display: inline-block;
      border-left: 9px solid #1CB6FF;
      border-top: 8px solid transparent;
      border-right: 9px solid transparent;
      border-bottom: 8px solid transparent;
    }
  }

  .charts-container-content {
    flex: 1;
    width: 100%;
  }
}
</style>