<template>
  <a-modal
    :visible="visible"
    :title="title"
    :width="'60%'"
    :bodyStyle="{ height: '80vh', padding: '20px' }"
    :footer="null"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="(value) => emit('update:visible', value)"
    :centered="true"
    :destroyOnClose="true"
    :maskClosable="false"
  >
    <div style="height: 100%; display: flex; flex-direction: column;">
      <!-- 加载状态 -->
      <div v-if="chartLoading" style="text-align: center; padding: 50px;">
        <a-spin size="large" />
      </div>
      
      <template v-else>
        <!-- 指标信息 -->
        <div style="margin-bottom: 16px; padding: 12px; background: #f5f7fa; border-radius: 4px;">
          <a-row :gutter="16">
            <a-col :span="4"><strong>指标编码：</strong>{{ row?.mtrcNo }}</a-col>
            <a-col :span="12" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><strong>指标名称：</strong>{{ row?.mtrcName }}</a-col>
            <a-col :span="4"><strong>采集频率：</strong>{{ getFreqText(row?.collFreq) }}</a-col>
            <a-col :span="4"><strong>数据条数：</strong>{{ chartDataList.length }}</a-col>
          </a-row>
        </div>
        
        <!-- 时间选择表单 -->
        <div style="margin-bottom: 16px; padding: 12px; background: #f9f9f9; border-radius: 4px;">
          <a-row :gutter="16">
            <a-col :span="16">
              <BasicForm @register="registerForm" />
            </a-col>
            <a-col :span="8">
              <a-space :size="5" style="float: right;">
                <a-button type="primary" @click="searchQuery">查询</a-button>
                <a-button @click="searchReset">重置</a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>

        <a-tabs v-model:activeKey="activeTabKey" @change="handleTabChange" style="flex: 1; display: flex; flex-direction: column;">
          <a-tab-pane key="list" tab="指标值" style="height: 100%;">
            <a-table
              :dataSource="chartDataList"
              :columns="dataColumns"
              :pagination="{ pageSize: 10 }"
              size="small"
              :scroll="{ y: 'calc(70vh - 200px)' }"
              bordered
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.key === 'riskLevel'">
                  <a-badge 
                    :status="getRiskLevelStatus(record.riskLevel)" 
                    :text="getRiskLevelText(record.riskLevel)" 
                  />
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          
          <a-tab-pane key="line" tab="走势图" style="height: 100%;">
            <div ref="lineChartRef" style="width: 100%; height: calc(70vh - 150px);"></div>
          </a-tab-pane>
          
          <a-tab-pane key="bar" tab="柱状图" style="height: 100%;">
            <div ref="barChartRef" style="width: 100%; height: calc(70vh - 150px);"></div>
          </a-tab-pane>
          
          <a-tab-pane key="pie" tab="风险分布" style="height: 100%;">
            <div ref="pieChartRef" style="width: 100%; height: calc(70vh - 150px);"></div>
          </a-tab-pane>
        </a-tabs>
      </template>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { queryAllList,queryByMtrcNo } from '../../MetricReport.api'
import { BasicForm, useForm } from '/@/components/Form/index'
import { FormSchema } from '/@/components/Table'

interface Props {
  visible: boolean
  title: string
  row?: any
}

const props = defineProps<Props>()
const emit = defineEmits(['update:visible', 'ok', 'cancel'])

// 响应式数据
const activeTabKey = ref('list')
const chartLoading = ref(false)
const chartDataList = ref<any[]>([])

const curMtrcSet = ref<any>({})


// 图表实例
const lineChartRef = ref<HTMLDivElement | null>(null)
const barChartRef = ref<HTMLDivElement | null>(null)
const pieChartRef = ref<HTMLDivElement | null>(null)

let lineChart: echarts.ECharts | null = null
let barChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null

// 表单配置
const searchFormSchema: FormSchema[] = [
  {
    label: '开始日期',
    field: 'stFillTime',
    component: 'DatePicker',
    colProps: { xs: 12, sm: 12, md: 12, lg: 8, xl: 8 },
    defaultValue: (new Date().getFullYear() - 3) + "-" + (new Date().getMonth() + 1) + "-" + (new Date().getDate()),
  },
  {
    label: '结束日期',
    field: 'endFillTime',
    defaultValue: new Date(),
    component: 'DatePicker',
    colProps: { xs: 12, sm: 12, md: 12, lg: 8, xl: 8 },
  },
]

// 初始化表单
const [registerForm, { setFieldsValue, getFieldsValue }] = useForm({
  labelWidth: 100,
  schemas: searchFormSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 }
})

// 表格列定义
const dataColumns = [
  { title: '填报时间', dataIndex: 'fillTime', key: 'fillTime', width: 150, render: (text) => text || '无数据' },
  { title: '填报值', dataIndex: 'fillVals', key: 'fillVals', width: 100 },
  { 
    title: '风险等级', 
    dataIndex: 'riskLevel', 
    key: 'riskLevel', 
    width: 100
  },
]

// 处理确定
const handleOk = () => {
  emit('ok')
  emit('update:visible', false)
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
  // 销毁图表实例
  cleanupCharts()
}

// 清理图表实例
const cleanupCharts = () => {
  if (lineChart) {
    lineChart.dispose()
    lineChart = null
  }
  if (barChart) {
    barChart.dispose()
    barChart = null
  }
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
}

// 获取采集频率文本
const getFreqText = (freq) => {
  const map = {
    1: '每日',
    2: '每周',
    3: '每月',
    4: '每季度',
    5: '每半年',
    6: '每年'
  }
  return map[freq] || freq
}

// 获取风险等级状态
const getRiskLevelStatus = (level) => {
  if (level === 1) return 'success'
  if (level === 2) return 'processing'
  if (level === 3) return 'error'
  return 'default'
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  if (level === 1) return '低风险'
  if (level === 2) return '中风险'
  if (level === 3) return '高风险'
  return '其他'
}

// 格式化时间
const formatTime = (time, collFreq) => {
  if (!time) return ''
  // 确保 time 是字符串
  const timeStr = String(time)
  
  // 确保 collFreq 是数字
  const freq = Number(collFreq) || 0

  try {
    if (freq == 1) {
      return timeStr.length >= 10 ? timeStr.substr(5, 5) : timeStr // MM-DD
    } else if (freq == 2) {
      return timeStr.length >= 10 ? timeStr.substr(5, 5) : timeStr // MM-DD
    } else if (freq == 3 || freq === 4 || freq === 5) {
      return timeStr.length >= 7 ? timeStr.substr(0, 7) : timeStr // YYYY-MM
    } else if (freq == 6) {
      return timeStr.length >= 4 ? timeStr.substr(0, 4) : timeStr // YYYY
    } else {
      return timeStr.length >= 17 ? timeStr.substr(11, 16) : timeStr // HH:mm
    }
  } catch (error) {
    return timeStr
  }
}

// 加载数据
const loadData = async () => {
  if (!props.row) return
  
  chartLoading.value = true
  
  try {
    // 获取表单数据
    const formData = getFieldsValue()

    queryByMtrcNo({
      mtrcNo: props.row.mtrcNo,
    }).then(res => {
      curMtrcSet.value = res || {}
    })
    
    // 从接口获取数据
    const res = await queryAllList({
      mtrcNos: props.row.mtrcNo,
      stFillTime: formData.stFillTime,
      endFillTime: formData.endFillTime
    })
    
    // 处理数据
    if (res && res.dataList) {
      chartDataList.value = res.dataList.map(item => {
        const formattedTime = formatTime(item.fillTime, curMtrcSet.value.collFreq)
        return {
          ...item,
          fillTime: formattedTime
        }
      })
    } else {
      chartDataList.value = []
    }
    
    await nextTick()
    
    // 根据当前激活的标签页初始化对应的图表
    setTimeout(() => {
      if (activeTabKey.value === 'line') {
        initLineChart()
      } else if (activeTabKey.value === 'bar') {
        initBarChart()
      } else if (activeTabKey.value === 'pie') {
        initPieChart()
      }
    }, 200)
  } catch (error) {
    chartDataList.value = []
  } finally {
    chartLoading.value = false
  }
}

// 查询
const searchQuery = () => {
  loadData()
}

// 重置
const searchReset = () => {

  setFieldsValue({
    stFillTime: (new Date().getFullYear() - 3) + "-" + (new Date().getMonth() + 1) + "-" + (new Date().getDate()),
    endFillTime: new Date()
  })
  loadData()
}

// 初始化所有图表
const initAllCharts = () => {
  // 注意：由于标签页可能未激活，容器可能不存在，所以这里不直接初始化
  // 图表会在标签切换时初始化
}

// 获取图表数据
const getChartData = () => {
  const categories = chartDataList.value.map(item => item.fillTime)
  const values = chartDataList.value.map(item => {
    const val = parseFloat(item.fillVals) || 0
    return val
  })
  
  // 按风险等级统计饼图数据
  const riskCount = {
    1: 0, // 低风险
    2: 0, // 中风险
    3: 0  // 高风险
  }
  
  chartDataList.value.forEach(item => {
    if (item.riskLevel && riskCount[item.riskLevel] !== undefined) {
      riskCount[item.riskLevel]++
    }
  })
  
  const pieData = []
  
  // 按固定顺序添加数据项，并指定颜色
  if (riskCount[1] > 0) {
    pieData.push({ value: riskCount[1], name: '低风险', itemStyle: { color: '#73D13D' } })
  }
  if (riskCount[2] > 0) {
    pieData.push({ value: riskCount[2], name: '中风险', itemStyle: { color: '#FA8C16' } })
  }
  if (riskCount[3] > 0) {
    pieData.push({ value: riskCount[3], name: '高风险', itemStyle: { color: '#CF1322' } })
  }
  
  return { categories, values, pieData }
}

// 初始化折线图
const initLineChart = () => {
  if (!lineChartRef.value) {
    return
  }
  
  if (lineChart) {
    lineChart.dispose()
  }
  
  lineChart = echarts.init(lineChartRef.value)
  
  const { categories, values } = getChartData()
  
  const option = {
    title: {
      text: `${props.row?.mtrcName} - 趋势分析`,
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        return `${params[0].name}<br/>${params[0].marker}${params[0].seriesName}: ${params[0].value}`
      }
    },
    grid: {
      left: '8%',
      right: '5%',
      top: '15%',
      bottom: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories.length > 0 ? categories : ['无数据'],
      axisLabel: {
        rotate: categories.length > 10 ? 30 : 0,
        interval: categories.length > 20 ? 2 : 0
      },
      axisLine: {
        lineStyle: { color: '#999' }
      }
    },
    yAxis: {
      type: 'value',
      name: `单位[${props.row?.unit || ''}]`,
      nameLocation: 'middle',
      nameGap: 45,
      splitLine: {
        lineStyle: { type: 'dashed', color: '#eee' }
      }
    },
    series: [{
      name: props.row?.mtrcName || '指标数值',
      data: values.length > 0 ? values : [0],
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 3,
        color: '#409eff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
        ])
      },
      markPoint: {
        data: [
          { type: 'max', name: '最大值' },
          { type: 'min', name: '最小值' }
        ]
      },
      markLine: {
        data: [
          { type: 'average', name: '平均值' }
        ]
      }
    }]
  }
  
  lineChart.setOption(option)
  lineChart.resize()
}

// 初始化柱状图
const initBarChart = () => {
  if (!barChartRef.value) {
    return
  }
  
  if (barChart) {
    barChart.dispose()
  }
  
  barChart = echarts.init(barChartRef.value)
  
  const { categories, values } = getChartData()
  
  const option = {
    title: {
      text: `${props.row?.mtrcName} - 对比分析`,
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function(params) {
        return `${params[0].name}<br/>${params[0].marker}${params[0].seriesName}: ${params[0].value}`
      }
    },
    grid: {
      left: '8%',
      right: '5%',
      top: '15%',
      bottom: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories.length > 0 ? categories : ['无数据'],
      axisLabel: {
        rotate: categories.length > 10 ? 30 : 0,
        interval: categories.length > 20 ? 2 : 0
      },
      axisLine: {
        lineStyle: { color: '#999' }
      }
    },
    yAxis: {
      type: 'value',
      name: `单位[${props.row?.unit || ''}]`,
      nameLocation: 'middle',
      nameGap: 45,
      splitLine: {
        lineStyle: { type: 'dashed', color: '#eee' }
      }
    },
    series: [{
      name: props.row?.mtrcName || '指标数值',
      data: values.length > 0 ? values : [0],
      type: 'bar',
      barWidth: '50%',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ]),
        borderRadius: [6, 6, 0, 0]
      },
      label: {
        show: values.length <= 20,
        position: 'top',
        color: '#333',
        fontSize: 11,
        formatter: '{c}'
      },
      markPoint: {
        data: [
          { type: 'max', name: '最大值' },
          { type: 'min', name: '最小值' }
        ]
      }
    }]
  }
  
  barChart.setOption(option)
  barChart.resize()
}

// 初始化饼图
const initPieChart = () => {
  if (!pieChartRef.value) {
    return
  }
  
  if (pieChart) {
    pieChart.dispose()
  }
  
  pieChart = echarts.init(pieChartRef.value)
  
  const { pieData } = getChartData()
  
  if (pieData.length === 0) {
    pieData.push({ value: 1, name: '暂无数据' })
  }
  
  const option = {
    title: {
      text: `${props.row?.mtrcName} - 风险分布`,
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>{c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 20,
      left: 'center',
      itemWidth: 25,
      itemHeight: 14
    },
    series: [{
      name: '风险分布',
      type: 'pie',
      radius: ['45%', '70%'],
      center: ['50%', '45%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        position: 'outside',
        formatter: '{b}: {d}%',
        fontSize: 11
      },
      emphasis: {
        scale: true,
        label: { show: true, fontWeight: 'bold' }
      },
      data: pieData
    }]
  }
  
  pieChart.setOption(option)
  pieChart.resize()
}

// 标签切换处理
const handleTabChange = (key) => {
  setTimeout(() => {
    if (key === 'line') {
      initLineChart()
    } else if (key === 'bar') {
      initBarChart()
    } else if (key === 'pie') {
      initPieChart()
    }
  }, 100)
}

// 监听可见性变化
watch(() => props.visible, async (newVal) => {
  if (newVal) {
    activeTabKey.value = 'list' // 默认选中列表
    await loadData()
  } else {
    cleanupCharts()
  }
})
</script>

<style scoped>
</style>