<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="公司名称">
        <el-select
          v-model="queryParams.companyIds"
          multiple
          placeholder="请输入公司名称搜索"
          style="width: 220px"
          clearable
          size="small"
        >
          <el-option
            v-for="item in formatterCompanyOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="操作类型">
        <el-select v-model="queryParams.operationType" placeholder="请选择操作类型" clearable size="small">
          <el-option label="充值" :value="1"></el-option>
          <el-option label="扣费" :value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="操作人员">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入操作人员"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></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"
          @click="handleExport"
          v-hasPermi="['company:trafficLog:export']"
        >导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="trafficRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="公司名称" align="center" prop="companyName" :show-overflow-tooltip="true" :formatter="companyNameFormatter"/>

      <el-table-column label="操作类型" align="center" prop="operationType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.operationType === 1 ? 'success' : 'danger'">
            {{ scope.row.operationType === 1 ? '充值' : '扣费' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="流量数量" align="center" prop="trafficAmount" >
        <template slot-scope="scope">
          <span :class="scope.row.operationType === 1 ? 'recharge' : 'deduction'">
            {{ scope.row.operationType === 1 ? '+' : '-' }}{{ formatTrafficAmount(scope.row)}}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作后余额" align="center" prop="balance" :formatter="formatBalance"/>

      <el-table-column label="操作人员" align="center" prop="userName" />

      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />

      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</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 { listTrafficLog, listTrafficLogExport } from "@/api/company/trafficLog";
import { allList } from '@/api/company/company'

export default {
  name: "CompanyTrafficLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流量记录表格数据
      trafficRecordList: [],
      // 日期范围
      dateRange: [],
      // 公司搜索相关
      companySearchLoading: false,
      companyOptions: [],
      formatterCompanyOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        companyId: null,
        companyIds: [], // 多选公司ID
        operationType: null,
        userName: null,
        createTime: null,
        createTimeStart: null,
        createTimeEnd: null
      }
    };
  },
  created() {
    this.getList();
    //初始化formatterCompanyOptions
    allList().then(e => {
      this.formatterCompanyOptions = e.rows;
    });
  },
  methods: {
    /** 查询流量记录列表 */
    getList() {
      this.loading = true;
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.createTimeStart = this.dateRange[0];
        this.queryParams.createTimeEnd = this.dateRange[1];
      } else {
        this.queryParams.createTimeStart = null;
        this.queryParams.createTimeEnd = null;
      }

      listTrafficLog(this.queryParams).then(response => {
        this.trafficRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    formatBalance(row){
      //对流量值进行判断，换算成GB或TB
      if(!row.balance){
        return "0 KB";
      }
      const absBalance = Math.abs(row.balance); // 获取绝对值
      if(absBalance < 1024){
        return row.balance + " KB";
      }
      else if(absBalance < 1024 * 1024){
        return (row.balance / 1024).toFixed(2) + " MB";
      }
      else if(absBalance < 1024 * 1024 * 1024){
        return (row.balance / (1024 * 1024)).toFixed(2) + " GB";
      }
      else{
        return (row.balance / (1024 * 1024 * 1024)).toFixed(2) + " TB";
      }
    },
    formatTrafficAmount(row){
      //对流量值进行判断，换算成GB或TB
      if(!row.trafficAmount){
        return "0 KB";
      }
      const absBalance = Math.abs(row.trafficAmount); // 获取绝对值
      if(absBalance < 1024){
        return row.trafficAmount + " KB";
      }
      else if(absBalance < 1024 * 1024){
        return (row.trafficAmount / 1024).toFixed(2) + " MB";
      }
      else if(absBalance < 1024 * 1024 * 1024){
        return (row.trafficAmount / (1024 * 1024)).toFixed(2) + " GB";
      }
      else{
        return (row.trafficAmount / (1024 * 1024 * 1024)).toFixed(2) + " TB";
      }
    },

    /** 搜索公司 */
    searchCompanies(query) {
      this.companySearchLoading = true;
      allList().then(response => {
        this.companyOptions = response.rows;
        if (query) {
          this.companyOptions = this.companyOptions.filter(item =>
            item.dictLabel.includes(query)
          );
        }
        this.companySearchLoading = false;
      }).catch(()=>{
        this.companySearchLoading = false;
      });
    },

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

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    companyNameFormatter(row){
      return this.formatterCompanyOptions.filter(item => item.dictValue === row.companyId)[0].dictLabel
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = {...this.queryParams};
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        queryParams.createTimeStart = this.dateRange[0];
        queryParams.createTimeEnd = this.dateRange[1];
      }
      this.$confirm('是否确认导出所有流量充值记录数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return listTrafficLogExport(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});

    }
  }
};
</script>

<style scoped>
.recharge {
  color: #67C23A;
  font-weight: bold;
}

.deduction {
  color: #F56C6C;
  font-weight: bold;
}

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