<template>
  <div class="app-container">
    <div class="app-content">
      <div class="title">综合统计看板</div>

      <el-form class="search-form" :inline="true" label-width="90px">
        <el-row :gutter="10">
          <!-- 时间范围选择 -->
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <!-- 统计维度选择 -->
          <el-col :span="4">
            <el-form-item label="统计维度">
              <el-select
                v-model="queryParams.dimension"
                placeholder="请选择统计维度"
                @change="handleDimensionChange"
                clearable
                style="width: 100%">
                <el-option label="个人" :value="1"></el-option>
                <el-option label="公司" :value="2"></el-option>
                <el-option label="部门" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 公司选择 -->
          <el-col :span="4" v-if="showCompanySelect">
            <el-form-item label="选择公司">
              <el-select
                v-model="queryParams.companyId"
                placeholder="请选择公司"
                @change="handleCompanyChange"
                clearable
                :disabled="!queryParams.dimension"
                style="width: 100%">
                <el-option
                  v-for="company in companyList"
                  :key="company.companyId"
                  :label="company.companyName"
                  :value="company.companyId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 部门选择 -->
          <el-col :span="4" v-if="showDepartmentSelect">
            <el-form-item label="选择部门">
              <el-cascader
                v-model="selectedDeptIds"
                :options="deptTreeData"
                :props="deptCascaderProps"
                placeholder="请选择部门"
                clearable
                style="width: 100%"
                @change="handleDeptChange">
              </el-cascader>
            </el-form-item>
          </el-col>

          <!-- 操作按钮 -->
          <el-col :span="6">
            <el-form-item label-width="0" style="padding-top: 35px;">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="success" icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">导出</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table v-loading="loading" :data="paginatedTableData" border style="width: 100%" height="600">
        <!-- 添加时间列 -->
        <el-table-column prop="statisticsTime" label="统计时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.statisticsTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="companyName" label="公司名称"/>
        <el-table-column prop="deptName" label="部门名称" v-if="showDeptNameColumn" />
        <!-- 根据维度决定是否显示人员姓名 -->
        <el-table-column prop="companyUserName" label="人员名称" v-if="showUserNameColumn" />
        <!-- 更新以下列为新的字段名 -->
        <el-table-column prop="sendCount" label="发课数">
          <template slot-scope="scope">
            {{ scope.row.sendCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="completeNum" label="完课数">
          <template slot-scope="scope">
            {{ scope.row.completeNum || 0 }}
          </template>
        </el-table-column>
        <!-- 完播率 -->
        <el-table-column prop="completeRate" label="完播率" width="100">
          <template slot-scope="scope">
            {{ calculateCompleteRate(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="answerNum" label="答题数">
          <template slot-scope="scope">
            {{ scope.row.answerNum || 0 }}
          </template>
        </el-table-column>
        <!-- 答题率 -->
        <el-table-column prop="answerRate" label="答题率" width="100">
          <template slot-scope="scope">
            {{ calculateAnswerRate(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="redPacketNum" label="红包领取数">
          <template slot-scope="scope">
            {{ scope.row.redPacketNum || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="redPacketAmount" label="红包金额(元)">
          <template slot-scope="scope">
            {{ scope.row.redPacketAmount || 0 }}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"        style="margin-top: 20px; text-align: right;">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import { getStatisticsData, getSearchUserInfo, getSearchCompanyInfo, getSearchDeptInfo } from "@/api/statistics/statistics";

export default {
  data() {
    return {
      exportLoading: false, // 添加导出加载状态
      loading: false,
      lastQueryDimension: null, // 记录上次查询的维度
      companyList: [],
      deptList: [], // 原始部门数据
      deptTreeData: [], // 树形部门数据
      selectedDeptIds: [], // 选中的部门ID路径
      userList: [],
      rawData: [],
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      dateRange: [],
      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]);
          }
        }]
      },
      deptCascaderProps: {
        value: 'deptId',
        label: 'deptName',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true, // 允许选择任意一级
        emitPath: false // 只返回选中节点的值，而不是整个路径
      },
      queryParams: {
        dimension: null,
        companyId: null,
        deptId: null,
        userId: null
      }
    };
  },

  computed: {
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },

    showCompanySelect() {
      // 公司维度不需要显示公司选择，其他维度都需要
      return this.queryParams.dimension && this.queryParams.dimension !== 2;
    },

    showDepartmentSelect() {
      // 部门维度不需要显示部门选择，个人维度需要显示
      return this.queryParams.dimension === 1 && this.queryParams.companyId;
    },



    // 控制部门名称列显示
    showDeptNameColumn() {
      // 基于上次查询的维度来决定是否显示部门名称列
      return this.lastQueryDimension && this.lastQueryDimension !== 2;
    },

    // 控制人员姓名列显示
    showUserNameColumn() {
      // 只有个人维度显示人员姓名列
      return this.lastQueryDimension === 1;
    }
  },

  mounted() {
    // 设置默认时间为当天
    const today = new Date();
    this.dateRange = [today, today];
    // 默认设置统计维度为公司
    this.queryParams.dimension = 2;
    this.loadData();
    // 页面初始化时查询一次数据
    this.fetchStatisticsData();
  },

  methods: {
    // 在 loadData 方法中也移除自动查询
    loadData() {
      // 使用 getSearchCompanyInfo 获取公司下拉数据
      getSearchCompanyInfo().then(response => {
        this.companyList = response.data || [];

        // 默认选择第一个公司（如果存在）
        if (this.companyList.length > 0 && this.queryParams.dimension !== 2) {
          this.queryParams.companyId = this.companyList[0].companyId;
          // 加载该公司的部门数据
          return this.loadDeptData(this.queryParams.companyId);
        }
      }).then(() => {
        // 移除自动查询调用，只保留初始加载
        // return this.fetchStatisticsData();
      }).catch(error => {
        console.error('数据加载失败:', error);
        this.$message.error('数据加载失败');
      });
    },

    loadDeptData(companyId) {
      if (!companyId) return Promise.resolve();

      return getSearchDeptInfo({ id: companyId }).then(response => {
        const deptData = response.data || [];
        this.deptList = deptData;

        // 如果后端直接返回树形结构（第一层数据有children），直接使用
        // 否则通过buildDeptTree构建树形结构
        const hasTreeStructure = deptData.some(dept => dept.children && dept.children.length > 0);
        if (hasTreeStructure) {
          this.deptTreeData = deptData.filter(dept => dept.parentId === 0 || dept.parentId === null);
        } else {
          this.deptTreeData = this.buildDeptTree(deptData);
        }

        // 默认选择第一个部门（如果存在）
        if (this.deptTreeData.length > 0 && this.queryParams.dimension === 1) {
          // 选择第一个顶级部门
          this.queryParams.deptId = this.deptTreeData[0].deptId;
          this.selectedDeptIds = [this.queryParams.deptId];
        }
      }).catch(error => {
        console.error('部门数据加载失败:', error);
        this.$message.error('部门数据加载失败');
      });
    },

    // 构建部门树形结构
    buildDeptTree(deptList) {
      if (!deptList || deptList.length === 0) return [];

      // 创建部门映射
      const deptMap = {};
      deptList.forEach(dept => {
        // 如果后端返回的数据中已经有children字段且有值，则使用后端的children
        // 否则初始化为空数组
        deptMap[dept.deptId] = {
          ...dept,
          children: (dept.children && dept.children.length > 0) ? dept.children : []
        };
      });

      // 构建树形结构
      const tree = [];
      deptList.forEach(dept => {
        if (dept.parentId === 0 || dept.parentId === null) {
          // 顶级部门
          tree.push(deptMap[dept.deptId]);
        } else {
          // 子部门 - 只有在后端没有返回children的情况下才手动构建
          if (deptMap[dept.parentId] && (!dept.children || dept.children.length === 0)) {
            deptMap[dept.parentId].children.push(deptMap[dept.deptId]);
          }
        }
      });

      // 清理空的children数组，保持数据结构整洁
      const cleanEmptyChildren = (nodes) => {
        nodes.forEach(node => {
          if (node.children && node.children.length === 0) {
            delete node.children;
          } else if (node.children && node.children.length > 0) {
            cleanEmptyChildren(node.children);
          }
        });
      };
      cleanEmptyChildren(tree);

      return tree;
    },

    // 添加时间格式化方法
    formatDateTime(dateString) {
      if (!dateString) return '';
      // 移除时区信息并格式化日期时间
      const date = new Date(dateString.replace(/\.\d{3}\+\d{4}$/, ''));
      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}`;
    },

    formatDate(date) {
      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');
      return `${year}-${month}-${day}`;
    },

    fetchStatisticsData() {
      this.loading = true; // 开始请求时设置 loading 为 true
      // 构造请求参数对象
      const params = {
        dimension: this.queryParams.dimension,
        startTime: this.formatDate(this.dateRange[0]),
        endTime: this.formatDate(this.dateRange[1])
      };

      // 根据新规则设置id参数
      if (this.queryParams.dimension === 1 && this.queryParams.deptId) {
        // 个人维度传递部门ID
        params.id = this.queryParams.deptId;
      } else if (this.queryParams.dimension === 3 && this.queryParams.companyId) {
        // 部门维度传递公司ID
        params.id = this.queryParams.companyId;
      }
      // 公司维度不传递ID参数

      // 以POST方式发送请求体
      return getStatisticsData(params).then(response => {
        this.rawData = response.data || [];
        this.tableData = [...this.rawData];
        this.currentPage = 1;
      }).catch(error => {
        console.error('统计数据加载失败:', error);
        this.$message.error('统计数据加载失败');
      }).finally(() => {
        this.loading = false; // 请求完成后设置 loading 为 false
      });
    },

    handleCompanyChange(companyId) {
      this.queryParams.deptId = null;
      this.selectedDeptIds = [];
      this.queryParams.userId = null;
      this.deptList = [];
      this.deptTreeData = [];
      this.userList = [];

      if (!companyId) return;

      // 使用 getSearchDeptInfo 获取部门下拉数据
      getSearchDeptInfo({ id: companyId }).then(response => {
        const deptData = response.data || [];
        this.deptList = deptData;

        // 如果后端直接返回树形结构（第一层数据有children），直接使用
        // 否则通过buildDeptTree构建树形结构
        const hasTreeStructure = deptData.some(dept => dept.children && dept.children.length > 0);
        if (hasTreeStructure) {
          this.deptTreeData = deptData.filter(dept => dept.parentId === 0 || dept.parentId === null);
        } else {
          this.deptTreeData = this.buildDeptTree(deptData);
        }

        // 默认选择第一个部门（如果存在）
        // 仅在个人维度下默认选择第一个部门
        if (this.deptTreeData.length > 0 && this.queryParams.dimension === 1) {
          // 选择第一个顶级部门
          this.queryParams.deptId = this.deptTreeData[0].deptId;
          this.selectedDeptIds = [this.queryParams.deptId];
        }
      }).catch(error => {
        console.error('部门数据加载失败:', error);
        this.$message.error('部门数据加载失败');
      });
      // 移除.then()后面的自动查询调用
    },
    handleDeptChange(selectedDeptId) {
      // 更新选中的部门ID
      this.queryParams.deptId = selectedDeptId;
    },

    handleQuery() {
      // 记录当前查询的维度
      this.lastQueryDimension = this.queryParams.dimension;
      // 触发统计数据请求
      this.fetchStatisticsData();
    },

    handleDimensionChange() {
      // 重置后续选择项
      this.queryParams.companyId = null;
      this.queryParams.deptId = null;
      this.selectedDeptIds = [];
      this.queryParams.userId = null;
      this.deptList = [];
      this.deptTreeData = [];
      this.userList = [];
    },

    resetQuery() {
      this.queryParams = {
        dimension: 2, // 重置为公司维度
        companyId: null,
        deptId: null,
        userId: null
      };
      this.selectedDeptIds = []; // 重置部门选择
      // 重置时间为当天
      const today = new Date();
      this.dateRange = [today, today];
      this.deptList = [];
      this.deptTreeData = [];
      this.userList = [];
      this.tableData = [...this.rawData];
      this.currentPage = 1;
      // 重置后立即发送请求
      this.lastQueryDimension = 2; // 同时更新lastQueryDimension
      this.fetchStatisticsData();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },

    handleCurrentChange(val) {
      this.currentPage = val;
    },

    // 计算完播率：完课数 / 发送数
    calculateCompleteRate(row) {
      const sendCount = row.sendCount || 0;
      const completeNum = row.completeNum || 0;

      if (sendCount === 0) {
        return '0%';
      }

      const rate = (completeNum / sendCount * 100).toFixed(2);
      return rate + '%';
    },

    // 计算答题率：答题数 / 完课数
    calculateAnswerRate(row) {
      const completeNum = row.completeNum || 0;
      const answerNum = row.answerNum || 0;

      if (completeNum === 0) {
        return '0%';
      }

      const rate = (answerNum / completeNum * 100).toFixed(2);
      return rate + '%';
    },
    // 添加导出方法
    handleExport() {
      if (this.tableData.length === 0) {
        this.$message.warning('没有可导出的数据');
        return;
      }

      this.exportLoading = true;

      try {
        // 创建 CSV 内容
        const headers = [
          '统计时间', '公司名称', '部门名称', '人员名称',
          '发课数', '完课数', '完播率', '答题数', '答题率',
          '红包领取数', '红包金额(元)'
        ];

        const csvContent = [
          headers.join(','),
          ...this.tableData.map(row => [
            this.formatDateTime(row.statisticsTime),
            row.companyName || '',
            row.deptName || '',
            row.companyUserName || '',
            row.sendCount || 0,
            row.completeNum || 0,
            this.calculateCompleteRate(row),
            row.answerNum || 0,
            this.calculateAnswerRate(row),
            row.redPacketNum || 0,
            row.redPacketAmount || 0
          ].map(field => `"${field}"`).join(','))
        ].join('\n');

        // 创建下载链接
        const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);

        link.setAttribute('href', url);

        // link.setAttribute('download', `综合统计看板_${new Date().toISOString().slice(0, 10)}.csv`);
        // 修改为：
        const now = new Date();
        const timestamp = now.getFullYear() +
          String(now.getMonth() + 1).padStart(2, '0') +
          String(now.getDate()).padStart(2, '0') +
          String(now.getHours()).padStart(2, '0') +
          String(now.getMinutes()).padStart(2, '0') +
          String(now.getSeconds()).padStart(2, '0');
        link.setAttribute('download', `综合统计看板_${timestamp}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败');
      } finally {
        this.exportLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  border: 1px solid #e6e6e6;
  padding: 12px;
  background-color: #f5f7fa;
}

.app-content {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 18px;
  width: 100%;
}

.search-form .el-row {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.table-section {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}

.table-section .el-table {
  width: 100% !important;
}

@media (min-width: 1200px) {
  .table-section {
    padding: 20px 50px;
  }
}
</style>
