<template>
  <div class="app-container">
    <!-- 添加维度切换Tab -->
    <el-tabs v-model="activeDimension" @tab-click="handleDimensionChange">
      <el-tab-pane label="公司维度" name="company"></el-tab-pane>
      <el-tab-pane label="课程维度" name="course"></el-tab-pane>
      <el-tab-pane label="小节维度" name="video"></el-tab-pane>
    </el-tabs>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="公司名" prop="companyId" v-if="activeDimension === 'company'">
        <el-select filterable v-model="queryParams.companyId" placeholder="请选择公司名"
                   clearable size="small">
          <el-option
            v-for="item in companys"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程" prop="courseId" v-if="activeDimension === 'course'||activeDimension === 'video'">
        <el-select filterable v-model="queryParams.courseId" placeholder="请选择课程"
                   clearable size="small" @change="handleCourseChange">
          <el-option
            v-for="item in courses"
            :key="item.courseId"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="小节" prop="videoId" v-if="activeDimension === 'video' && queryParams.courseId">
        <el-select filterable v-model="queryParams.videoId" placeholder="请选择小节"
                   clearable size="small">
          <el-option
            v-for="item in videos"
            :key="item.videoId"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-form-item label="看课时间" prop="createTime">
          <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd"
                          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                          @change="xdChange"></el-date-picker>
        </el-form-item>
        <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-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table height="500" v-loading="loading" border :data="packageOrderList">
      <el-table-column label="销售公司" align="center" prop="companyName" width="120px"
                       v-if="activeDimension === 'company'"/>
      <el-table-column label="课程名称" align="center" prop="courseName"
                       v-if="activeDimension === 'course'"/>
      <el-table-column label="小节名称" align="center" prop="videoName"
                       v-if="activeDimension === 'video'"/>
      <el-table-column label="进线人数" align="center" prop="accessCount"/>
      <el-table-column label="完课人数" align="center" prop="finishedCount"/>
      <el-table-column label="完播数" align="center" prop="courseCompleteTimes"/>
      <el-table-column label="完课率" align="center" prop="finishRate"/>
    </el-table>
    <div class="total-summary">
      <span class="total-title">总计：</span>
      <span class="total-item">进线人数: {{ calculatedTotalData.accessCount }}</span>
      <span class="total-item">完课人数: {{ calculatedTotalData.finishedCount }}</span>
      <span class="total-item">完课率: {{ calculatedTotalData.finishRate}}</span>
      <span class="total-item">完播数: {{ calculatedTotalData.courseCompleteTimes }}</span>
    </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listPackageOrder, getPackageOrder, delPackageOrder, addPackageOrder, updatePackageOrder, exportPackageOrder,
  PackageOrderReport, orderReport, courseReport, exportOrderReport, exportCourseReport
} from "@/api/his/packageOrder";
import {getCompanyList} from "@/api/company/company";
import packageOrderDetails from '../../components/his/packageOrderDetails.vue';
import {treeselect} from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getTask} from "@/api/common";
import {getCourseList, getVideosByCourse} from "@/api/course/userWatchCourseStatistics";

export default {
  name: "PackageOrder",
  components: {packageOrderDetails, Treeselect},
  data() {
    return {
      normalizer: function(node) {
        return {
          id: node.id || node.dictValue,
          label: node.label || node.dictLabel,
          children: node.children
        }
      },
      // 添加用于存储计算总和的数据
      calculatedTotalData: {
        accessCount: 0,
        finishedCount: 0,
        finishRate: '0%',
        courseCompleteTimes: 0,
      },
      totalData: {},
      companys: [],
      courses: [],  // 课程列表
      videos: [],   // 小节列表
      activeDimension: 'company', // 当前激活的维度
      companyId: undefined,
      show: {
        open: false,
      },
      sourceOptions: [],
      actName: "2",
      // 遮罩层
      loading: true,
      startTime: null,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      createTime: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      endTime: null,
      // 总条数
      total: 0,
      // 套餐订单表格数据
      packageOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否支付字典
      isPayOptions: [],
      // 状态字典
      statusOptions: [],
      refundStatusOptions: [],
      packageSubTypeOptions: [],
      payTypeOptions: [],
      deliveryPayStatusOptions: [],
      deliveryStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        userId: null,
        doctorId: null,
        doctorName: null,
        phone: null,
        phoneMk: null,
        packageId: null,
        packageName: null,
        payMoney: null,
        isPay: null,
        days: null,
        status: null,
        startTime: null,
        startDate: null,
        endDate:null,
        finishTime: null,
        sTime: null,
        eTime: null,
        stTime: null,
        endTime: null,
        endStartTime: null,
        endEndTime: null,
        companyUserName: null,
        companyName: null,
        deptId: null,
        source: null,
        dimension: 'company',  // 添加维度参数
        courseId: null,    // 课程ID
        videoId: null     // 小节ID
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    // 设置默认时间为前一天
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    this.createTime = [formatDate(yesterday), formatDate(yesterday)];
    this.queryParams.sTime = this.createTime[0];
    this.queryParams.eTime = this.createTime[1];
    // 获取课程列表
    getCourseList().then(response => {
      this.courses = response.data;
    })
    getCompanyList().then(response => {
      this.companys = response.data;
      if (this.companys != null && this.companys.length > 0) {
        this.companyId = this.companys[0].companyId;
      }
      this.companys.push({companyId: "-1", companyName: "无"})
    });
    this.getList();
  },
  methods: {
    /** 查询套餐订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.dimension = this.activeDimension;
      let requestParams = { ...this.queryParams };
      if (this.activeDimension === 'video') {
        // 在小节维度下，如果已选择小节，只保留videoId，不传递courseId
        if (requestParams.videoId) {
          delete requestParams.courseId;
        }
      }
      courseReport(requestParams).then(response => {
        const rows = response.rows || [];
        // 标准化数据，为缺失字段提供默认值
        this.packageOrderList = rows.map(item => ({
          ...item,
          // 确保必需字段存在，如果缺失则提供默认值
          companyName: item.companyName || '-',
          courseName: item.courseName || '-',
          videoName: item.videoName || '-',
          accessCount: item.accessCount || 0,
          finishedCount: item.finishedCount || 0,
          courseCompleteTimes: item.courseCompleteTimes || 0,
          finishRate: item.finishRate || '0%',
        }));
        console.log("列表数据:", this.packageOrderList);
        this.total = response.total;
        this.calculateTotals();
      }).catch(error => {
        // 即使接口返回错误，也要重置加载状态
        console.error('获取数据失败:', error);
        this.packageOrderList = [];
        this.total = 0;
      }).finally(() => {
        // 无论成功或失败，都重置加载状态
        this.loading = false;
        // 延迟强制更新以确保DOM完全渲染
        setTimeout(() => {
          this.$forceUpdate();
        }, 100);
      });
    },
    calculateTotals() {
      // 重置总计数据
      this.calculatedTotalData = {
        accessCount: 0,
        finishedCount: 0,
        courseCompleteTimes: 0,
        finishRate: '0%',
      };

      // 遍历当前页数据计算总和
      this.packageOrderList.forEach(item => {
        this.calculatedTotalData.accessCount += Number(item.accessCount) || 0;
        this.calculatedTotalData.finishedCount += Number(item.finishedCount) || 0;
        this.calculatedTotalData.courseCompleteTimes += Number(item.courseCompleteTimes) || 0;
      });

      if (this.calculatedTotalData.accessCount > 0) {
        // 完课率 = 完课人数 / 进线人数
        this.calculatedTotalData.finishRate = ((this.calculatedTotalData.finishedCount / this.calculatedTotalData.accessCount) * 100).toFixed(2) + '%';
      } else {
        this.calculatedTotalData.finishRate = '0.00%';
      }
    },
    /** 维度切换处理 */
    handleDimensionChange(tab) {
      this.activeDimension = tab.name;
      // 更新查询参数中的维度
      this.queryParams.dimension = tab.name;

      // 重置相关查询参数
      if (this.activeDimension === 'company') {
        // 公司维度，清空课程和小节参数
        this.queryParams.courseId = null;
        this.queryParams.videoId = null;
      } else if (this.activeDimension === 'course') {
        // 课程维度，清空公司和小节参数
        this.queryParams.companyId = null;
        this.queryParams.videoId = null;
      } else if (this.activeDimension === 'video') {
        // 保留 courseId 的选择状态，但清空 videoId
        this.queryParams.videoId = null;
      }

      // 清空小节列表
      this.videos = [];
      // 重新获取数据
      this.getList();
    },
    /** 课程变更处理 */
    handleCourseChange(val) {
      // 在课程维度和小节维度都需要处理课程变更
      if (this.activeDimension === 'course' || this.activeDimension === 'video') {
        this.queryParams.courseId = val;
        this.queryParams.videoId = null; // 清空已选择的小节

        if (val) {
          // 根据课程ID获取对应的小节列表
          this.getVideosByCourseId(val);
        } else {
          // 如果清空课程，也清空小节选项
          this.videos = [];
        }
      }
    },

    /** 根据训练营获取营期数据 */
    getVideosByCourseId(courseId) {
      getVideosByCourse(courseId).then((response) => {
        this.videos = response.data || [];
      }).catch(error => {
        console.error('获取小节数据失败:', error);
        this.videos = [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderSn: null,
        userId: null,
        doctorId: null,
        packageId: null,
        packageName: null,
        payMoney: null,
        isPay: null,
        days: null,
        status: 0,
        startTime: null,
        finishTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清空所有时间相关变量
      this.createTime = null;
      this.startTime = null;
      this.endTime = null;

      // 重置所有查询参数
      this.queryParams = {
        pageNum: null,
        pageSize: null,
        orderSn: null,
        userId: null,
        doctorId: null,
        doctorName: null,
        phone: null,
        phoneMk: null,
        packageId: null,
        packageName: null,
        payMoney: null,
        isPay: null,
        days: null,
        status: null,
        startTime: null,
        finishTime: null,
        sTime: null,
        eTime: null,
        stTime: null,
        endTime: null,
        endStartTime: null,
        endEndTime: null,
        companyUserName: null,
        companyName: null,
        deptId: null,
        source: null,
        dimension: this.activeDimension,  // 维持当前维度
        companyId: null,  // 重置所有维度ID
        courseId: null,
        videoId: null,
      };
      // 重新获取课程列表
      getCourseList().then(response => {
        this.courses = response.data;
      });
      this.videos = [];
      // 立即执行查询
      this.handleQuery();
    },
    xdChange() {
      if (this.createTime != null) {
        this.queryParams.sTime = this.createTime[0];
        this.queryParams.eTime = this.createTime[1];
      } else {
        this.queryParams.sTime = null;
        this.queryParams.eTime = null;
      }
    },
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出完课统计报表', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportCourseReport(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    endChange() {
      if (this.endTime != null) {
        this.queryParams.endStartTime = this.endTime[0];
        this.queryParams.endEndTime = this.endTime[1];
      } else {
        this.queryParams.endStartTime = null;
        this.queryParams.endEndTime = null;
      }
    }
  }
};
</script>

<style scoped>
.total-summary {
  margin-top: 15px;
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.total-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  margin-right: 20px;
  flex-shrink: 0;
}

.total-item {
  margin-right: 25px;
  padding: 5px 10px;
  background: white;
  border-radius: 3px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
  display: inline-block;
  margin-bottom: 5px;
  font-size: 13px;
  color: #606266;
}

.total-item::before {
  content: "";
  display: inline-block;
  width: 3px;
  height: 3px;
  background: #409eff;
  border-radius: 50%;
  margin-right: 5px;
  vertical-align: middle;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .total-summary {
    flex-direction: column;
    align-items: flex-start;
  }

  .total-title {
    margin-bottom: 10px;
  }

  .total-item {
    margin-right: 10px;
    margin-bottom: 8px;
  }
}
</style>
