<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="公司名称" prop="companyId" >-->
<!--        <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="项目" prop="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="课程" prop="courseId">-->
<!--        <el-select filterable  v-model="queryParams.courseId" placeholder="请选择课程"  clearable size="small" @change="courseChange(queryParams.courseId)">-->
<!--          <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="年月" prop="time">
        <el-date-picker
          v-model="time"
          type="daterange"
          placeholder="选择年月"
          :picker-options="pickerOptions"
          :value-format="'yyyy-MM-dd'"
          @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-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"
          v-hasPermi="['course:courseTrafficLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <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="projectName" />
      <el-table-column label="日期" align="center" prop="month" />
      <el-table-column label="使用流量" align="center" prop="totalInternetTraffic">
        <template slot-scope="scope">
          <span>{{ formatTrafficData(scope.row.totalInternetTraffic) }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="费用" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ formatTrafficMoney(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, getCourseTrafficLog, delCourseTrafficLog, addCourseTrafficLog, updateCourseTrafficLog, exportCourseTrafficLog } from "@/api/course/courseTrafficLog";
import {courseList} from "@/api/course/courseRedPacketLog";
import {allList}from "@/api/company/company";
export default {
  name: "CourseTrafficLog",
  data() {
    return {
      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]);
          }
        }]
      },
      companyList:[],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 短链课程流量记录表格数据
      courseTrafficLogList: [],
      projectOptions:[],
      courseLists:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      time: null,
      // 查询参数
      queryParams: {
        startDate: null,
        endDate: null,
        pageNum: 1,
        pageSize: 10,
        userId: null,
        videoId: null,
        qwExternalContactId: null,
        internetTraffic: null,
        qwUserId: null,
        companyUserId: null,
        companyId: null,
        courseId: null,
        tabType: 'project'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    courseList().then(response => {
      this.courseLists = response.list;
    });
    this.getDicts("sys_course_project").then(response => {
      this.projectOptions = response.data;
    });
    this.getAllCompany();

  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (column.property === 'totalInternetTraffic') {
          const values = data.map(item => Number(item.totalInternetTraffic));
          const total = values.reduce((acc, curr) => acc + curr, 0);
          sums[index] = this.formatTrafficData(total);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    handleDateData(){
      if (this.time) {
        this.queryParams.startDate = this.time[0];
        this.queryParams.endDate = this.time[1];
      } else {
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
      }
    },
    getAllCompany() {
      allList().then(response => {
        this.companyList = response.rows;
      });
    },
    formatTrafficData(traffic) {

        if (traffic < 1024) { // Less than 1 KB
          return traffic + ' B';
        } else if (traffic < 1024 * 1024) { // Less than 1 MB
          return (traffic / 1024).toFixed(2) + ' KB';
        } else if (traffic < 1024 * 1024 * 1024) { // Less than 1 GB
          return (traffic / (1024 * 1024)).toFixed(2) + ' MB';
        } else { // More than 1 GB
          return (traffic / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
        }

    },
    formatTrafficMoney(traffic){
      return (traffic / (1024 * 1024 * 1024) * 0.095).toFixed(2) + ' 元'
    },

    handleShortcut() {
      this.queryParams.time = new Date().toISOString().slice(0, 7);
    },
    /** 查询短链课程流量记录列表 */
    getList() {
      this.loading = true;
      listCourseTrafficLog(this.queryParams).then(response => {
        this.courseTrafficLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).finally(()=>{
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        logId: null,
        userId: null,
        videoId: null,
        createTime: null,
        qwExternalContactId: null,
        internetTraffic: null,
        qwUserId: null,
        companyUserId: null,
        companyId: null,
        courseId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加短链课程流量记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const logId = row.logId || this.ids
      getCourseTrafficLog(logId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改短链课程流量记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.logId != null) {
            updateCourseTrafficLog(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourseTrafficLog(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const logIds = row.logId || this.ids;
      this.$confirm('是否确认删除短链课程流量记录编号为"' + logIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCourseTrafficLog(logIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有短链课程流量记录数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCourseTrafficLog(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
