<template>
  <div class="completion-trend">
    <!-- 时间筛选器 -->
    <view class="time-filter-section">
      <view class="filter-row">
        <StaticsTab v-model="activeTimeRange" :tabs="timeRangeOptions" active-color="#2B7BFF"
          @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>

    <!-- 图表标题 -->
    <h3 class="chart-title">抽问抽答完成趋势图</h3>

    <!-- 图表容器 -->
    <div class="chart-container">
      <div ref="trendChart" class="chart" style="width: 100%; height: 400rpx;"></div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <text>加载中...</text>
    </div>

    <!-- 无数据提示 -->
    <div v-if="!loading && chartData.length === 0" class="no-data">
      <text>暂无趋势数据</text>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import StaticsTab from "@/pages/inspectionStatistics/components/StaticsTab.vue";
import { getCompletionTrend } from '@/api/questionStatistics/questionStatistics';
import { calculateTimeRange } from '@/utils/formatUtils.js';

export default {
  name: 'CompletionTrend',
  components: {
    StaticsTab
  },
  data() {
    return {
      loading: false,
      activeTimeRange: 'month', // year, month, custom
      customStartTime: '',
      customEndTime: '',
      dateRange: [],
      totalDays: 0,
      chartData: [],
      xAxisData: [],
      trendChart: null,
      timeRangeOptions: [
        { title: '本年', type: 'year' },
        { title: '本月', type: 'month' },
        { title: '自定义', type: 'custom' }
      ]
    };
  },
  mounted() {
    this.setDefaultDates();
    this.initChart();
    this.loadData();
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose();
    }
  },
  methods: {
    // 设置默认日期
    setDefaultDates() {
      const today = new Date();
      // 本月第一天
      const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

      // 使用本地时间格式化，避免UTC时间转换问题
      this.customStartTime = this.formatLocalDate(firstDayOfMonth);
      this.customEndTime = this.formatLocalDate(today);
      // 初始化dateRange
      this.dateRange = [this.customStartTime, this.customEndTime];
      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}`;
    },
    
    initChart() {
      const chartDom = this.$refs.trendChart;
      if (chartDom) {
        this.trendChart = echarts.init(chartDom);
        this.setChartOption();
      }
    },
    setChartOption() {
      if (!this.trendChart) return;
      console.log('setChartOption', this.chartData, this.xAxisData);
      const option = {
        // title: {
        //   text: '抽问抽答完成趋势',
        //   left: 'center',
        //   textStyle: {
        //     fontSize: 16,
        //     fontWeight: 'normal'
        //   }
        // },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}<br/>`;
            });
            return result;
          }
        },
        legend: {
          show: true,
          // bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xAxisData
        },
        yAxis: {
          type: 'value',
          min: 0,
          // max: 100,
          // axisLabel: {
          //   formatter: '{value}'
          // }
        },
        series: this.chartData
      };

      this.trendChart.setOption(option);
    },
    handleTimeRangeChange(range) {
      console.log('时间范围选择:', range, this.dateRange);
      
      // 使用calculateTimeRange计算时间范围
      const timeRangeResult = calculateTimeRange(range, this.dateRange);
      this.customStartTime = timeRangeResult.startDate;
      this.customEndTime = timeRangeResult.endDate;
      this.dateRange = [this.customStartTime, this.customEndTime];
      
      this.activeTimeRange = range;
      this.calculateDays();
      this.loadData();
    },
    handleDateRangeChange(e) {
      if (e && e.length === 2) {
        this.dateRange = e;
        this.customStartTime = e[0];
        this.customEndTime = e[1];
        this.calculateDays();
        this.loadData();
      }
    },
    
    // 计算天数
    calculateDays() {
      if (this.customStartTime && this.customEndTime) {
        const start = new Date(this.customStartTime);
        const end = new Date(this.customEndTime);
        const diffTime = Math.abs(end - start);
        this.totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
      }
    },
    
    async loadData() {
      this.loading = true;

      try {
        // 构建请求参数
        const params = {
          timeType: this.activeTimeRange
        };

        // 如果是自定义时间范围，添加开始和结束日期
        if (this.activeTimeRange === 'custom') {
          if (!this.customStartTime || !this.customEndTime) {
            uni.showToast({
              title: '请选择完整的时间范围',
              icon: 'none'
            });
            this.loading = false;
            return;
          }
          params.startDate = this.customStartTime;
          params.endDate = this.customEndTime;
        }

        // 调用API接口
        const response = await getCompletionTrend(params);

        // 检查权限控制
        if (response.show === false) {
          uni.showToast({
            title: '当前角色无权限查看此数据',
            icon: 'none'
          });
          this.chartData = [];
          this.setChartOption();
          return;
        }

        // 处理API返回的数据
        const { processedData, xAxisData } = this.processApiData(response);
        this.chartData = processedData;
        this.xAxisData = xAxisData;
        this.setChartOption();

      } catch (error) {
        console.error('加载数据失败:', error);
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 处理API返回的数据格式
    processApiData(apiData) {
      console.log('processApiData', apiData);

      // 根据API返回的数据结构进行处理
      if (!apiData || !apiData.model) {
        return { processedData: [], xAxisData: [] };
      }

      const { xAxis, series } = apiData.model;

      // 处理x轴数据
      const xAxisData = xAxis || [];

      // 处理系列数据
      const processedData = [];

      if (series && series.length > 0) {
        // 如果是站长角色，显示多条线；如果是科长角色，显示单条线
        // 这里简化处理，只显示第一条线
        for (let i = 0; i < series.length; i++) {
          processedData.push({
            name: series[i].name,
            type: 'line',
            data: series[i].data
          });
        }

      }

      return { processedData, xAxisData };
    },


  },
  watch: {
    chartData: {
      handler() {
        this.$nextTick(() => {
          this.setChartOption();
        });
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.completion-trend {
  padding: 10rpx 0;

  .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 {
          ::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: -86rpx;
          top: -8rpx;
          font-size: 25rpx;
          color: black;
          font-weight: 500;
          white-space: nowrap;
        }
      }
  }

  .chart-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    text-align: center;
  }

  .chart-container {
    background: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .loading-container,
  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200rpx;
    font-size: 28rpx;
    color: #999;
  }
}
</style>