<template>
  <view class="problem-discovery">
    <!-- 时间筛选区域 -->
    <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="chart-section">
      <view class="section-title">总体问题分布</view>
      <view class="chart-container">
        <view class="pie-chart" id="pieChart"></view>
      </view>
    </view>



    <view v-if="isZhanZhang">
      <!-- 问题分布对比 -->
      <view class="chart-section">
        <view class="section-title">问题分布对比</view>
        <view class="radarChart-container">
          <view class="radar-chart" id="radarChart"></view>
        </view>
      </view>
      <view v-for="(item, index) in pieChartData" :key="index">
        <!-- 问题对比 -->
        <view class="chart-section" v-if="item.problemCompareData && item.problemCompareData.length > 0">
          <view class="section-title">{{ item.name }}-问题对比</view>
          <view class="table-container">
            <statistic-table :columns="problemCompareColumns" :data="item.problemCompareData" />
          </view>
          <view class="section-title" style="margin-top: 20rpx;">{{ item.name }}-问题趋势</view>
          <view class="chart-container">
            <view class="line-chart" :id="'lineChart' + index"></view>
          </view>
        </view>

        <!-- 问题趋势 -->
        <!-- <view class="chart-section">
         
        </view> -->
      </view>
    </view>


    <view v-else>
      <view v-for="(item, index) in pieChartData" :key="index">
        <!-- 问题对比 -->
        <view class="chart-section">
          <view class="section-title">{{ item.name }}-问题明细</view>
          <view class="chart-container">
            <view class="pie-chart" :id="'pieChart' + index"></view>
          </view>
          <view class="section-title" style="margin-top: 20rpx;">{{ item.name }}-问题趋势</view>
          <view class="chart-container">
            <view class="line-chart" :id="'lineChart' + index"></view>
          </view>
        </view>

        <!-- 问题趋势 -->
        <!-- <view class="chart-section">
       
        </view> -->
      </view>
    </view>
  </view>
</template>

<script>
import StaticsTab from './StaticsTab.vue'
import { calculateTimeRange } from '@/utils/formatUtils.js';
import * as echarts from 'echarts'
import {
  getProblemDistribution,
  getProblemDistributionComparison,
  getChannelProblemComparison,
  getChannelProblemTrend
} from '@/api/inspectionStatistics/inspectionStatistics'

export default {
  name: 'ProblemDiscovery',
  components: {
    StaticsTab,

  },
  data() {
    return {
      activeTimeRange: 'month',
      timeRangeOptions: [
        { title: '本年', type: 'year' },
        { title: '本月', type: 'month' },
        { title: '自定义', type: 'custom' }
      ],
      dateRange: [],
      startDate: '',
      endDate: '',
      totalDays: 0,

      // 表格配置
      problemCompareColumns: [
        { title: '分类', props: 'category' },
      ],
      problemCompareData: [],
      pieChartData: [],//保存总体问题数据，方便遍历
      // 图表实例
      pieChart: null,
      radarChart: null,
      lineChart: null
    }
  },
  computed: {
    // 站长
    isZhanZhang() {
      let roles = this.$store.state.user.roles;
      console.log('用户角色:', roles)
      return roles && roles.includes('test')
    },
  },
  mounted() {
    this.setDefaultDates()
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  methods: {
    // 加载通道面貌问题对比数据
    async loadChannelProblemComparison(categoryCodeOne) {
      try {
        console.log('开始请求getChannelProblemComparison接口...')
        const response = await getChannelProblemComparison({
          startDate: this.startDate,
          endDate: this.endDate,
          categoryCodeOne: categoryCodeOne
        })


        if (response && response.code === 200) {
          // console.log('通道面貌问题对比数据详情:', response.data)
          //分类的值
          let nameArr = []
          let res = []
          response.data.forEach(item => {
            if (!this.problemCompareColumns.find(col => col.props === item.deptId)) {
              //设置列
              this.problemCompareColumns.push({
                title: item.deptName,//旅检一科
                props: item.deptId,//220
              })
            }
            if (!nameArr.find(ele => ele.code === item.code) && item.total > 0) {
              nameArr.push({
                code: item.code,//00000145
                name: item.name,//语言规范
              })
            }
          })
          nameArr.forEach(element => {
            let categoryArr = response.data.filter(item => item.code == element.code)
            let obj = {
              category: element.name,
            }

            // 为每个部门添加问题数量
            categoryArr.forEach(item => {
              obj[item.deptId] = item.total
            })

            res.push(obj)
          })

          // console.log('处理后的数据:', res, '列配置:', this.problemCompareColumns)
          return res;
          // this.problemCompareData = res
        }
      } catch (error) {
        console.error('请求getChannelProblemComparison接口失败:', error)
        // 降级方案：使用默认数据

      }
    },

    // 加载通道面貌问题趋势数据
    loadChannelProblemTrend(arr) {
      // 确保arr是有效的数组
      if (!arr || !Array.isArray(arr) || arr.length === 0) {
        return {
          legend: [],
          date: [],
          series: []
        }
      }

      let res = {}
      let legend = []
      let date = []
      
      // 先收集所有日期，确保日期顺序一致
      arr.forEach(item => {
        if (item.date && !date.includes(item.date)) {
          date.push(item.date)
        }
      })
      
      // 按日期排序
      date.sort((a, b) => new Date(a) - new Date(b))
      
      // 按名称分组数据，确保每个名称的数据长度与日期数组一致
      arr.forEach(item => {
        if (item.name && item.date) {
          if (!legend.includes(item.name)) {
            legend.push(item.name)
            res[item.name] = new Array(date.length).fill(0) // 初始化数组，填充0
          }
          
          const dateIndex = date.indexOf(item.date)
          if (dateIndex !== -1) {
            res[item.name][dateIndex] = item.total || 0
          }
        }
      })
      console.log('处理后的数据:', res, '日期:', date, '名称:', legend)
      // 生成series数据，确保与legend顺序一致
      let series = legend.map(name => ({
        name: name,
        type: 'line',
    
        data: res[name] || []
      }))

      return {
        legend: legend,
        date: date,
        series: series
      }
    },
    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}`;
    },


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

    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.refreshChartData()
    },

    // 刷新图表数据
    async refreshChartData() {
      console.log('刷新图表数据，时间范围:', this.startDate, '至', this.endDate)
      try {

        // 重新渲染图表
        this.refreshCharts()
      } catch (error) {
        console.error('刷新图表数据失败:', error)
      }
    },

    // 刷新图表
    refreshCharts() {
      if (this.pieChart) {
        this.pieChart.dispose()
        this.pieChart = null
      }
      if (this.radarChart) {
        this.radarChart.dispose()
        this.radarChart = null
      }
      if (this.lineChart) {
        this.lineChart.dispose()
        this.lineChart = null
      }

      // 销毁所有遍历的折线图和环形图
      if (this.pieChartData && this.pieChartData.length > 0) {
        this.pieChartData.forEach(item => {
          if (item.trendChart) {
            item.trendChart.dispose()
            item.trendChart = null
          }
          if (item.pieChartDetail) {
            item.pieChartDetail.dispose()
            item.pieChartDetail = null
          }
        })
      }

      this.$nextTick(() => {
        this.initPieChart()
        this.initRadarChart()
        this.initLineChart()
      })
    },

    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 initCharts() {
      try {
        // 初始化饼图
        this.initPieChart()
        // 初始化雷达图
        this.initRadarChart()
        // 初始化问题趋势折线图
        this.initLineChart()
      } catch (error) {
        console.error('图表数据加载失败:', error)
      }
    },
    //处理列表数据
    handleProblemDto(arr) {
      let nameArr = []
      let res = []
      arr.forEach(item => {
        if (!this.problemCompareColumns.find(col => col.props === item.deptId)) {
          //设置列
          this.problemCompareColumns.push({
            title: item.deptName,//旅检一科
            props: item.deptId,//220
          })
        }
        if (!nameArr.find(ele => ele.code === item.code) && item.total > 0) {
          nameArr.push({
            code: item.code,//00000145
            name: item.name,//语言规范
          })
        }
      })
      nameArr.forEach(element => {
        let categoryArr = arr.filter(item => item.code == element.code)
        let obj = {
          category: element.name,
        }

        // 为每个部门添加问题数量
        categoryArr.forEach(item => {
          obj[item.deptId] = item.total
        })

        res.push(obj)
      })
      return res;
    },
    //获取站长遍历的图表和列表
    async getZhanZhangChartAndList() {
      for (let i = 0; i < this.pieChartData.length; i++) {
        //分类
       
        //获取问题对比数据
        let problemCompareData = this.handleProblemDto(this.pieChartData[i].checkLargeScreenProblemDtoList)
        console.log(problemCompareData, "problemCompareData")
        
        this.$set(this.pieChartData[i], 'problemCompareData', problemCompareData || [])

        //获取问题趋势数据
        let problemTrendData = this.loadChannelProblemTrend(this.pieChartData[i].checkLargeScreenProblemTrendDtoList)
        console.log(problemTrendData, "problemTrendData")
        this.$set(this.pieChartData[i], 'problemTrendData', problemTrendData || [])

        // 初始化对应的折线图
        if (problemTrendData) {
          this.$nextTick(() => {
            // 使用setTimeout确保DOM已经完全渲染
            setTimeout(() => {
              this.initTrendChart(i, problemTrendData)
            }, 100)
          })
        }
      }
    },
    // 处理问题明细数据，用于环形图展示
    handleProblemDetailDto(arr) {
      if (!arr || !Array.isArray(arr)) {
        console.warn('handleProblemDetailDto: 传入的数据不是数组或为空')
        return []
      }
       
      // 按问题类型分组统计
      const problemTypeMap = {}
      arr.forEach(item => {
        if (item.name && item.total > 0) {
          if (!problemTypeMap[item.name]) {
            problemTypeMap[item.name] = 0
          }
          problemTypeMap[item.name] += item.total
        }
      })

      // 转换为环形图数据格式
      const pieData = Object.keys(problemTypeMap).map(name => ({
        name: name,
        value: problemTypeMap[name]
      }))

      console.log('环形图数据:', pieData)
      return pieData
    },
    getOtherPieAndLine() {
      for (let i = 0; i < this.pieChartData.length; i++) {
        //分类

        //获取问题明细数据（环形图数据）
        let problemDetailData = this.handleProblemDetailDto(this.pieChartData[i].checkLargeScreenProblemDtoList)
        console.log(problemDetailData, "problemDetailData")
        
        this.$set(this.pieChartData[i], 'problemDetailData', problemDetailData || [])

        //获取问题趋势数据
        let problemTrendData = this.loadChannelProblemTrend(this.pieChartData[i].checkLargeScreenProblemTrendDtoList)
        console.log(problemTrendData, "problemTrendData")
        this.$set(this.pieChartData[i], 'problemTrendData', problemTrendData || [])

        // 初始化对应的环形图
        if (problemDetailData && problemDetailData.length > 0) {
          this.$nextTick(() => {
            // 使用setTimeout确保DOM已经完全渲染
            setTimeout(() => {
              this.initPieChartDetail(i, problemDetailData)
            }, 100)
          })
        }

        // 初始化对应的折线图
        if (problemTrendData) {
          this.$nextTick(() => {
            // 使用setTimeout确保DOM已经完全渲染
            setTimeout(() => {
              this.initTrendChart(i, problemTrendData)
            }, 100)
          })
        }
      }
    },
    // 初始化遍历的环形图
    initPieChartDetail(index, pieData) {
      const chartDom = document.getElementById('pieChart' + index)
      if (!chartDom) {
        console.error('环形图容器未找到:', 'pieChart' + index)
        return
      }

      try {
        const chart = echarts.init(chartDom)
        const option = {

          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          // legend: {
          //   orient: 'vertical',
          //   left: 'left',
          //   top: 'middle',
          //   textStyle: {
          //     color: '#666'
          //   }
          // },
          series: [
            {
              name: '问题明细',
              type: 'pie',
              radius: ['30%', '50%'], // 环形图设置
              center: ['50%', '50%'],
              data: pieData,
              label: {
                show: true,
                formatter: '{b} {c}'
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }

        chart.setOption(option)

        // 保存图表实例到对应的数据项中
        this.$set(this.pieChartData[index], 'pieChartDetail', chart)
        console.log('环形图初始化成功:', 'pieChart' + index)
      } catch (error) {
        console.error('环形图初始化失败:', error)
      }
    },

    // 初始化遍历的折线图
    initTrendChart(index, trendData) {
      const chartDom = document.getElementById('lineChart' + index)
      if (!chartDom) {
        console.error('折线图容器未找到:', 'lineChart' + index)
        return
      }

      try {
        const chart = echarts.init(chartDom)
        const option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: trendData.legend
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: trendData.date
          },
          yAxis: {
            type: 'value'
          },
          series: trendData.series
        }

        chart.setOption(option)

        // 保存图表实例到对应的数据项中
        this.$set(this.pieChartData[index], 'trendChart', chart)
      } catch (error) {
        console.error('折线图初始化失败:', error)
      }
    },

    async initPieChart() {
      // 使用document.getElementById获取DOM元素，确保在uni-app中正确获取
      const chartDom = document.getElementById('pieChart')
      if (!chartDom) {
        console.error('饼图容器未找到')
        return
      }

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

      const response = await getProblemDistribution(calculateTimeRange(this.activeTimeRange, this.dateRange))



      if (response && response.code === 200) {
        this.pieChartData = response.data;
        //获取站长遍历的图表和列表
        if (this.isZhanZhang) {
          await this.getZhanZhangChartAndList()
        } else {
          await this.getOtherPieAndLine()
        }

        try {
          this.pieChart = echarts.init(chartDom)
          const option = {
            title: {
              text: '总体问题分布',
              left: 'center',
              textStyle: {
                color: '#fff'
              }
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              show: false
            },
            // grid: {
            //   left: '10%',
            //   right: '10%',
            //   top: '15%',
            //   bottom: '10%',
            //   containLabel: true
            // },
            series: [
              {
                name: '问题分布',
                type: 'pie',
                radius: '50%',
                // center: ['35%', '50%'],
                data: response.data.map(item => ({
                  name: item.name,
                  value: item.total
                })),
                label: {
                  show: true,
                  formatter: function (params) {
                    return params.name + '\n' + params.percent + '%'
                  }
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }

          this.pieChart.setOption(option)
        } catch (error) {
          console.error('饼图初始化失败:', error)
        }
      }



    },

    async initRadarChart() {
      // 检查雷达图容器是否存在（根据用户角色条件显示）
      if (!this.isZhanZhang) {
        console.log('当前用户角色不显示雷达图')
        return
      }

      const chartDom = document.getElementById('radarChart')
      if (!chartDom) {
        console.error('雷达图容器未找到')
        return
      }

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

      const response = await getProblemDistributionComparison({
        startDate: this.startDate,
        endDate: this.endDate
      })
      if (response && response.code === 200) {
        console.log('通道面貌问题对比数据详情:', response.data)
        let indicator = [];
        let indicatorName = [];
        let legend = [];
        let data = [];
        let deptIds = [];
        response.data.forEach(item => {
          if (indicator.filter(ele => ele == item.code).length == 0) {
            indicator.push(item.code)
          }
          if (indicatorName.filter(ele => ele == item.name).length == 0) {
            if (!indicatorName.includes(item.name)) {
              indicatorName.push(item.name)
            }
          }
          if (legend.filter(ele => ele == item.deptName).length == 0) {
            legend.push(item.deptName)
          }
          if (deptIds.filter(ele => ele == item.deptId).length == 0) {
            deptIds.push(item.deptId)
          }

        })
        // console.log(indicatorName, deptIds, 111111111111, response.data)
        // 定义不同部门的颜色数组
        const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']

        data = deptIds.map((item, index) => {
          const getAll = response.data.filter(ele => ele.deptId == item)
          // console.log(getAll, "getAll")
          return {
            name: getAll[0].deptName,
            value: indicator.map(code => getAll.find(ele => ele.code == code).total),
            // 为每个数据系列设置不同的颜色
            areaStyle: {
              color: colorList[index % colorList.length],
              opacity: 0.3
            },
            lineStyle: {
              color: colorList[index % colorList.length],
              width: 2
            },
            itemStyle: {
              color: colorList[index % colorList.length],
              borderWidth: 2
            }
          }
        })

        // console.log(indicatorName, "data", data, indicatorName)
        try {
          this.radarChart = echarts.init(chartDom)
          const option = {
            tooltip: {},
            grid: {
              top: '0',
              bottom: '25%',
              left: '10%',
              right: '10%'
            },
            legend: {
              data: legend,
              bottom: 0,
              // textStyle: {
              //   color: '#666'
              // }
            },
            radar: {
              indicator: indicatorName.map(item => ({ name: item })),
              radius: '50%',
              center: ['50%', '40%'],
            },
            series: [
              {
                type: 'radar',
                data: data,
                symbol: 'none',
              }
            ]
          }

          this.radarChart.setOption(option)
        } catch (error) {
          console.error('雷达图初始化失败:', error)
        }
      }


    },

    async initLineChart() {
      if (!this.isZhanZhang) {
        console.log('当前用户角色不显示雷达图')
        return
      }
      const chartDom = document.getElementById('lineChart')
      if (!chartDom) {
        console.error('折线图容器未找到')
        return
      }

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

      const response = await getChannelProblemTrend({
        startDate: this.startDate,
        endDate: this.endDate
      })


      if (response && response.code === 200) {
        console.log('通道面貌问题趋势数据详情:', response.data)
        let res = {}
        let legend = []
        let date = []
        response.data.forEach(item => {
          if (!date.includes(item.date)) {
            date.push(item.date)
          }
          if (!legend.includes(item.name)) {
            legend.push(item.name)
          }
          if (!res[item.name]) {
            res[item.name] = []
          }
          res[item.name].push(item.total)
        })
        let data = Object.keys(res).map(key => ({
          name: key,
          type: 'line',

          data: res[key]
        }))
        // console.log(legend, date, res)

        try {
          this.lineChart = echarts.init(chartDom)
          const option = {
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: legend
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: date
            },
            yAxis: {
              type: 'value'
            },
            series: data
          }

          this.lineChart.setOption(option)
        } catch (error) {
          console.error('折线图初始化失败:', error)
        }
      }

    },
    resizeCharts() {
      if (this.pieChart) this.pieChart.resize()
      if (this.radarChart) this.radarChart.resize()
      if (this.lineChart) this.lineChart.resize()
    },
    beforeDestroy() {
      if (this.pieChart) this.pieChart.dispose()
      if (this.radarChart) this.radarChart.dispose()
      if (this.lineChart) this.lineChart.dispose()
    }
  }
}
</script>

<style lang="scss" scoped>
.problem-discovery {
  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 {

          // 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-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;
    }

    .radarChart-container {
      height: 550rpx;

      .radar-chart {
        height: 550rpx;
      }
    }

    .chart-container {
      height: 400rpx;

      .pie-chart,
      .line-chart {
        width: 100%;
        height: 100%;
      }


    }

    .table-container {
      margin-top: 16rpx;
    }
  }
}
</style>