<template>
  <div class="el-container-md">
    <!-- 筛选条件区域 -->
    <el-form :model="queryParams" class="live-data-css" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="公司名" prop="companyIds">
        <div class="company-select-wrapper">
          <el-select
            filterable
            multiple
            collapse-tags
            v-model="queryParams.companyIds"
            placeholder="请选择公司（可多选）"
            @change="getList"
            clearable
            size="small"
            style="min-width: 280px;"
          >
            <el-option
              v-for="item in companys"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
          <el-button type="text" size="mini" @click="selectAllCompany">全选</el-button>
          <el-button type="text" size="mini" @click="invertSelectCompany">反选</el-button>
        </div>
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          value-format="yyyy-MM-dd"
        ></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>

    <!-- 操作工具栏 -->
    <div class="selection-toolbar">
      <el-button plain type="primary" size="mini" icon="el-icon-download" :loading="exportLoading" @click="handleExport">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      ref="dataTable"
      :data="dataList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="companyName" label="分公司名称" min-width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="totalAttendanceCount" label="总到课人数(去重)" width="140" align="center">
        <template slot-scope="scope">{{ scope.row.totalAttendanceCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="totalCompleteCount" label="总完课人数(去重)" width="110" align="center">
        <template slot-scope="scope">{{ scope.row.totalCompleteCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="totalCompleteRate" label="总完课率" width="100" align="center">
        <template slot-scope="scope">{{ formatPercent(scope.row.totalCompleteRate) }}</template>
      </el-table-column>
      <el-table-column prop="liveAttendanceCount" label="直播课人数(去重)" width="140" align="center">
        <template slot-scope="scope">{{ scope.row.liveAttendanceCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="liveCompleteCount" label="直播完课人数(去重)" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.liveCompleteCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="liveCompleteRate" label="直播完课率" width="110" align="center">
        <template slot-scope="scope">{{ formatPercent(scope.row.liveCompleteRate) }}</template>
      </el-table-column>
      <el-table-column prop="replayAttendanceCount" label="回放课人数(去重)" width="140" align="center">
        <template slot-scope="scope">{{ scope.row.replayAttendanceCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="replayCompleteCount" label="回放完课人数(去重)" width="150" align="center">
        <template slot-scope="scope">{{ scope.row.replayCompleteCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="replayCompleteRate" label="回放完课率" width="110" align="center">
        <template slot-scope="scope">{{ formatPercent(scope.row.replayCompleteRate) }}</template>
      </el-table-column>
      <el-table-column prop="gmv" label="GMV" width="120" align="center">
        <template slot-scope="scope">{{ formatMoney(scope.row.gmv) }}</template>
      </el-table-column>
      <el-table-column prop="orderCount" label="订单数" width="90" align="center">
        <template slot-scope="scope">{{ scope.row.orderCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="orderUserCount" label="下单人数" width="100" align="center">
        <template slot-scope="scope">{{ scope.row.orderUserCount || 0 }}</template>
      </el-table-column>
      <el-table-column prop="employeeCount" label="现存员工人数(去重)" width="150" align="center">
        <template slot-scope="scope">{{ scope.row.employeeCount || 0 }}</template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      style="margin-top: 20px;"
    />
  </div>
</template>

<script>
import { listLiveDataCompany, exportLiveDataCompany } from "@/api/live/liveData";
import {getCompanyList} from "@/api/company/company";

export default {
  name: "LiveDataCompany",
  data() {
    return {
      loading: true,
      exportLoading: false,
      showSearch: true,
      dataList: [],
      companys: [],
      total: 0,
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        companyIds: [],
        startDate: null,
        endDate: null
      }
    };
  },
  created() {
    this.getList();
    getCompanyList().then(response => {
      this.companys = response.data || []
    }).catch(error => {
      console.error('获取公司列表失败:', error)
      this.companys = []
    })
  },
  methods: {
    /** 获取列表数据 */
    getList() {
      this.loading = true;
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startDate = this.dateRange[0];
        this.queryParams.endDate = this.dateRange[1];
      } else {
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
      }
      listLiveDataCompany(this.queryParams).then(response => {
        if (response.code === 200) {
          this.dataList = response.rows || [];
          this.total = response.total || 0;
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 验证公司ID不能为空
      if (!this.queryParams.companyIds || this.queryParams.companyIds.length === 0) {
        this.$message.warning('请选择公司');
        return;
      }

      // 验证时间范围不能为空
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning('请选择时间范围');
        return;
      }

      // 验证时间范围不能超过31天
      const startDate = new Date(this.dateRange[0]);
      const endDate = new Date(this.dateRange[1]);
      const diffTime = Math.abs(endDate - startDate);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      if (diffDays > 31) {
        this.$message.warning('时间范围不能超过31天');
        return;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.companyName = null;
      this.queryParams.companyIds = [];
      this.queryParams.startDate = null;
      this.queryParams.endDate = null;
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    /** 全选公司 */
    selectAllCompany() {
      this.queryParams.companyIds = this.companys.map(c => c.companyId);
      this.getList();
    },
    /** 反选公司 */
    invertSelectCompany() {
      const selected = new Set(this.queryParams.companyIds || []);
      this.queryParams.companyIds = this.companys
        .filter(c => !selected.has(c.companyId))
        .map(c => c.companyId);
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startDate = this.dateRange[0];
        this.queryParams.endDate = this.dateRange[1];
      } else {
        this.queryParams.startDate = null;
        this.queryParams.endDate = null;
      }
      this.$confirm('是否确认导出分公司直播数据统计?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        const exportParam = { ...this.queryParams };
        delete exportParam.pageNum;
        delete exportParam.pageSize;
        return exportLiveDataCompany(exportParam);
      }).then(response => {
        if (response.code === 200) {
          this.download(response.msg);
        }
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    },
    formatPercent(value) {
      const num = Number(value || 0);
      return `${num.toFixed(2)}%`;
    },
    formatMoney(value) {
      const num = Number(value || 0);
      return `¥${num.toFixed(2)}`;
    }
  }
};
</script>

<style scoped>
.selection-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-left: 10px;
}

.live-data-css {
  padding-left: 10px;
  padding-top: 30px;
}

.company-select-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
