<template>
  <div class="app-container">
    <!-- Tab 切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="公司" name="company"></el-tab-pane>
      <el-tab-pane label="项目" name="project"></el-tab-pane>
      <el-tab-pane label="课程" name="course"></el-tab-pane>
      <el-tab-pane label="公开课" name="common"></el-tab-pane>
    </el-tabs>

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 公司选择 -->
      <el-form-item label="公司" v-if="activeTab === 'all' || activeTab === 'company'">
        <el-select v-model="queryParams.companyId" placeholder="请选择公司" filterable clearable size="small">
          <el-option v-for="(option, index) in companyList" :key="index" :value="option.dictValue" :label="option.dictLabel"></el-option>
        </el-select>
      </el-form-item>

      <!-- 项目选择 -->
      <el-form-item label="项目" v-if="activeTab === 'all' || activeTab === 'project'">
        <el-select v-model="queryParams.project" placeholder="请选择项目" filterable clearable size="small">
          <el-option v-for="dict in projectOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>

      <!-- 课程选择 -->
      <el-form-item label="课程" v-if="activeTab === 'all' || activeTab === 'course'">
        <el-select v-model="queryParams.courseId" placeholder="请选择课程" filterable clearable size="small">
          <el-option v-for="dict in courseLists" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="公开课" v-if="activeTab === 'all' || activeTab === 'common'">
        <el-select v-model="queryParams.courseId" placeholder="请选择课程" filterable clearable size="small">
          <el-option v-for="dict in courseLists" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>

      <!-- 时间选择 -->
      <el-form-item label="年月">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          placeholder="选择年月"
          :value-format="'yyyy-MM-dd'"
          :picker-options="pickerOptions"
          @change="handleDateData"
        ></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-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['course:courseTrafficLog:export']" >导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table border v-loading="loading" :data="courseTrafficLogList" @selection-change="handleSelectionChange"
              show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 公司列 -->
      <el-table-column label="公司" align="center" prop="companyName" v-if="activeTab === 'all' || activeTab === 'company'" />
      <!-- 项目列 -->
      <el-table-column label="项目" align="center" prop="projectName" v-if="activeTab === 'all' || activeTab === 'project'" />
      <!-- 课程列 -->
      <el-table-column label="课程" align="center" prop="courseName" v-if="activeTab === 'all' || activeTab === 'course'||activeTab === 'common'" />
      <el-table-column label="日期" align="center" prop="month" />
      <el-table-column label="使用流量" align="center">
        <template slot-scope="scope">
          <span>{{ formatTrafficData(scope.row.totalInternetTraffic) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listCourseTrafficLog, exportCourseTrafficLog } from "@/api/course/courseTrafficLog";
import { courseList } from "@/api/course/courseRedPacketLog";
import { allList } from "@/api/company/company";

export default {
  data() {
    return {
      activeTab: "company", // 默认 tab
      timeRange: null, // 时间范围单独绑定
      companyList: [],
      projectOptions: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const start = new Date();
              const end = new Date();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨日',
            onClick(picker) {
              const start = new Date();
              start.setDate(start.getDate() - 1);
              const end = new Date(start);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '本周',
            onClick(picker) {
              const now = new Date();
              const day = now.getDay() || 7;
              const start = new Date(now);
              start.setDate(now.getDate() - day + 1);
              const end = new Date();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const start = new Date(new Date().setDate(1));
              const end = new Date();
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      courseLists: [],
      loading: false,
      exportLoading: false,
      showSearch: true,
      total: 0,
      courseTrafficLogList: [],
      queryParams: {
        tabType: "", // 当前 tab 类型
        startDate: null,
        endDate: null,
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        project: null,
        courseId: null
      }
    };
  },
  created() {
    courseList().then(res => this.courseLists = res.list);
    this.getDicts("sys_course_project").then(res => this.projectOptions = res.data);
    this.getAllCompany();
    this.getList();
  },
  methods: {

    getSummaries(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          // 第一列显示"总计"
          sums[index] = '总计'
          return
        }

        // 如果是流量列
        if (column.property === 'totalInternetTraffic' ||
          (column.label === '使用流量' && !column.property)) {
          const values = data.map(item => Number(item.totalInternetTraffic) || 0)
          if (!values.every(value => isNaN(value))) {
            const total = values.reduce((prev, curr) => {
              const value = Number(curr)
              return prev + (isNaN(value) ? 0 : value)
            }, 0)
            sums[index] = this.formatTrafficData(total)
          } else {
            sums[index] = 'N/A'
          }
        } else {
          // 其他列留空
          sums[index] = ''
        }
      })

      return sums
    },

    handleTabClick(tab) {
      this.queryParams.tabType = tab.name;
      this.queryParams.pageNum = 1;

      // 清理互斥参数
      if (tab.name !== "project") this.queryParams.project = null;
      if (tab.name !== "course") this.queryParams.courseId = null;
      if (tab.name !== "company") this.queryParams.companyId = null;

      this.getList();
    },

    handleDateData() {
      if (this.timeRange) {
        this.queryParams.startDate = this.timeRange[0];
        this.queryParams.endDate = this.timeRange[1];
      } else {
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
      }
    },
    getAllCompany() {
      allList().then(res => this.companyList = res.rows);
    },
    getList() {
      this.loading = true;
      listCourseTrafficLog(this.queryParams).then(res => {
        this.courseTrafficLogList = res.rows;
        this.total = res.total;
      }).finally(() => {
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.tabType = this.activeTab
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.timeRange = null;
      this.queryParams = {
        ...this.queryParams,
        startDate: null,
        endDate: null,
        companyId: null,
        project: null,
        courseId: null,
        pageNum: 1,
      };
      this.getList();
    },
    formatTrafficData(traffic) {
      return `${(traffic / (1024 ** 3)).toFixed(4)} GB`;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logId);
    },
    handleExport() {
      this.$confirm("确认导出数据?", "提示").then(() => {
        this.exportLoading = true;
        return exportCourseTrafficLog(this.queryParams);
      }).then(res => {
        this.download(res.msg);
      }).finally(() => {
        this.exportLoading = false;
      });
    },
  }
};
</script>
