<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司" prop="companyId">
        <select-tree
          v-model="selectedCompanyList"
          :raw-data="deptList"
          :parentSelectable="true"
          placeholder="请选择销售"
          :multiple="true"
          component-width="300px"
          :max-display-tags="3"
          :check-strictly="false"
          :return-leaf-only="false"
          @change="handleMultiChange"
        ></select-tree>
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="SOP任务" prop="channel" label-width="70px">
        <date-range
          v-model="selectedMultipleTasks"
          :raw-data="channelList"
          placeholder="请选择多个任务"
          :parentSelectable="true"
          :multiple="true"
          component-width="300px"
          :max-display-tags="3"
          :check-strictly="false"
          :return-leaf-only="false"
          :show-node-detail="true"
        @change="handleMultiChange"
        @dateRangeChange="dateRangeChange"
        ></date-range>
      </el-form-item>
      <el-form-item label="包含未发课" label-width="120px">
        <el-checkbox v-model="queryParams.includeSend0">
        </el-checkbox>
      </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="['system:stats:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 警告提示 -->
    <el-alert
      title="待激活人数依赖进粉时的自动标记和员工手动标记是可变的，相应的目标人数和进线完播率受此影响；为了不受进粉期人数变化影响，第二天新进报名产生的观后数据不做统计；辅助工作台人数不一致可能是受进粉影响，也有可能是员工删除了好友或者取消了客户频道报名。"
      type="warning"
      :closable="false"
      show-icon
      class="mb8">
    </el-alert>

    <el-table border v-loading="loading" :data="statsList" @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries">
      <!-- 未上线部分 -->
        <el-table-column prop="deptName" label="所属部门" width="180" align="center"/>
        <el-table-column prop="companyUserName" label="员工"  />
      <el-table-column prop="trainCampNum" label="营期人数"  align="center" />
      <el-table-column prop="sendNum" label="发课数"  align="center" />
      <el-table-column prop="notRegisteredNum" label="待看课"  align="center" />
      <el-table-column prop="registeredNum" label="上线数"  align="center" />
      <el-table-column prop="interruptNum" label="看课中断"  align="center" />
      <el-table-column prop="completedNum" label="已完课"  align="center" />
      <el-table-column prop="qwRepeatNum" label="企微重粉"  align="center" >
        <template slot-scope="scope">
          <span>{{scope.row.qwRepeatNum || 0}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userRepeatNum" label="看课重粉(小程序)"  align="center" >
        <template slot-scope="scope">
          <span>{{scope.row.userRepeatNum || 0}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="regRate" label="上线率" align="center">
        <template slot-scope="scope">
          <span v-if="typeof scope.row.regRate === 'number'">
            {{ (scope.row.regRate * 100).toFixed(2) }}%
          </span>
          <span v-else>
            0.00%
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="finishedRate" label="完课率" align="center">
        <template slot-scope="scope">
          <span v-if="typeof scope.row.finishedRate === 'number'">
            {{ (scope.row.finishedRate * 100).toFixed(2) }}%
          </span>
          <span v-else>
            0.00%
          </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 {
  listEmployeeStats,
  getEmployeeList,
  getChannelList,
  exportEmployeeStats,
  getSOPTaskData,
  getDeptData,
  exportSellerData
} from '@/api/system/employeeStats'
import {getCompanyList} from "@/api/company/company";
import {getUserList} from "@/api/company/companyUser";
import SelectTree from "@/components/TreeSelect/index.vue";
import dateRange from '@/components/TreeSelect/dateRange.vue'

export default {
  name: "EmployeeStats",
  components: {SelectTree,dateRange},
  data() {
    return {
      // 遮罩层
      loading: true,
      companys:[],
      selectedMultipleTasks: [],
      selectedCompanyList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工统计表格数据
      statsList: [],
      // 员工列表
      employeeList: [],
      companyUserList: [],
      // 频道列表
      channelList: [],
      // 日期范围
      dateRange: [],
      deptList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channel: null,
        startDate: null,
        endDate: null,
        companyId: null,
        periodList: [],
        // 包含未发课数
        includeSend0: false
      },
      // 总体统计
      totalStats: {
        totalEmployees: 0,
        onlineEmployees: 0,
        offlineEmployees: 0,
        completionRate: '0.00'
      }
    };
  },
  created() {
    this.getList();

    // getCompanyList().then(response => {
    //   this.companys = response.data;
    // });

    getSOPTaskData({}).then(response => {
      this.channelList = response.data;
    });

    getDeptData().then(response => {
      this.deptList = response.data;
    })
  },
  methods: {
    dateRangeChange(e){
      getSOPTaskData({
        startDate: e[0],
        endDate: e[1]
      }).then(response => {
        this.channelList = response.data;
      });
    },
    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 (['trainCampNum', 'sendNum', 'notRegisteredNum', 'registeredNum', 'interruptNum', 'completedNum', 'qwRepeatNum', 'userRepeatNum'].includes(column.property)) {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = 'N/A';
          }
        }
        else if (column.property === 'regRate') {
          const totalRegistered = data.reduce((sum, item) => sum + (Number(item.registeredNum) || 0), 0);
          const totalSendNum = data.reduce((sum, item) => sum + (Number(item.sendNum) || 0), 0);

          if (totalSendNum > 0) {
            const rate = (totalRegistered / totalSendNum * 100).toFixed(2);
            sums[index] = `${rate}%`;
          } else {
            sums[index] = '0.00%';
          }
        }
        else if (column.property === 'finishedRate') {
          const totalCompleted = data.reduce((sum, item) => sum + (Number(item.completedNum) || 0), 0);
          const totalSendNum = data.reduce((sum, item) => sum + (Number(item.sendNum) || 0), 0);

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

      return sums;
    },
    handleCompanyUserId(val){
      if(val == null || val === '') {
        this.queryParams.companyUserId = null;
        this.queryParams.userIds = [];
      }
    },
    handleMultiChange(e){

    },
    handleSeller(){
      if(this.queryParams.companyId != null) {
        getUserList(this.queryParams.companyId).then(res=>{
          if(res.code === 200) {
            this.companyUserList = res.data
          }
        })
      } else {
        this.queryParams.companyUserId = null;
      }
    },
    /** 查询员工统计列表 */
    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;
      }
      if(this.selectedCompanyList != null && this.selectedCompanyList.length > 0) {
        this.queryParams.userIds = this.selectedCompanyList;
      }else {
        this.queryParams.userIds = [];
      }

      listEmployeeStats(this.queryParams).then(response => {
        this.statsList = response.data.list;
        this.total = response.data.total;

      }).finally(()=>{
        this.loading = false;
      })
    },
    /** 获取员工列表 */
    getEmployeeList() {
      getEmployeeList().then(response => {
        this.employeeList = response.data || [];
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.error("请选择时间范围");
        return;
      }

      if(this.selectedCompanyList == null || this.selectedCompanyList.length <= 0) {
        this.$message.error("公司为必选!");
        return;
      }
      this.queryParams.pageNum = 1;
      this.queryParams.periodList = this.selectedMultipleTasks;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.selectedMultipleTasks = [];
      this.selectedCompanyList = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.periodList = this.selectedMultipleTasks;
      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;
      }
      if(this.selectedCompanyList != null && this.selectedCompanyList.length > 0) {
        this.queryParams.userIds = this.selectedCompanyList;
      }else {
        this.queryParams.userIds = [];
      }
      const queryParams = this.queryParams;

      this.$confirm('是否确认导出当前查询数据？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportSellerData(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.stats-card {
  text-align: center;
  margin-bottom: 16px;

  .stats-number {
    font-size: 24px;
    font-weight: bold;
    color: #409EFF;

    &.online {
      color: #67C23A;
    }

    &.offline {
      color: #F56C6C;
    }

    &.rate {
      color: #E6A23C;
    }
  }
}

.mb8 {
  margin-bottom: 8px;
}

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

::v-deep .el-alert {
  margin-bottom: 16px;
}
</style>
