<template>
  <view class="inspection-stats-charts">
    <!-- 时间筛选器 -->
    <view class="time-filter-section">
      <view class="filter-row">
        <StaticsTab v-model="activeTimeRange" :tabs="timeRangeOptions" active-color="#4873E3"
          @change="handleTimeRangeChange" />
        <view v-if="activeTimeRange === 'custom'" class="custom-time-section">
          <uni-datetime-picker v-model="dateRange" type="daterange" rangeSeparator="至" @change="handleDateRangeChange"
            class="date-range-picker" :clear-icon="false"/>
          <text class="days-count">共 {{ totalDays }} 天</text>
        </view>
      </view>
    </view>

    <!-- 计划安排总览 - 面积图 -->
    <view class="stats-card">
      <view class="chart-container">
        <text class="chart-title">计划安排总览</text>
        <view class="chart-wrapper">
          <!-- 使用ECharts实现的面积图 -->
          <view id="lineChart" class="echarts-canvas"></view>
        </view>
      </view>
    </view>

    <!-- 日常任务检查指标累计分布 - 雷达图 -->
    <view class="stats-card">
      <view class="chart-container">
        <text class="chart-title">日常任务检查指标累计分布</text>
        <view class="chart-wrapper">
          <!-- 使用ECharts实现的雷达图 -->
          <view id="radarChart" class="echarts-canvas"></view>
        </view>
      </view>
    </view>

    <!-- 任务明细统计表 -->
    <view class="stats-card">
      <view class="table-container">
        <text class="chart-title">任务明细统计</text>
        <statistic-table :columns="tableColumns" :data="tableData">
          <template #column-frequency="{ row, index }">
            {{ `${row.ruleTypeDesc}${row.ruleTypeNum}次` }}
          </template>
        </statistic-table>
      </view>
    </view>
  </view>
</template>

<script>

import { calculateTimeRange } from '@/utils/formatUtils.js';
import StaticsTab from './StaticsTab.vue';
import * as echarts from 'echarts';
import { getPlanOverview, getDailyTaskMetrics, getTaskDetailStats } from '@/api/inspectionStatistics/inspectionStatistics.js';
export default {
  name: 'InspectionStatsCharts',
  components: {
    StaticsTab
  },
  props: {
    // 时间范围选项数组
    timeRanges: {
      type: Array,
      default: () => ['近一周', '近一月', '近90天']
    }
  },
  data() {
    return {
      activeTimeRange: 'month',
      timeRangeOptions: [
        { title: '本年', type: 'year' },
        { title: '本月', type: 'month' },
        { title: '自定义', type: 'custom' }
      ],
      dateRange: [],
      startDate: '',
      endDate: '',
      totalDays: 0,
      tableColumns: [
        { title: '开始时间', props: 'checkStartTime' },
        { title: '任务名称', props: 'taskName' },
        { title: '检查级别', props: 'checkedLevelDesc' },
        { title: '执行频率', props: 'frequency', slot: true },
        { title: '结束时间', props: 'checkEndTime' }
      ],
      tableData: [],
      radarData: {
        indicators: [
          { name: '安全检查', max: 100 },
          { name: '设备检查', max: 100 },
          { name: '环境检查', max: 100 },
          { name: '流程检查', max: 100 },
          { name: '文档检查', max: 100 }
        ],
        data: []
      },
      lineChart: null,
      radarChart: null
    };
  },

  mounted() {
    this.setDefaultDates()
    this.$nextTick(() => {
      this.initCharts();

      this.renderCharts();
    });
  },

  methods: {
    setDefaultDates() {
      const today = new Date()
      const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)

      // 使用本地时间格式化，避免UTC时间转换问题
      this.startDate = this.formatLocalDate(firstDayOfMonth)
      this.endDate = this.formatLocalDate(today)
     
      // 初始化dateRange
      this.dateRange = [this.startDate, this.endDate]
      this.calculateDays()
    },

    // 格式化本地日期为YYYY-MM-DD格式
    formatLocalDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    calculateDays() {
      if (this.startDate && this.endDate) {
        const start = new Date(this.startDate)
        const end = new Date(this.endDate)
        const diffTime = Math.abs(end - start)
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
        this.totalDays = diffDays
      }
    },

    handleDateRangeChange(e) {
      if (e && Array.isArray(e) && e.length === 2) {
        this.startDate = e[0]
        this.endDate = e[1]
        this.calculateDays()
        // 自定义时间范围改变时重新请求数据
        this.renderCharts()
      }
    },

    // 处理时间范围变化
    handleTimeRangeChange(timeRange) {
     
      // 使用calculateTimeRange计算时间范围
      const timeRangeResult = calculateTimeRange(timeRange, this.dateRange)
      
      this.startDate = timeRangeResult.startDate
      this.endDate = timeRangeResult.endDate
      this.dateRange = [this.startDate, this.endDate]
      this.calculateDays()

      this.renderCharts();
    },



    // 初始化ECharts实例
    initCharts() {
      // 面积图初始化
      const lineChartDom = document.getElementById('lineChart');
      if (lineChartDom) {
        this.lineChart = echarts.init(lineChartDom);
      }

      // 雷达图初始化
      const radarChartDom = document.getElementById('radarChart');
      if (radarChartDom) {
        this.radarChart = echarts.init(radarChartDom);
      }
    },

    // 渲染面积图
    async renderLineChart(query) {
      if (!this.lineChart) return;
      
      // 清除图表之前的状态，确保不会残留缺省图
      this.lineChart.clear();
      
      let res = await getPlanOverview(query)
      let data = {}
      if (res && res.data) {
        res.data.forEach(item => {
          if (!data[item.typeDesc]) {
            data[item.typeDesc] = []
          }
          data[item.typeDesc].push({
            date: item.date,
            value: item.total
          })
        })
      }
      console.log(data, "data")
      let xAxisData = Object.values(data)[0]?.map(key => key.date) || []


      const option = {
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        legend: {
          data: Object.keys(data),
          textStyle: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value'
        },
        series: Object.keys(data).map(key => ({
          data: data[key].map(item => item.value),
          type: 'line',
          name: key
        })),
        grid: {
          left: '3%',
          right: '10%',
          bottom: '3%',

          containLabel: true
        }
      };

      this.lineChart.setOption(option);
    },

    // 设置空雷达图状态
    setEmptyRadarChart() {
      if (!this.radarChart) return;

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        radar: {
          indicator: []
        },
        series: []
      };

      this.radarChart.setOption(option);
    },

    // 渲染雷达图
    async renderRadarChart(query) {

      if (!this.radarChart) return;
      
      // 清除图表之前的状态，确保不会残留缺省图
      this.radarChart.clear();
      
      let response = await getDailyTaskMetrics(query)
      if (response.code !== 200 || !response.data) {
        console.error('获取雷达图数据失败:', response)
        // 设置空数据状态
        this.setEmptyRadarChart()
        return;
      }

      const { data } = response;
      console.log(data, "data")

      // 检查数据是否为空
      if (!data || data.length === 0) {
        console.warn('雷达图数据为空')
        this.setEmptyRadarChart()
        return;
      }

      // 计算最大值，用于设置雷达图指标范围
      const maxValue = data.length > 0 ? Math.max(...data.map(item => item.total || 0)) : 0;

      let indicator = data.map(item => ({
        name: `${item.name} ${item.total || 0}`,
        max: maxValue
      }))

      // 雷达图数据格式修正
      let seriesData = [{
        value: data.map(item => item.total || 0),
        name: '计划执行指标'
      }]


      const option = {
        radar: {
          indicator: indicator,
          radius: '65%',
          splitNumber: 5,
          axisName: {
            color: '#666',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(211, 211, 211, 0.5)'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: ['rgba(244, 244, 244, 0.1)', 'rgba(244, 244, 244, 0.2)']
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(211, 211, 211, 0.5)'
            }
          }
        },
        series: [{
          type: 'radar',
          data: seriesData,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(24, 144, 255, 0.6)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
            ])
          },
          lineStyle: {
            width: 2,
            color: '#1890ff'
          },
          // 移除雷达图每个角上的圆点
          symbol: 'none',
          // label: {
          //   show: true,
          //   formatter: '{c}'
          // }
        }]
      };


      this.radarChart.setOption(option);

    },

    //获取表格数据
    async getTaskDetailStats(query) {
      let res = await getTaskDetailStats(query)
      if (res && res.data) {
        this.tableData = res.data
      }
    },

    // 渲染所有图表
    renderCharts() {
      const query = calculateTimeRange(this.activeTimeRange, this.dateRange);

      this.renderLineChart(query);
      this.renderRadarChart(query);
      this.getTaskDetailStats(query)
    }
  }
};
</script>

<style lang="scss" scoped>
.inspection-stats-charts {
  padding: 26rpx;

  .stats-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    padding: 24rpx;
  }

  .time-filter {
    margin-bottom: 32rpx;

    .time-tabs {
      ::v-deep .h-tabs {
        justify-content: center;
        gap: 48rpx;

        .h-tabs-item {
          padding: 16rpx 32rpx;
          font-size: 28rpx;

          &.active {
            font-weight: bold;
          }
        }
      }
    }
  }

  .time-filter-section {
    margin-bottom: 20rpx;
    padding: 0 20rpx;
  }

  .filter-row {
    display: flex;
    align-items: center;
    flex-direction: row;

    .custom-time-section {
      position: relative;
      display: flex;
      align-items: center;
      gap: 24rpx;
      margin-top: 2rpx;
      width: 350rpx;

      .date-range-picker {

        // min-width: 200rpx;
        ::v-deep .icon-calendar {
          display: none !important;
        }

        ::v-deep .uni-date-range {
          font-size: 16rpx !important;
          background: transparent !important;
          color: black !important;


        }

        ::v-deep .uni-date-x {
          height: 25rpx !important;
          line-height: 25rpx !important;

          .range-separator {
            font-size: 20rpx !important;
            padding: 0 !important
          }

          .uni-date__x-input {
            height: 25rpx !important;
            line-height: 25rpx !important;
          }
        }

        ::v-deep .uni-date-x--border {
          border: none !important;
        }


      }

      .days-count {
        position: absolute;
        right: -85rpx;
         top:-8.5rpx;
        font-size: 25rpx;
        color: black;
        font-weight: 500;
        white-space: nowrap;
      }
    }
  }





  .chart-container {
    margin-bottom: 40rpx;

    .chart-title {
      display: block;
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      padding-left: 12rpx;

    }

    .chart-wrapper {
      height: 300rpx;

      display: flex;
      align-items: center;
      justify-content: center;


      .echarts-canvas {
        width: 100%;
        height: 100%;
      }

      .chart-placeholder {
        text-align: center;
        color: #999;

        .placeholder-text {
          display: block;
          margin-top: 16rpx;
          font-size: 24rpx;
        }
      }
    }
  }

  .table-container {
    .chart-title {
      display: block;
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      padding-left: 12rpx;

    }


  }
}
</style>