<template>
  <div class="app-container">
    <!-- 搜索筛选区域 -->
    <el-card class="filter-card mb16">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="handleTimeRangeChange"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="预设时段" prop="quickTime">
          <el-select v-model="queryParams.quickTime" placeholder="快速选择" clearable @change="handleQuickTimeChange" style="width: 120px">
            <el-option label="今日" value="today" />
            <el-option label="近7天" value="7days" />
            <el-option label="近30天" value="30days" />
            <el-option label="本年度" value="year" />
          </el-select>
        </el-form-item>

        <el-form-item label="处理部门" prop="departmentId">
          <el-select
            v-model="queryParams.departmentId"
            placeholder="请选择部门"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="dept in departmentList"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="政策标题" prop="policyTitle" v-if="queryParams.policyFilter === 'title'">
          <el-input
            v-model="queryParams.policyTitle"
            placeholder="请输入政策标题关键词"
            clearable
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="政策文号" prop="policyCode" v-if="queryParams.policyFilter === 'code'">
          <el-input
            v-model="queryParams.policyCode"
            placeholder="请输入政策文号"
            clearable
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="沟通类型" prop="submitType">
          <el-select v-model="queryParams.submitType" placeholder="请选择类型" clearable style="width: 120px">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_SUBMIT_TYPE)"
                       :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">分析</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- KPI 指标卡片 -->
    <el-row :gutter="20" class="kpi-row mb20">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="kpi-card" shadow="hover">
          <div class="kpi-content">
            <div class="kpi-icon" style="background-color: #409EFF;">
              <i class="el-icon-chat-line-round"></i>
            </div>
            <div class="kpi-info">
              <div class="kpi-label">累计沟通总数</div>
              <div class="kpi-value">{{ kpiData.totalCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="kpi-card" shadow="hover">
          <div class="kpi-content">
            <div class="kpi-icon" style="background-color: #67C23A;">
              <i class="el-icon-circle-plus"></i>
            </div>
            <div class="kpi-info">
              <div class="kpi-label">今日新增</div>
              <div class="kpi-value">{{ kpiData.todayCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="kpi-card" shadow="hover">
          <div class="kpi-content">
            <div class="kpi-icon" style="background-color: #E6A23C;">
              <i class="el-icon-time"></i>
            </div>
            <div class="kpi-info">
              <div class="kpi-label">平均处理时长</div>
              <div class="kpi-value">{{ formatProcessTime(kpiData.avgProcessTime) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="kpi-card" shadow="hover">
          <div class="kpi-content">
            <div class="kpi-icon" style="background-color: #F56C6C;">
              <i class="el-icon-s-claim"></i>
            </div>
            <div class="kpi-info">
              <div class="kpi-label">总回复率</div>
              <div class="kpi-value">{{ formatRate(kpiData.replyRate) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 民意热度分析 -->
    <el-row :gutter="20" class="mb20">
      <!-- 政策沟通交流排行 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>政策沟通交流排行 Top 10</span>
            <div class="card-header-actions">
              <el-radio-group v-model="rankOrder" size="mini" @change="getPolicyRank">
                <el-radio-button label="desc">正序</el-radio-button>
                <el-radio-button label="asc">倒序</el-radio-button>
              </el-radio-group>
              <el-button size="mini" icon="el-icon-download" @click="exportChart('policyRankChart')">导出</el-button>
            </div>
          </div>
          <div ref="policyRankChart" style="height: 400px"></div>
        </el-card>
      </el-col>

      <!-- 政策沟通交流趋势分析 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>政策沟通交流趋势分析</span>
            <div class="card-header-actions">
              <el-radio-group v-model="trendGranularity" size="mini" @change="getTrendAnalysis">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
              <el-button size="mini" icon="el-icon-download" @click="exportChart('trendChart')">导出</el-button>
            </div>
          </div>
          <div ref="trendChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 部门处理效能分析（根据角色条件显示） -->
    <el-row :gutter="20" class="mb20" v-if="showDepartmentAnalysis">
      <!-- 工作量分布 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>部门工作量分布</span>
            <el-button size="mini" icon="el-icon-download" @click="exportChart('workloadChart')">导出</el-button>
          </div>
          <div ref="workloadChart" style="height: 400px;"></div>
        </el-card>
      </el-col>

      <!-- 处理效率（带滚动条） -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card scrollable-chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>部门处理效率（平均天数）</span>
            <div class="card-header-actions">
              <el-tooltip content="设置显示部门数量" placement="top">
                <el-select v-model="displayDepartmentCount" size="mini" style="width: 80px; margin-right: 10px;" @change="updateDepartmentCharts">
                  <el-option label="10" value="10" />
                  <el-option label="20" value="20" />
                  <el-option label="50" value="50" />
                  <el-option label="100" value="100" />
                  <el-option label="全部" value="all" />
                </el-select>
              </el-tooltip>
              <el-button size="mini" icon="el-icon-download" @click="exportChart('efficiencyChart')">导出</el-button>
            </div>
          </div>
          <div class="scrollable-chart-container" ref="efficiencyChartContainer">
            <div ref="efficiencyChart" class="scrollable-chart" :style="{ height: efficiencyChartHeight + 'px' }"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 部门回复率（根据角色条件显示） -->
    <el-row :gutter="20" class="mb20" v-if="showDepartmentAnalysis">
      <el-col :xs="24" :lg="24">
        <el-card class="chart-card scrollable-chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>部门回复率</span>
            <div class="card-header-actions">
              <el-tooltip content="设置显示部门数量" placement="top">
                <el-select v-model="displayDepartmentCount" size="mini" style="width: 80px; margin-right: 10px;" @change="updateDepartmentCharts">
                  <el-option label="10" value="10" />
                  <el-option label="20" value="20" />
                  <el-option label="50" value="50" />
                  <el-option label="100" value="100" />
                  <el-option label="全部" value="all" />
                </el-select>
              </el-tooltip>
              <el-button size="mini" icon="el-icon-download" @click="exportChart('replyRateChart')">导出</el-button>
            </div>
          </div>
          <div class="scrollable-chart-container" ref="replyRateChartContainer">
            <div ref="replyRateChart" class="scrollable-chart" :style="{ height: replyRateChartHeight + 'px' }"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 政策沟通交流内容分析 -->
    <el-row :gutter="20" class="mb20">
      <!-- 沟通类型分布 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>沟通类型分布</span>
            <el-button size="mini" icon="el-icon-download" @click="exportChart('typeChart')">导出</el-button>
          </div>
          <div ref="typeChart" style="height: 400px;"></div>
        </el-card>
      </el-col>

      <!-- 高频词云 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>高频词云分析</span>
            <el-button size="mini" icon="el-icon-download" @click="exportChart('wordCloudChart')">导出</el-button>
          </div>
          <div ref="wordCloudChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as PolicyCommunicationsApi from '@/api/server/policycommunications';
import * as echarts from 'echarts';
import 'echarts-wordcloud';

export default {
  name: "PolicyCommunicationsAnalysis",
  data() {
    return {
      // 查询参数
      queryParams: {
        dateRange: [],
        quickTime: '',
        //departmentIds: [],
        departmentId:  undefined,
        policyFilter: '',
        policyTitle: '',
        policyCode: '',
        submitType: ''
      },

      // 快速选择配置
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },

      // 部门列表
      departmentList: [],

      // KPI数据
      kpiData: {
        totalCount: 0,
        todayCount: 0,
        avgProcessTime: 0,
        replyRate: 0,
        pendingCount: 0,
        repliedCount: 0,
        publishedCount: 0
      },

      // 图表相关
      rankOrder: 'desc',
      trendGranularity: 'day',

      // 超时列表和统计
      overtimeList: [],
      overtimeSummary: {
        totalOverdueCount: 0,
        avgOverdueDays: 0,
        maxOverdueDays: 0
      },
      overtimeLoading: false,

      // ECharts实例
      charts: {},

      // 加载状态
      loading: false,

      // 新增：用户角色
      userRoles: [],

      // 新增：部门数据
      departmentRawData: [],

      // 新增：显示部门数量控制
      displayDepartmentCount: '20',

      // 新增：图表高度计算
      efficiencyChartHeight: 400,
      replyRateChartHeight: 400,

      // 图表容器引用
      efficiencyChartContainer: null,
      replyRateChartContainer: null
    };
  },
  computed: {
    /** 判断是否显示部门分析相关图表 */
    showDepartmentAnalysis() {
      return !this.userRoles.includes('trs_policy_user');
    },

    /** 计算当前要显示的部门数据 */
    displayDepartmentData() {
      if (!this.departmentRawData || this.departmentRawData.length === 0) {
        return [];
      }

      let data = [...this.departmentRawData];

      // 根据选择的数量筛选数据
      if (this.displayDepartmentCount !== 'all') {
        const count = parseInt(this.displayDepartmentCount);
        data = data.slice(0, count);
      }

      return data;
    }
  },
  created() {
    this.initData();
    this.loadAnalysisData();
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.handleResize);

    // 初始化滚动容器引用
    this.$nextTick(() => {
      this.efficiencyChartContainer = this.$refs.efficiencyChartContainer;
      this.replyRateChartContainer = this.$refs.replyRateChartContainer;
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    Object.values(this.charts).forEach(chart => {
      if (chart) chart.dispose();
    });
  },
  methods: {
    /** 初始化数据 */
    async initData() {
      try {
        const deptRes = await PolicyCommunicationsApi.getDepartmentList();
        this.departmentList = deptRes.data.departmentList || [];
        console.log('部门列表:', this.departmentList);
        await this.loadUserRoles();
      } catch (error) {
        console.error('初始化数据失败:', error);
        this.$message.error('初始化数据失败');
      }
    },

    /** 加载用户角色 */
    async loadUserRoles() {
      try {
        if (this.$store && this.$store.getters) {
          const userInfo = this.$store.getters.user || {};
          this.userRoles = userInfo.roles || [];

          if (this.$store.getters.roles) {
            this.userRoles = this.$store.getters.roles;
          }
        }

        if (!this.userRoles || this.userRoles.length === 0) {
          const userInfo = await this.getUserInfo();
          this.userRoles = userInfo.roles || [];
        }

        console.log('当前用户角色:', this.userRoles);
      } catch (error) {
        console.error('获取用户角色失败:', error);
        this.userRoles = [];
      }
    },

    /** 获取用户信息（备用方法） */
    async getUserInfo() {
      try {
        return {};
      } catch (error) {
        return {};
      }
    },

    /** 初始化图表 */
    initCharts() {
      const baseCharts = [
        'policyRankChart',
        'trendChart',
        'workloadChart',
        'typeChart',
        'wordCloudChart'
      ];

      baseCharts.forEach(ref => {
        const dom = this.$refs[ref];
        if (dom) {
          this.charts[ref] = echarts.init(dom);
        }
      });

      // 初始化部门分析图表
      if (this.showDepartmentAnalysis) {
        const efficiencyChartDom = this.$refs.efficiencyChart;
        const replyRateChartDom = this.$refs.replyRateChart;

        if (efficiencyChartDom) {
          this.charts.efficiencyChart = echarts.init(efficiencyChartDom);
        }
        if (replyRateChartDom) {
          this.charts.replyRateChart = echarts.init(replyRateChartDom);
        }
      }
    },

    /** 加载分析数据 */
    async loadAnalysisData() {
      this.loading = true;
      try {
        await this.getKpiData();
        await this.getPolicyRank();
        await this.getTrendAnalysis();

        if (this.showDepartmentAnalysis) {
          await this.getDepartmentAnalysis();
          await this.getOvertimeList();
        }

        await this.getContentAnalysis();

      } catch (error) {
        console.error('加载分析数据失败:', error);
        this.$message.error('加载分析数据失败');
      } finally {
        this.loading = false;
      }
    },

    /** 获取KPI数据 */
    async getKpiData() {
      try {
        const params = this.buildApiParams();
        const res = await PolicyCommunicationsApi.getAnalysisKpi(params);
        if (res.code === 0 && res.data) {
          this.kpiData = res.data;
        } else {
          this.kpiData = {};
        }
      } catch (error) {
        console.error('获取KPI数据失败:', error);
        this.$message.error('获取KPI数据失败');
      }
    },

    /** 获取政策排行 */
    async getPolicyRank() {
      try {
        const params = {
          ...this.buildApiParams(),
          order: this.rankOrder,
          limit: 10
        };
        const res = await PolicyCommunicationsApi.getPolicyRank(params);

        let data = [];
        if (res.code === 0 && res.data && res.data.policyRankList) {
          data = res.data.policyRankList;
        }

        const option = {
          title: {
            text: '政策沟通交流数量排行',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const item = data[params[0].dataIndex];
              return `${item.policyTitle || '未知政策'}<br/>
              沟通数量: ${item.count || 0}<br/>
              回复数量: ${item.replyCount || 0}<br/>
              回复率: ${(item.replyRate || 0).toFixed(1)}%`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: ''
          },
          yAxis: {
            type: 'category',
            data: data.map(item => item.policyTitle || '未知政策'),
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.length > 20 ? value.substring(0, 20) + '...' : value;
              }
            }
          },
          series: [
            {
              name: '沟通数量',
              type: 'bar',
              data: data.map(item => item.count || 0),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }
          ]
        };

        this.charts.policyRankChart?.setOption(option);
      } catch (error) {
        console.error('获取政策排行失败:', error);
        this.$message.error('获取政策排行失败');
      }
    },

    /** 获取趋势分析 */
    async getTrendAnalysis() {
      try {
        const params = {
          ...this.buildApiParams(),
          granularity: this.trendGranularity
        };
        const res = await PolicyCommunicationsApi.getTrendAnalysis(params);

        let data = [];
        if (res.code === 0 && res.data && res.data.trendData) {
          data = res.data.trendData;
        }

        let xAxisData = [];
        let xAxisName = '';

        switch (this.trendGranularity) {
          case 'day':
            xAxisName = '日期';
            xAxisData = data.map(item => item.date || '');
            break;
          case 'week':
            xAxisName = '周次';
            xAxisData = data.map(item => `第${item.week || 0}周`);
            break;
          case 'month':
            xAxisName = '月份';
            xAxisData = data.map(item => `${item.year || '2024'}-${item.month || '01'}`);
            break;
        }

        const option = {
          title: {
            text: '政策沟通交流趋势变化',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            formatter: function(params) {
              const item = data[params[0].dataIndex];
              return `${params[0].axisValue}<br/>
              沟通数量: ${item.count || 0}<br/>
              回复数量: ${item.replyCount || 0}<br/>
              回复率: ${item.count > 0 ? ((item.replyCount || 0) / item.count * 100).toFixed(1) : 0}%`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            name: xAxisName
          },
          yAxis: {
            type: 'value',
            name: '沟通数量'
          },
          series: [
            {
              name: '沟通数量',
              type: 'line',
              data: data.map(item => item.count || 0),
              smooth: true,
              lineStyle: {
                width: 3
              },
              itemStyle: {
                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.1)'
                  }
                ])
              }
            }
          ]
        };

        this.charts.trendChart?.setOption(option);
      } catch (error) {
        console.error('获取趋势分析失败:', error);
        this.$message.error('获取趋势分析失败');
      }
    },

    /** 获取部门分析数据 */
    async getDepartmentAnalysis() {
      if (!this.showDepartmentAnalysis) {
        return;
      }

      try {
        const params = this.buildApiParams();
        const res = await PolicyCommunicationsApi.getDepartmentAnalysis(params);

        let departmentData = [];
        let workloadData = [];

        if (res.code === 0 && res.data) {
          if (res.data.departmentData) {
            departmentData = res.data.departmentData;
            // 按照处理数量排序，显示最重要的部门
            departmentData.sort((a, b) => (b.totalCount || 0) - (a.totalCount || 0));
          }
          if (res.data.workloadDistribution) {
            workloadData = res.data.workloadDistribution;
          }
        }

        // 缓存原始部门数据
        this.departmentRawData = departmentData;

        // 更新部门图表
        this.updateDepartmentCharts();

        // 工作量分布饼图
        const workloadOption = {
          title: {
            text: '部门工作量分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: workloadData.map(item => item.deptName || '未知部门')
          },
          series: [
            {
              name: '工作量',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '20',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: workloadData.map(item => ({
                name: item.deptName || '未知部门',
                value: item.workload || 0
              }))
            }
          ]
        };

        this.charts.workloadChart?.setOption(workloadOption);
      } catch (error) {
        console.error('获取部门分析失败:', error);
        this.$message.error('获取部门分析失败');
      }
    },

    /** 更新部门图表 */
    updateDepartmentCharts() {
      if (!this.showDepartmentAnalysis) {
        return;
      }

      const departmentData = this.displayDepartmentData;

      // 计算动态高度（每项40px，最小400px）
      const baseHeight = 400;
      const itemHeight = 40;
      const calculatedHeight = Math.max(baseHeight, departmentData.length * itemHeight + 100);

      // 设置图表高度
      this.efficiencyChartHeight = calculatedHeight;
      this.replyRateChartHeight = calculatedHeight;

      // 更新效率图表
      this.updateEfficiencyChart(departmentData);

      // 更新回复率图表
      this.updateReplyRateChart(departmentData);

      // 重新渲染图表
      this.$nextTick(() => {
        this.charts.efficiencyChart?.resize();
        this.charts.replyRateChart?.resize();
      });
    },

    /** 更新处理效率图表 */
    updateEfficiencyChart(departmentData) {
      const data = departmentData || this.displayDepartmentData;

      const option = {
        title: {
          text: `部门平均处理时长（${this.displayDepartmentCount === 'all' ? '全部' : this.displayDepartmentCount}个部门）`,
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const item = data[params[0].dataIndex];
            return `${item.deptName || '未知部门'}<br/>
            平均处理天数: ${item.avgProcessDays ? item.avgProcessDays.toFixed(1) : 0}天<br/>
            处理总数: ${item.totalCount || 0}<br/>
            已回复: ${item.repliedCount || 0}<br/>
            待处理: ${item.pendingCount || 0}`;
          }
        },
        grid: {
          left: '15%', // 左边距更大以适应长部门名
          right: '5%',
          top: '15%',
          bottom: '5%',
          containLabel: false // 不包含标签，手动调整
        },
        xAxis: {
          type: 'value',
          name: '处理天数',
          nameLocation: 'middle',
          nameGap: 25,
          axisLabel: {
            formatter: '{value}天'
          }
        },
        yAxis: {
          type: 'category',
          inverse: true, // 反转Y轴，使第一个在最上面
          data: data.map(item => item.deptName || '未知部门'),
          axisLabel: {
            interval: 0,
            width: 120, // 限制标签宽度
            overflow: 'truncate', // 截断
            ellipsis: '...', // 显示省略号
            formatter: function(value) {
              if (value && value.length > 12) {
                return value.substring(0, 12) + '...';
              }
              return value || '未知部门';
            }
          },
          axisTick: {
            show: false // 隐藏刻度线
          },
          axisLine: {
            show: true
          }
        },
        series: [
          {
            name: '平均处理天数',
            type: 'bar',
            data: data.map(item => ({
              value: item.avgProcessDays || 0,
              itemStyle: {
                color: this.getProcessDaysColor(item.avgProcessDays)
              }
            })),
            label: {
              show: true,
              position: 'right',
              formatter: '{c}天',
              color: '#333'
            },
            barWidth: '60%'
          }
        ]
      };

      this.charts.efficiencyChart?.setOption(option);
    },

    /** 获取处理天数颜色 */
    getProcessDaysColor(days) {
      if (!days && days !== 0) return '#909399';
      if (days > 15) return '#F56C6C'; // 红色，表示处理慢
      if (days > 7) return '#E6A23C'; // 黄色，表示一般
      return '#67C23A'; // 绿色，表示处理快
    },

    /** 更新回复率图表 */
    updateReplyRateChart(departmentData) {
      const data = departmentData || this.displayDepartmentData;

      const option = {
        title: {
          text: `部门回复率（${this.displayDepartmentCount === 'all' ? '全部' : this.displayDepartmentCount}个部门）`,
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const item = data[params[0].dataIndex];
            return `${item.deptName || '未知部门'}<br/>
            回复率: ${(item.replyRate || 0).toFixed(1)}%<br/>
            处理总数: ${item.totalCount || 0}<br/>
            已回复: ${item.repliedCount || 0}<br/>
            待处理: ${item.pendingCount || 0}`;
          }
        },
        grid: {
          left: '15%', // 左边距更大以适应长部门名
          right: '5%',
          top: '15%',
          bottom: '5%',
          containLabel: false
        },
        xAxis: {
          type: 'value',
          name: '回复率 (%)',
          nameLocation: 'middle',
          nameGap: 25,
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        yAxis: {
          type: 'category',
          inverse: true, // 反转Y轴
          data: data.map(item => item.deptName || '未知部门'),
          axisLabel: {
            interval: 0,
            width: 120,
            overflow: 'truncate',
            ellipsis: '...',
            formatter: function(value) {
              if (value && value.length > 12) {
                return value.substring(0, 12) + '...';
              }
              return value || '未知部门';
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: true
          }
        },
        series: [
          {
            name: '回复率',
            type: 'bar',
            data: data.map(item => ({
              value: item.replyRate || 0,
              itemStyle: {
                color: this.getReplyRateColor(item.replyRate)
              }
            })),
            label: {
              show: true,
              position: 'right',
              formatter: '{c}%',
              color: '#333'
            },
            barWidth: '60%'
          }
        ]
      };

      this.charts.replyRateChart?.setOption(option);
    },

    /** 获取回复率颜色 */
    getReplyRateColor(rate) {
      if (!rate && rate !== 0) return '#909399';
      if (rate < 60) return '#F56C6C'; // 红色，回复率低
      if (rate < 80) return '#E6A23C'; // 黄色，回复率一般
      return '#67C23A'; // 绿色，回复率高
    },

    /** 获取超时列表 */
    async getOvertimeList() {
      if (!this.showDepartmentAnalysis) {
        return;
      }

      try {
        this.overtimeLoading = true;
        const params = {
          ...this.buildApiParams(),
          overtimeDays: 20
        };
        const res = await PolicyCommunicationsApi.getOvertimeList(params);

        if (res.code === 0 && res.data) {
          this.overtimeList = res.data.overdueList || [];
          this.overtimeSummary = {
            totalOverdueCount: res.data.totalOverdueCount || 0,
            avgOverdueDays: res.data.avgOverdueDays || 0,
            maxOverdueDays: res.data.maxOverdueDays || 0
          };
        } else {
          this.overtimeList = [];
          this.overtimeSummary = {
            totalOverdueCount: 0,
            avgOverdueDays: 0,
            maxOverdueDays: 0
          };
        }
      } catch (error) {
        console.error('获取超时列表失败:', error);
        this.$message.error('获取超时列表失败');
        this.overtimeList = [];
        this.overtimeSummary = {
          totalOverdueCount: 0,
          avgOverdueDays: 0,
          maxOverdueDays: 0
        };
      } finally {
        this.overtimeLoading = false;
      }
    },

    /** 获取内容分析 */
    async getContentAnalysis() {
      try {
        const params = this.buildApiParams();

        const typeRes = await PolicyCommunicationsApi.getTypeDistribution(params);
        let typeData = [];
        let wordCloudData = [];

        if (typeRes.code === 0 && typeRes.data) {
          if (typeRes.data.typeDistribution) {
            typeData = typeRes.data.typeDistribution;
          }
          if (typeRes.data.wordCloudData) {
            wordCloudData = typeRes.data.wordCloudData;
          }
        }

        const typeDict = {
          '咨询': '咨询',
          '建议': '建议',
          '投诉': '投诉',
          '1': '类型1',
          '2': '类型2'
        };

        const typeOption = {
          title: {
            text: '沟通类型分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: typeData.map(item => typeDict[item.typeCode] || item.typeCode || '未知类型')
          },
          series: [
            {
              name: '类型分布',
              type: 'pie',
              radius: '50%',
              data: typeData.map(item => ({
                name: typeDict[item.typeCode] || item.typeCode || '未知类型',
                value: item.count || 0
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };

        const wordCloudOption = {
          title: {
            text: '沟通内容高频词',
            left: 'center'
          },
          tooltip: {
            show: true,
            formatter: function(params) {
              return `${params.name}<br/>出现次数: ${params.value}`;
            }
          },
          series: [{
            type: 'wordCloud',
            shape: 'circle',
            left: 'center',
            top: 'center',
            width: '90%',
            height: '90%',
            right: null,
            bottom: null,
            sizeRange: [12, 60],
            rotationRange: [-90, 90],
            rotationStep: 45,
            gridSize: 8,
            drawOutOfBound: false,
            textStyle: {
              fontFamily: 'sans-serif',
              fontWeight: 'bold',
              color: function () {
                return 'rgb(' + [
                  Math.round(Math.random() * 160),
                  Math.round(Math.random() * 160),
                  Math.round(Math.random() * 160)
                ].join(',') + ')';
              }
            },
            emphasis: {
              focus: 'self',
              textStyle: {
                shadowBlur: 10,
                shadowColor: '#333'
              }
            },
            data: wordCloudData.map(item => ({
              name: item.name || '未知',
              value: item.value || 0
            }))
          }]
        };

        this.charts.typeChart?.setOption(typeOption);
        this.charts.wordCloudChart?.setOption(wordCloudOption);
      } catch (error) {
        console.error('获取内容分析失败:', error);
        this.$message.error('获取内容分析失败');
      }
    },

    /** 构建API参数 */
    buildApiParams() {
      const params = {
        startTime: '',
        endTime: '',
        //departmentIds: this.queryParams.departmentIds.join(','),
        departmentId: this.queryParams.departmentId,
        policyTitle: this.queryParams.policyTitle,
        policyCode: this.queryParams.policyCode,
        submitType: this.queryParams.submitType
      };

      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        params.startTime = this.formatDateTime(this.queryParams.dateRange[0], 'start');
        params.endTime = this.formatDateTime(this.queryParams.dateRange[1], 'end');
      }

      return params;
    },

    /** 格式化日期时间为后端需要的格式 */
    formatDateTime(date, type = 'start') {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');

      if (type === 'start') {
        return `${year}-${month}-${day} 00:00:00`;
      } else {
        return `${year}-${month}-${day} 23:59:59`;
      }
    },

    /** 快速时间选择 */
    handleQuickTimeChange(value) {
      if (!value) {
        this.queryParams.dateRange = [];
        return;
      }

      const end = new Date();
      const start = new Date();

      switch (value) {
        case 'today':
          start.setHours(0, 0, 0, 0);
          end.setHours(23, 59, 59, 999);
          break;
        case '7days':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          break;
        case '30days':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          break;
        case 'year':
          start.setFullYear(start.getFullYear(), 0, 1);
          start.setHours(0, 0, 0, 0);
          break;
      }

      this.queryParams.dateRange = [start, end];
    },

    /** 时间范围变化 */
    handleTimeRangeChange() {
      this.queryParams.quickTime = '';
    },

    /** 查看详情 */
    handleViewDetail(row) {
      console.log('查看详情:', row);
      this.$message.info('查看详情功能待实现');
    },

    /** 导出图表 */
    exportChart(chartName) {
      const chart = this.charts[chartName];
      if (chart) {
        try {
          const dataURL = chart.getDataURL({
            pixelRatio: 2,
            backgroundColor: '#fff'
          });
          const link = document.createElement('a');
          link.href = dataURL;
          link.download = `${chartName}_${new Date().getTime()}.png`;
          link.click();
          this.$message.success('图表导出成功');
        } catch (error) {
          console.error('导出图表失败:', error);
          this.$message.error('导出图表失败');
        }
      }
    },

    /** 导出超时列表 */
    async exportOvertimeList() {
      try {
        const params = this.buildApiParams();
        params.overtimeDays = 20;

        const res = await PolicyCommunicationsApi.exportOvertimeList(params);
        this.$download.excel(res, `超时未回复清单_${new Date().getTime()}.xlsx`);
        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出超时列表失败:', error);
        this.$message.error('导出超时列表失败');
      }
    },

    /** 搜索分析 */
    handleQuery() {
      this.loadAnalysisData();
    },

    /** 重置搜索 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dateRange = [];
      this.queryParams.quickTime = '';
      this.loadAnalysisData();
    },

    /** 窗口大小变化 */
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) chart.resize();
      });
    },

    /** 格式化处理时间 */
    formatProcessTime(days) {
      if (!days && days !== 0) return '0天';
      return days.toFixed(1) + '天';
    },

    /** 格式化比率 */
    formatRate(rate) {
      if (!rate && rate !== 0) return '0%';
      return rate.toFixed(1) + '%';
    },

    /** 时间格式化 */
    parseTime(time) {
      if (!time) return '';
      try {
        const date = new Date(time);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (e) {
        return time;
      }
    }
  }
};
</script>

<style scoped>
.filter-card {
  margin-bottom: 16px;
}

.kpi-row {
  margin-bottom: 20px;
}

.kpi-card {
  border-radius: 8px;
}

.kpi-content {
  display: flex;
  align-items: center;
}

.kpi-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.kpi-icon i {
  font-size: 24px;
  color: white;
}

.kpi-info {
  flex: 1;
}

.kpi-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.kpi-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.scrollable-chart-card {
  overflow: hidden; /* 防止外部溢出 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 滚动图表容器样式 */
.scrollable-chart-container {
  width: 100%;
  height: 400px; /* 固定容器高度 */
  overflow-y: auto; /* 垂直滚动 */
  overflow-x: hidden; /* 隐藏水平滚动 */
  position: relative;
  border-radius: 4px;
  background: #fafafa;
}

.scrollable-chart-container::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.scrollable-chart-container::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道背景 */
  border-radius: 4px;
}

.scrollable-chart-container::-webkit-scrollbar-thumb {
  background: #c1c1c1; /* 滚动条滑块颜色 */
  border-radius: 4px;
}

.scrollable-chart-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8; /* 滑块悬停颜色 */
}

.scrollable-chart {
  width: 100%;
  min-height: 400px; /* 最小高度 */
}

.empty-table {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .kpi-content {
    flex-direction: column;
    text-align: center;
  }

  .kpi-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .chart-card {
    margin-bottom: 16px;
  }

  .scrollable-chart-container {
    height: 300px; /* 移动端高度稍小 */
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .card-header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 1200px) {
  .scrollable-chart-container {
    height: 350px;
  }
}
</style>
