<template>
  <view class="problem-rectification">
    <!-- 时间筛选区域 -->
    <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>

    <DataCard v-if="!isBanZuZhangOrKeZhang" title="问题整改" :cardData="cardData" />


    <view class="chart-section">
      <!-- <view class="section-title">通道面貌-问题趋势</view> -->
      <view class="chart-container">
        <view class="stacked-bar-chart" id="stackedBarChart"></view>
      </view>
    </view>

  </view>
</template>

<script>
import StaticsTab from './StaticsTab.vue'
import DataCard from './DataCard.vue'
import { getRectificationStatusTotal, getRectificationStatusComparison } from '@/api/inspectionStatistics/inspectionStatistics.js'
import { calculateTimeRange } from '@/utils/formatUtils.js';
import * as echarts from 'echarts'
export default {
  name: 'ProblemRectification',
  components: {
    StaticsTab,
    DataCard

  },
  data() {
    return {
      activeTimeRange: 'month',
      timeRangeOptions: [
        { title: '本年', type: 'year' },
        { title: '本月', type: 'month' },
        { title: '自定义', type: 'custom' }
      ],
      dateRange: [],
      startDate: '',
      endDate: '',
      totalDays: 0,
      cardData: [],
      // 堆叠柱状图实例
      stackedBarChart: null
    }
  },
  computed: {
    isBanZuZhangOrKeZhang() {
      let roles = this.$store.state.user.roles;
      return roles && (roles.includes('banzuzhang') || roles.includes('kezhang'))
    },
  },
  mounted() {
    this.setDefaultDates()
    this.getProblemRectificationData()
    this.$nextTick(() => {
      this.initStackedBarChart()
    })
  },

  methods: {
    handleTimeRangeChange(timeRange) {
      const timeRangeResult = calculateTimeRange(timeRange, this.dateRange)
      this.startDate = timeRangeResult.startDate
      this.endDate = timeRangeResult.endDate
      this.dateRange = [this.startDate, this.endDate]
      this.calculateDays()
      this.getProblemRectificationData()
      this.initStackedBarChart()
    },
    getProblemRectificationData() {

      getRectificationStatusTotal(calculateTimeRange(this.activeTimeRange, this.dateRange))
        .then(res => {
          const { data } = res

          this.cardData = [
            {
              label: '按期已完成',
              value: data?.onTimeCompletedCount || '0',
              image: '/static/images/blue-box.png'
            },
            {
              label: '超期已完成',
              value: data?.overTimeCompletedCount || '0',
              image: '/static/images/pink-box.png'
            },
            {
              label: '按期整改中',
              value: data?.onTimeUnfinishedCount || '0',
              image: '/static/images/green-paper.png'
            },
            {
              label: '超期整改中',
              value: data?.overTimeUnfinishedCount || '0',
              image: '/static/images/yellow-paper.png'
            }
          ]
        })
    },
    setDefaultDates() {
      const today = new Date()
      const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)

      this.startDate = firstDayOfMonth.toISOString().split('T')[0]
      this.endDate = today.toISOString().split('T')[0]
      // 初始化dateRange
      this.dateRange = [this.startDate, this.endDate]
      this.calculateDays()
    },

    handleDateRangeChange(e) {
      if (e && Array.isArray(e) && e.length === 2) {
        this.startDate = e[0]
        this.endDate = e[1]
        this.calculateDays()
        this.getProblemRectificationData()
        this.initStackedBarChart()
      }
    },

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

    async initStackedBarChart() {
      const chartDom = document.getElementById('stackedBarChart')
      if (!chartDom) {
        console.error('堆叠柱状图容器未找到')
        return
      }

      try {
        // 如果图表实例已存在，先清除之前的状态
        if (this.stackedBarChart) {
          this.stackedBarChart.clear();
        }

        let query = calculateTimeRange(this.activeTimeRange, this.dateRange);
        let res = await getRectificationStatusComparison(query)
        const { data } = res;

        // 检查数据是否为空
        if (!data || data.length === 0) {
          this.setEmptyStackedBarChart()
          return
        }

        // 处理数据为堆积图格式
        let xAxisData = [];
        let seriesData = [];

        // 定义四种状态的数据字段映射和颜色配置
        const statusConfig = [
          { key: 'onTimeCompletedCount', name: '按期完成', color: '#5896FC' },
          { key: 'overTimeCompletedCount', name: '超期完成', color: '#FA7E7E' },
          { key: 'onTimeUnfinishedCount', name: '按期整改中', color: '#00AE41' },
          { key: 'overTimeUnfinishedCount', name: '超期整改中', color: '#FAC000' }
        ];

        // 提取部门名称作为x轴数据
        xAxisData = data.map(item => item.deptName);

        // 为每种状态创建系列数据
        statusConfig.forEach(status => {
          const seriesItem = {
            name: status.name,
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: status.color
            },
            emphasis: {
              focus: 'series'
            },
            data: data.map(item => item[status.key] || 0),
            label: {
              show: true,
              position: 'inside',
              formatter: function (params) {
                // 只显示非零值
                return params.value > 0 ? params.value : '';
              },
              color: '#fff',
              fontSize: 12,
              fontWeight: 'bold'
            }
          };
          seriesData.push(seriesItem);
        });

        console.log('堆积图数据:', { xAxisData, seriesData });

        this.stackedBarChart = echarts.init(chartDom)
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: statusConfig.map(item => item.name)
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
              interval: 0,
              rotate: 45 // 如果部门名称太长可以旋转显示
            }
          },
          yAxis: {
            type: 'value'
          },
          series: seriesData
        }

        this.stackedBarChart.setOption(option)
      } catch (error) {
        console.error('堆叠柱状图初始化失败:', error)
        this.setEmptyStackedBarChart()
      }
    },

    // 设置空堆叠柱状图状态
    setEmptyStackedBarChart() {
      const chartDom = document.getElementById('stackedBarChart')

      if (!chartDom) return

      // 如果图表实例不存在，先初始化
      if (!this.stackedBarChart) {
        this.stackedBarChart = echarts.init(chartDom)
      }

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        xAxis: {
          show: false
        },
        yAxis: {
          show: false
        },
        series: []
      }

      this.stackedBarChart.setOption(option)
    }
  },
  beforeDestroy() {
    {
      if (this.stackedBarChart) this.stackedBarChart.dispose()
    }
  }

}


</script>

<style lang="scss" scoped>
.problem-rectification {
  padding: 24rpx;

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

    .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: -85rpx;
          top: -8.5rpx;
          font-size: 25rpx;
          color: black;
          font-weight: 500;
          white-space: nowrap;


        }
      }
    }
  }

  .chart-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    .section-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }

    .chart-container {
      height: 1200rpx;

      .stacked-bar-chart {
        width: 100%;
        height: 100%;
      }
    }
  }

}
</style>