
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="课程" prop="courseId">
        <el-select filterable v-model="queryParams.courseId" placeholder="请选择课程"
                   clearable size="small" @change="courseChange(queryParams.courseId)">
          <el-option
            v-for="dict in courseList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程小节" prop="videoId">
        <el-select filterable v-model="queryParams.videoId" placeholder="请选择课程小节"
                   clearable size="small">
          <el-option
            v-for="dict in videoList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售名称" prop="salesName">
        <el-input v-model="queryParams.salesName" placeholder="请输入销售名称" clearable size="small" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="createTime"
          size="small"          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
          :disabled-date="disabledDate"
          @change="handleCreateTimeChange"></el-date-picker>
      </el-form-item>
      <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
      v-loading="loading"
      border
      :data="packageList"
      show-summary
      :summary-method="getSummaries"
      height="600"
    >
      <el-table-column label="销售名称" align="center" prop="salesName" />
      <el-table-column label="APP 会员数" align="center" prop="appUserCount" />
      <el-table-column label="新注册 APP 会员数" align="center" prop="newAppUserCount" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程小节" align="center" prop="videoTitle" />
      <el-table-column label="完课数" align="center" prop="finishedCount" />
      <el-table-column label="完课率" align="center" prop="completionRate">
        <template slot-scope="scope">
          <span v-if="typeof scope.row.completionRate === 'number'">
            {{ (scope.row.completionRate * 100).toFixed(2) }}%
          </span>
          <span v-else>
            {{ scope.row.completionRate || '0.00%' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="未看课数" align="center" prop="notWatchedCount" />
      <el-table-column label="中断数" align="center" prop="interruptCount" />
      <el-table-column label="看课中数" align="center" prop="watchingCount" />
      <el-table-column label="答题数" align="center" prop="answeredCount" />
      <el-table-column label="答题正确数" align="center" prop="correctCount" />
      <el-table-column label="答题正确率" align="center" prop="correctRate">
        <template slot-scope="scope">
          <span v-if="typeof scope.row.correctRate === 'number'">
            {{ (scope.row.correctRate * 100).toFixed(2) }}%
          </span>
          <span v-else>
            {{ scope.row.correctRate || '0.00%' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="红包个数" align="center" prop="redPacketCount" />
      <el-table-column label="红包金额" align="center" prop="redPacketAmount" />
    </el-table>
  </div>
</template>

<script>import { courseList, videoList } from '@/api/course/courseRedPacketLog';
import { appWatchCourseStatistics, appWatchCourseStatisticsExport } from "@/api/app/statistics/appStatistics";

export default {
  name: "appWatchCourseStatistics",
  components: {},
  data() {
    return {
      courseList: [],
      videoList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      createTime: null,
      // 表格数据
      packageList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        courseId: null,
        videoId: null,
        salesName: null,
        sTime: null,
        eTime: null
      }
    };
  },
  created() {
    this.initDefaultDate();
    this.getList();
    courseList().then(response => {
      this.courseList = response.list;
    });
  },
  methods: {
    /** 初始化默认日期为今天 */
    initDefaultDate() {
      const today = this.parseTime(new Date(), '{y}-{m}-{d}');
      this.createTime = today;
      this.queryParams.sTime = today;
      this.queryParams.eTime = today;
    },

    /** 禁用日期选择 - 只能选择今天及之前的日期 */
    disabledDate(time) {
      return time.getTime() > Date.now();
    },

    /** 课程变更处理 */
    courseChange(row) {
      this.queryParams.videoId = null;
      if (row === '') {
        this.videoList = [];
        return;
      }
      videoList(row).then(response => {
        this.videoList = response.list;
      });
    },

    /** 创建时间变更处理 */
    handleCreateTimeChange(val) {
      if (val) {
        this.queryParams.sTime = val;
        this.queryParams.eTime = val;
      } else {
        this.queryParams.sTime = null;
        this.queryParams.eTime = null;
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.initDefaultDate();
      this.queryParams.courseId = null;
      this.queryParams.videoId = null;
      this.queryParams.salesName = null;
      this.videoList = [];
      this.handleQuery();
    },

    /** 获取表格合计方法 */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        const values = data.map(item => Number(item[column.property]));

        if (['appUserCount', 'newAppUserCount', 'finishedCount', 'notWatchedCount', 'interruptCount', 'watchingCount', 'answeredCount', 'correctCount', 'redPacketCount'].includes(column.property)) {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + value;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = 'N/A';
          }
        } else if (column.property === 'redPacketAmount') {
          if (!values.every(value => isNaN(value))) {
            const total = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + value;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = total.toFixed(2);
          } else {
            sums[index] = 'N/A';
          }
        } else if (column.property === 'completionRate') {
          const totalFinished = data.reduce((sum, item) => sum + (Number(item.finishedCount) || 0), 0);
          const totalCount = totalFinished + data.reduce((sum, item) => sum + (Number(item.notWatchedCount) || 0), 0);

          if (totalCount > 0) {
            const rate = (totalFinished / totalCount * 100).toFixed(2);
            sums[index] = `${rate}%`;
          } else {
            sums[index] = '0.00%';
          }
        } else if (column.property === 'correctRate') {
          const totalAnswered = data.reduce((sum, item) => sum + (Number(item.answeredCount) || 0), 0);
          const totalCorrect = data.reduce((sum, item) => sum + (Number(item.correctCount) || 0), 0);

          if (totalAnswered > 0) {
            const rate = (totalCorrect / totalAnswered * 100).toFixed(2);
            sums[index] = `${rate}%`;
          } else {
            sums[index] = '0.00%';
          }
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      appWatchCourseStatistics(this.queryParams).then(response => {
        this.packageList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出 APP 看课统计数据项？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return appWatchCourseStatisticsExport(this.queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    },

    /** 时间格式化 */
    parseTime(time, pattern) {
      if (!time) return null;
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
      let date;
      if (typeof time === 'string') {
        date = new Date(time.replace(/-/g, '/'));
      } else {
        date = new Date(time);
      }
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hour = date.getHours();
      const minute = date.getMinutes();
      const second = date.getSeconds();

      const obj = {
        '{y}': year,
        '{m}': month < 10 ? '0' + month : month,
        '{d}': day < 10 ? '0' + day : day,
        '{h}': hour < 10 ? '0' + hour : hour,
        '{i}': minute < 10 ? '0' + minute : minute,
        '{s}': second < 10 ? '0' + second : second
      };

      return format.replace(/\{(\w+)\}/g, (match, key) => obj[`{${key}}`] || match);
    }
  }
};
</script>

<style scoped>.mb8 {
  margin-bottom: 8px;
}

::v-deep .el-table .el-table__header th {
  background-color: #f5f7fa;
}

::v-deep .el-table__body-wrapper {
  overflow-y: auto;
}
</style>
