<script setup>
import { getMemberAttrAnalysis } from '../api'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'

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

const props = defineProps(['attrId', 'attrType'])

const detail = ref({
  str_analysis: {
    items: []
  },
  num_analysis: {
    avg: '0',
    min: '0',
    max: '0',
    first_quarter: '0',
    median: '0',
    three_quarters: '0'
  }
})

// 1字符串 2 数字
const type = computed(() => {
  return props.attrType == 2 || props.attrType == 3 ? 2 : 1
})

async function fetchInfo() {
  const res = await getMemberAttrAnalysis({ attr_id: props.attrId, attr_type: type.value })
  detail.value = res.data
}
watch(() => props.attrId, fetchInfo)

const options = computed(() => {
  return {
    color: ['#af1c40', '#c17933', '#8f0034', '#d45548', '#ab3259', '#dec34c', '#8b8920', '#a25a6d'],
    tooltip: { trigger: 'item', formatter: '{b}: {c}<br />{d}%' },
    series: [
      {
        type: 'pie',
        label: { formatter: '{b}\n{d}%' },
        itemStyle: { borderRadius: 6 },
        radius: [0, '70%'],
        data: detail.value.str_analysis.items.map(item => {
          return { name: item.group_name, value: item.total }
        })
      }
    ]
  }
})
</script>

<template>
  <div>
    <el-form-item label="字段值分布">
      <template v-if="type === 2">
        <div>
          <el-form-item label-width="auto" label="平均值">{{ detail.num_analysis.avg }}</el-form-item>
          <el-form-item label-width="auto" label="最大值">{{ detail.num_analysis.max }}</el-form-item>
          <el-form-item label-width="auto" label="最小值">{{ detail.num_analysis.min }}</el-form-item>
        </div>
        <div style="margin-left: 100px">
          <el-form-item label-width="auto" label="1/4位数">{{ detail.num_analysis.first_quarter }}</el-form-item>
          <el-form-item label-width="auto" label="中位数">{{ detail.num_analysis.median }}</el-form-item>
          <el-form-item label-width="auto" label="3/4位数">{{ detail.num_analysis.three_quarters }}</el-form-item>
        </div>
      </template>
      <template v-else>
        <v-chart class="chart" :option="options" autoresize ref="chart" style="height: 200px" v-if="detail.str_analysis.items.length" />
        <el-empty description="暂无数据" v-else />
      </template>
    </el-form-item>
  </div>
</template>
