<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="8">
        <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: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 处理效率 -->
      <el-col :xs="24" :lg="8">
        <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('efficiencyChart')">导出</el-button>
          </div>
          <div ref="efficiencyChart" style="height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 响应情况 -->
      <el-col :xs="24" :lg="8">
        <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('replyRateChart')">导出</el-button>
          </div>
          <div ref="replyRateChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 超时未回复清单 -->
    <!--    <el-card class="mb20" shadow="hover" v-if="showDepartmentAnalysis">
          <div slot="header" class="card-header">
            <span>超时未回复清单（超过20个工作日）</span>
            <el-tag type="danger" size="small" v-if="overtimeSummary.totalOverdueCount > 0">
              共{{ overtimeSummary.totalOverdueCount }}条
            </el-tag>
            <el-button size="mini" icon="el-icon-download" @click="exportOvertimeList">导出Excel</el-button>
          </div>
          <el-table
            v-loading="overtimeLoading"
            :data="overtimeList"
            :stripe="true"
            style="width: 100%"
          >
            <el-table-column label="政策标题" prop="policyTitle" min-width="200" show-overflow-tooltip />
            <el-table-column label="沟通主题" prop="title" min-width="200" show-overflow-tooltip />
            <el-table-column label="提交时间" prop="submitTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.submitTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="处理部门" prop="replyDept" width="150" />
            <el-table-column label="已超时天数" prop="overtimeDays" width="120">
              <template v-slot="scope">
                <el-tag type="danger">{{ scope.row.overtimeDays }}天</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template v-slot="scope">
                <el-button type="text" size="mini" @click="handleViewDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="overtimeList.length === 0" class="empty-table">
            <el-empty description="暂无超时未回复记录" />
          </div>
        </el-card>-->

    <!-- 政策沟通交流内容分析 -->
    <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: []
    };
  },
  computed: {
    /** 判断是否显示部门分析相关图表 */
    showDepartmentAnalysis() {
      // 如果用户角色包含 trs_policy_user，则不显示部门分析图表
      return !this.userRoles.includes('trs_policy_user');
    }
  },
  created() {
    this.initData();
    this.loadAnalysisData();
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.handleResize);
  },
  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();
        console.log('原始部门数据:', deptRes.data); // 打印原始数据

        // 获取部门列表，排除特定名称的部门
        let allDepartments = deptRes.data.departmentList || [];

        // 定义要排除的部门名称列表
        const excludedNames = ['平台管理', '自治区政府及部门', '拓尔思', '纵横伟业', '技术运维单位', '凌动科技有限公司','中国联通','灵奕','世纪泓科技有限公司','新华网'];

        // 过滤掉指定名称的部门
        this.departmentList = allDepartments.filter(dept => {
          if (!dept.name) return false;
          // 检查部门名称是否在被排除的列表中
          return !excludedNames.includes(dept.name.trim());
        });

        // 记录被过滤掉的部门
        const excludedDepartments = allDepartments.filter(dept => {
          if (!dept.name) return false;
          return excludedNames.includes(dept.name.trim());
        });

        if (excludedDepartments.length > 0) {
          console.log('被排除的部门:', excludedDepartments);
          console.log('过滤后剩余的部门数量:', this.departmentList.length);
        }

        // 获取用户角色信息
        await this.loadUserRoles();
      } catch (error) {
        console.error('初始化数据失败:', error);
        this.$message.error('初始化数据失败');
      }
    },

    /** 加载用户角色 */
    async loadUserRoles() {
      try {
        // 从 Vuex store 中获取用户角色
        // 假设使用 Vuex 管理用户状态
        if (this.$store && this.$store.getters) {
          const userInfo = this.$store.getters.user || {};
          this.userRoles = userInfo.roles || [];

          // 或者如果有单独的 roles getter
          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 {
        // 如果有获取用户信息的 API
        // const res = await this.$api.user.getInfo();
        // return res.data || {};
        return {};
      } catch (error) {
        return {};
      }
    },

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

      // 部门分析图表
      const departmentCharts = [
        'workloadChart',
        'efficiencyChart',
        'replyRateChart'
      ];

      // 初始化所有基础图表
      baseCharts.forEach(ref => {
        const dom = this.$refs[ref];
        if (dom) {
          this.charts[ref] = echarts.init(dom);
        }
      });

      // 根据角色决定是否初始化部门分析图表
      if (this.showDepartmentAnalysis) {
        departmentCharts.forEach(ref => {
          const dom = this.$refs[ref];
          if (dom) {
            this.charts[ref] = echarts.init(dom);
          }
        });
      }
    },

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

        // 获取民意热度分析数据
        await this.getPolicyRank();
        await this.getTrendAnalysis();

        // 只有非 trs_policy_user 角色才获取部门效能分析数据和超时清单
        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 > 10 ? value.substring(0, 10) + '...' : 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() {
      // 如果用户是 trs_policy_user，则不获取部门分析数据
      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;
          }
          if (res.data.workloadDistribution) {
            workloadData = res.data.workloadDistribution;
          }
        }

        // 工作量分布
        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
              }))
            }
          ]
        };

        // 处理效率 - 使用 departmentData
        const efficiencyOption = {
          title: {
            text: '部门平均处理时长',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const item = departmentData[params[0].dataIndex];
              return `${item.deptName || '未知部门'}<br/>
              平均处理天数: ${item.avgProcessDays || 0}天<br/>
              处理总数: ${item.totalCount || 0}<br/>
              已回复: ${item.repliedCount || 0}`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: ''
          },
          yAxis: {
            type: 'category',
            data: departmentData.map(item => item.deptName || '未知部门'),
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value && value.length > 10 ? value.substring(0, 10) + '...' : (value || '未知部门');
              }
            }
          },
          series: [
            {
              name: '平均处理天数',
              type: 'bar',
              data: departmentData.map(item => item.avgProcessDays || 0),
              itemStyle: {
                color: function(params) {
                  const days = params.value;
                  if (days > 15) return '#F56C6C';
                  if (days > 7) return '#E6A23C';
                  return '#67C23A';
                }
              }
            }
          ]
        };

        // 回复率 - 使用 departmentData
        const replyRateOption = {
          title: {
            text: '部门回复率',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const item = departmentData[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: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: '',
            max: 100
          },
          yAxis: {
            type: 'category',
            data: departmentData.map(item => item.deptName || '未知部门'),
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value && value.length > 10 ? value.substring(0, 10) + '...' : (value || '未知部门');
              }
            }
          },
          series: [
            {
              name: '回复率',
              type: 'bar',
              data: departmentData.map(item => item.replyRate || 0),
              label: {
                show: true,
                position: 'right',
                formatter: '{c}%'
              },
              itemStyle: {
                color: function(params) {
                  const rate = params.value;
                  if (rate < 60) return '#F56C6C';
                  if (rate < 80) return '#E6A23C';
                  return '#67C23A';
                }
              }
            }
          ]
        };

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

    /** 获取超时列表 */
    async getOvertimeList() {
      // 如果用户是 trs_policy_user，则不获取超时列表
      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) {
        // 开始时间设置为当天的 00:00:00
        params.startTime = this.formatDateTime(this.queryParams.dateRange[0], 'start');
        // 结束时间设置为当天的 23:59:59
        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;
}

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

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

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

/* 响应式调整 */
@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;
  }
}
</style>
