<script setup>
import { defineProps, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts' // 引入 ECharts
import LTitle from '@/components/LTitle.vue'

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
})

const chartInstance = ref(null) // ECharts 实例
const chartRef = ref(null) // 图表容器 DOM
const riskLevel = ref('')
const riskLevelText = ref('')
const riskLevelClass = ref('')
const riskDescription = ref('')
const riskInfoList = ref([
  {
    level: '无风险',
    description: '无任何不良风险记录',
    class: 'text-green-600',
  },
  { level: '低风险', description: '涉稳、寻衅滋事', class: 'text-yellow-500' },
  {
    level: '中风险',
    description: '吸毒、涉毒、犯罪前科',
    class: 'text-orange-500',
  },
  {
    level: '高风险',
    description: '涉案人员、在逃、犯罪嫌疑人',
    class: 'text-red-500',
  },
])

// 根据风险等级动态设置图表配置
function getChartOption(level) {
  const valueMap = {
    A: 10, // 无风险
    F: 30, // 低风险
    C: 60, // 中风险
    D: 60, // 中风险
    B: 90, // 高风险
    E: 90, // 高风险
    default: 0, // 未知风险
  }
  const labelNameMap = {
    A: '无风险', // 无风险
    F: '低风险', // 低风险
    C: '中风险', // 中风险
    D: '中风险', // 中风险
    B: '高风险', // 高风险
    E: '高风险', // 高风险
    default: '未知风险', // 未知风险
  }
  const value = valueMap[level] || valueMap.default
  const labelName = labelNameMap[level] || labelNameMap.default

  // 根据不同风险等级设置不同的颜色方案
  let colorGradient = []
  let detailColor = '#333'

  switch (level) {
    case 'A': // 无风险
      colorGradient = [
        { offset: 0, color: '#52c41a' },
        { offset: 1, color: '#7fdb42' },
      ]
      detailColor = '#52c41a'
      break
    case 'F': // 低风险
      colorGradient = [
        { offset: 0, color: '#faad14' },
        { offset: 1, color: '#ffc53d' },
      ]
      detailColor = '#faad14'
      break
    case 'C': // 中风险
    case 'D':
      colorGradient = [
        { offset: 0, color: '#fa8c16' },
        { offset: 1, color: '#ffa940' },
      ]
      detailColor = '#fa8c16'
      break
    case 'B': // 高风险
    case 'E':
      colorGradient = [
        { offset: 0, color: '#f5222d' },
        { offset: 1, color: '#ff4d4f' },
      ]
      detailColor = '#f5222d'
      break
    default:
      colorGradient = [
        { offset: 0, color: '#999' },
        { offset: 1, color: '#ccc' },
      ]
      detailColor = '#999'
  }

  return {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        radius: '100%',
        center: ['50%', '70%'],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, colorGradient),
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.2)',
        },
        progress: {
          show: true,
          width: 20,
          roundCap: true,
          clip: false,
        },
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 20,
            color: [
              [
                1,
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  {
                    offset: 0,
                    color: 'rgba(0, 0, 0, 0.1)',
                  },
                  {
                    offset: 1,
                    color: 'rgba(0, 0, 0, 0.05)',
                  },
                ]),
              ],
            ],
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: true,
          distance: -26,
          length: 5,
          lineStyle: {
            color: '#999',
            width: 2,
          },
        },
        axisLabel: {
          show: true,
          distance: -8,
          fontSize: 12,
          color: '#999',
          formatter: function (value) {
            if (value % 20 === 0) {
              return value
            }
            return ''
          },
        },
        anchor: {
          show: false,
        },
        pointer: {
          icon: 'triangle',
          iconStyle: {
            color: detailColor,
            borderColor: detailColor,
            borderWidth: 1,
          },
          offsetCenter: ['7%', '-67%'],
          length: '10%',
          width: 15,
        },
        detail: {
          valueAnimation: true,
          fontSize: 30,
          fontWeight: 'bold',
          color: detailColor,
          offsetCenter: [0, '-25%'],
          formatter: function (value) {
            return `{value|${value}分}\n{level|${labelName}}`
          },
          rich: {
            value: {
              fontSize: 30,
              fontWeight: 'bold',
              color: detailColor,
              padding: [0, 0, 5, 0],
            },
            level: {
              fontSize: 14,
              fontWeight: 'normal',
              color: detailColor,
              padding: [5, 0, 0, 0],
            },
          },
        },
        data: [
          {
            value,
          },
        ],
      },
    ],
  }
}

// 获取风险描述
function getRiskDescription(level) {
  switch (level) {
    case 'A':
      return '根据综合分析，当前报告未检测到任何不良风险记录。各项指标表现正常，总体状况良好，可以放心处理。'
    case 'F':
      return '当前报告显示存在低风险情况，主要涉及涉稳或寻衅滋事类问题。建议关注相关指标变化，保持适当警惕。'
    case 'C':
    case 'D':
      return '注意！当前报告显示存在中等风险，涉及吸毒、涉毒或有犯罪前科等问题。建议进一步核实相关情况，谨慎处理。'
    case 'B':
    case 'E':
      return '警告！当前报告显示高度风险状态，检测到涉案人员、在逃人员或犯罪嫌疑人特征。请立即采取相应安全措施，并向相关部门报告。'
    default:
      return '无法获取风险评估信息，请检查数据来源。'
  }
}

// 根据风险等级动态设置文本和样式
function setRiskProperties(level) {
  switch (level) {
    case 'A':
      riskLevelText.value = '无风险'
      riskLevelClass.value = 'text-green-600'
      break
    case 'F':
      riskLevelText.value = '低风险'
      riskLevelClass.value = 'text-yellow-500'
      break
    case 'C':
    case 'D':
      riskLevelText.value = '中风险'
      riskLevelClass.value = 'text-orange-500'
      break
    case 'B':
    case 'E':
      riskLevelText.value = '高风险'
      riskLevelClass.value = 'text-red-500'
      break
    default:
      riskLevelText.value = '未知风险'
      riskLevelClass.value = 'text-gray-500'
  }

  riskDescription.value = getRiskDescription(level)
}

// 初始化图表
function initChart() {
  if (!chartRef.value) return

  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartRef.value)
  }

  const option = getChartOption(riskLevel.value)
  chartInstance.value.setOption(option)

  // 处理窗口大小变化
  window.addEventListener('resize', () => {
    if (chartInstance.value) {
      chartInstance.value.resize()
    }
  })
}

// 更新图表
function updateChart(level) {
  if (!chartInstance.value) return

  const option = getChartOption(level)
  chartInstance.value.setOption(option, true)
}

onMounted(() => {
  riskLevel.value = props.data.risk_level
  setRiskProperties(riskLevel.value)
  initChart()
})

watch(
  () => props.data.risk_level,
  newLevel => {
    riskLevel.value = newLevel
    setRiskProperties(newLevel)
    updateChart(newLevel)
  }
)

// 在组件销毁前清理
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }
  window.removeEventListener('resize', () => chartInstance.value?.resize())
})
</script>

<template>
  <div class="card">
    <div class="span-2xl font-bold" :class="riskLevelClass">
      <div ref="chartRef" class="chart-container"></div>
    </div>

    <!-- 风险描述区域 -->
    <div class="risk-description" :class="riskLevelClass">
      {{ riskDescription }}
    </div>

    <div class="mt-6">
      <LTitle title="信息解读" type="blue-green" />
      <div class="mt-4 rounded-lg bg-slate-100/80 px-4 py-2 space-y-4">
        <div v-for="(item, index) in riskInfoList" :key="index" class="flex items-center justify-between">
          <span class="font-bold" :class="[item.class]">
            {{ item.level }}
          </span>
          <span class="span-gray-700">
            {{ item.description }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 210px;
}

.risk-description {
  margin-top: 10px;
  padding: 10px 15px;
  background-color: #f5f5f5;
  border-radius: 6px;
  color: #333;
  font-size: 13px;
  line-height: 1.5;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}
</style>
