<template>
  <div class="commissionDetails-box">
    <!-- <div class="query-box">
      <ul>
        <li>
          <input type="button" class="normalBtn" value="导出" @click="exportExcel">
        </li>
      </ul>
    </div> -->
    <v-table
      v-if="isReady"
      is-horizontal-resize
      column-width-drag
      style="width:100%"
      :columns="columns"
      :table-data="dataList"
      :filter-method="filterMethod"
      :total="total"
      :pageSize="msg.pageSize"
      :pageIndex="msg.pageIndex"
      :handleCurrentChange="handleCurrentChange"
      :multiple-sort="multipleSort"
      :is-loading="loading"
      sort-always
      @sort-change="sortChange"
      @on-custom-comp="customCompFunc"
    ></v-table>
    <div style="height:20px;"> </div>
  </div>
</template>
<script>
import Vue from 'vue'
import XLSX from 'xlsx'
var FileSaver = require('file-saver')
export default {
  data() {
    return {
      activeName: "first",
      commonName: "姓名",
      loading: false,
      msg: {
        pageIndex: 1,
        pageSize: 20,
        ParentId: 0,
        OrderBy: "",
        BName:-1,
        EmName: '',
        Periods: '201903',
        RB_Branch_Id: -1,
        RB_Department_Id: 0,
      },
      total: 0,
      currentPage: 1,
      columns: [],
      remoteLoading: false,
      total: 0,
      dataList: [],
      isReady: false,
      multipleSort: false,
      loading: true,
      CompanyList:[],
      dataListTwo: [],
      stringPerons:'',
      periodsList: [],
    };
  },
  methods: {
    exportExcel(){
      const defaultCellStyle =  {'!cols': [{wpx: 60}, {wpx: 200}, {wpx: 60}, {wpx: 150},{wpx:60}]};
      const wopts = { bookType:'xlsx', bookSST:false, type:'binary', defaultCellStyle: defaultCellStyle, showGridLines: true};
      const wb = { SheetNames: ['提成统计'], Sheets: {}, Props: {} }; 
      let data = []
      this.dataList.forEach(x=>{
        let obj={
          '公司':x.bName,
          '部门':x.departmentName,
          '员工':x.createByStr,
          '提成金额':x.commissionMoney.toFixed(2),
          '额外奖励':x.otherMoney.toFixed(2),
          '额外扣除':x.backMoney.toFixed(2),
          '应发提成':x.sumMoney.toFixed(2),
          '收客数':x.peopleCount,
          '单签证人数':x.visaPeopleCount,
          '所属期数':x.periods
        }
        data.push(obj)
      })
      wb.Sheets['提成统计'] = XLSX.utils.json_to_sheet(data)
      
      //创建二进制对象写入转换好的字节流
      let tmpDown =  new Blob([this.s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" })
      FileSaver.saveAs(tmpDown, "提成统计.xls");
    },
    s2ab (s) {
      if (typeof ArrayBuffer !== 'undefined') {  
        var buf = new ArrayBuffer(s.length);  
        var view = new Uint8Array(buf);  
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;  
        return buf;  
      } else {  
        var buf = new Array(s.length);  
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;  
        return buf;
      }
    },
    filterMethod(filters){
      let data = JSON.parse(JSON.stringify(this.dataListTwo))
      let dataListTwo = JSON.parse(JSON.stringify(this.dataListTwo))
      if (filters.bName && filters.bName!='' && filters.bName!='__all__'){
        data = data.filter(item => item.bName && item.bName.indexOf(filters.bName)!=-1);
      }
      if (filters.departmentName && filters.departmentName!=''){
        data = data.filter(item => item.departmentName && item.departmentName.indexOf(filters.departmentName)!=-1);
      }
      if (filters.emName && filters.emName!=''){
        data = data.filter(item => item.emName.indexOf(filters.emName)!=-1);
      }
      if (filters.periods && filters.periods!='' && filters.periods!='__all__'){
        this.msg.Periods = filters.periods
        this.getList();
      } else if (!filters.bName && filters.bName==='' && filters.bName==='__all__'){
        this.msg.Periods = ''
        this.getList();
      }
      if ((filters.bName === '' || filters.bName==='__all__') && filters.departmentName === '' && filters.emName === '' && filters.periods === ''){
        data = dataListTwo
      }
      this.dataList = data
    },
    customCompFunc(params) {
      if (params.type === "see") {
        this.getInfo(params.data)
      } 
    },
    getCompanyList() {
      //获取公司列表
      this.apipost(
        "admin_get_BranchGetList",
        this.getCompanyMsg,
        res => {
          if (res.data.resultCode == 1) {
            let data = res.data.data;
            data.forEach(x => {
              x.disabled = false;
            });
            this.CompanyList = data;
            this.initColums();
          } else {
          }
        },
        err => {}
      );
    },
    initColums() {
      this.isReady = false;
      let that = this;
      let companyList = [];
      let periodsList = this.periodsList;
      this.CompanyList.forEach(x => {
        let item = {};
        item.label = x.BName;
        item.value = x.BName;
        companyList.push(item);
      });
      let ppList = [];
      this.dataList.forEach(x=>{
        ppList.push({
          label: x.emName,
          value: x.emName
        })
      })
      let company = {
        field: "bName",
        title: "公司",
        width: 40,
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        result: "",
        filterMultiple: false,
        filters: companyList,
        type: "select"
        // filterMultiple: false,
        // filters: companyList,
        // result: "",
        // type: "select",
        // orderBy: "asc"
        // isFrozen:true
      };
      let department = {
        field: "departmentName",
        title: "部门",
        width: 80,
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        result: "",
        filterMultiple: false,
        filters: companyList,
        type: "text"
      };
      let userName = {
        field: "emName",
        title: "姓名",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        result: "",
        filterMultiple: false,
        filters: ppList,
        type: "select"
      };
      let periods = {
        field: "periods",
        title: "期数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        result: "",
        filterMultiple: false,
        filters: periodsList,
        type: "select"
      };
      let rejectCount = {
        field: "rejectCount",
        title: "单据驳回次数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 100,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.rejectCount <= 0 ? '' : rowData.rejectCount}</span>`
        }
      };
      // let receivedPeopleCount = {
      //   field: "receivedPeopleCount",
      //   title: "收客总人数",
      //   titleAlign: "left",
      //   columnAlign: "left",
      //   isResize: true,
      //   width: 100,
      //   orderBy: "",
      //   formatter: function(rowData, rowIndex, pagingIndex, field) {
      //     return `<span>${rowData.receivedPeopleCount <= 0 ? '' : rowData.receivedPeopleCount}</span>`
      //   }
      // };
      // let orderCount = {
      //   field: "orderCount",
      //   title: "订单数量",
      //   titleAlign: "left",
      //   columnAlign: "left",
      //   isResize: true,
      //   width: 80,
      //   orderBy: "",
      //   formatter: function(rowData, rowIndex, pagingIndex, field) {
      //     return `<span>${rowData.orderCount <= 0 ? '' : rowData.orderCount}</span>`
      //   }
      // };
      let uncollected = {
        field: "uncollected",
        title: "未收款金额",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.uncollected <= 0 ? '' : that.moneyFormat(rowData.uncollected)}</span>`
        }
      };
      let lateCount = {
        field: "lateCount",
        title: "迟到次数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.lateCount <= 0 ? '' : rowData.lateCount}</span>`
        }
      };
      let leaveEarlyCount = {
        field: "leaveEarlyCount",
        title: "早退次数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 70,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.leaveEarlyCount <= 0 ? '' : rowData.leaveEarlyCount}</span>`
        }
      };
      let complainCount = {
        field: "complainCount",
        title: "投诉次数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.complainCount <= 0 ? '' : rowData.complainCount}</span>`
        }
      };
      let LllegalModifyRemarkCount = {
        field: "lllegalModifyRemarkCount",
        title: "结团后修改备注",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 105,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.lllegalModifyRemarkCount <= 0 ? '' : rowData.lllegalModifyRemarkCount}</span>`
        }
      };
      let AppletOrderCount = {
        field: "appletOrderCount",
        title: "报名确认单数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 95,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.appletOrderCount <= 0 ? '' : rowData.appletOrderCount}</span>`
        }
      };
      let discountPrice = {
        field: "discountPrice",
        title: "少价金额",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.discountPrice <= 0 ? '' : that.moneyFormat(rowData.discountPrice)}</span>`
        }
      };
      let shaoJian = {
        field: "shaoJian",
        title: "违反少价规定",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 95,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return ''
        }
      };
      let shenHeShiJian = {
        field: "shenHeShiJian",
        title: "违反单据审核时间",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 120,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.shenHeShiJian <= 0 ? '' : rowData.shenHeShiJian}</span>`
        }
      };
      let xiaoShouKaiTuan = {
        field: "xiaoShouKaiTuan",
        title: "销售开团",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 120,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.xiaoShouKaiTuan <= 0 && !rowData.xiaoShouKaiTuan  ? '' : rowData.xiaoShouKaiTuan}</span>`
        }
      };
      let planDmcPriceCount = {
        field: "planDmcPriceCount",
        title: "用款计划违规",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 120,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.planDmcPriceCount <= 0 && !rowData.planDmcPriceCount  ? '' : rowData.planDmcPriceCount}</span>`
        }
      };
      this.columns = [];
      this.columns.push(company);
      this.columns.push(department);
      this.columns.push(userName);
      this.columns.push(periods);
      this.columns.push(xiaoShouKaiTuan);
      this.columns.push(LllegalModifyRemarkCount);
      this.columns.push(AppletOrderCount);
      this.columns.push(shaoJian);
      this.columns.push(shenHeShiJian);
      this.columns.push(rejectCount);
      // this.columns.push(receivedPeopleCount);
      // this.columns.push(orderCount);
      this.columns.push(uncollected);
      this.columns.push(lateCount);
      this.columns.push(leaveEarlyCount);
      this.columns.push(complainCount);
      this.columns.push(discountPrice);
      this.columns.push(planDmcPriceCount)
      this.isReady = true;
    },
    sortChange(param) {
      // if(param.sumMoney==''){
        if(param.complainCount!=''){
          this.msg.OrderBy='a.ComplainCount '+param.complainCount
        }
        if(param.discountPrice!=''){
          this.msg.OrderBy='a.DiscountPrice '+param.discountPrice
        }
        if(param.shenHeShiJian!=''){
          this.msg.OrderBy='a.ShenHeShiJian '+param.shenHeShiJian
        }
        if(param.lateCount!=''){
          this.msg.OrderBy='a.LateCount '+param.lateCount
        }
        if(param.leaveEarlyCount!=''){
          this.msg.OrderBy='a.LeaveEarlyCount '+param.leaveEarlyCount
        }
        if(param.orderCount!=''){
          this.msg.OrderBy='a.OrderCount '+param.orderCount
        }
        if(param.receivedPeopleCount && param.receivedPeopleCount!=''){
          this.msg.OrderBy='a.ReceivedPeopleCount '+param.receivedPeopleCount
        }
        if(param.rejectCount!=''){
          this.msg.OrderBy='a.RejectCount '+param.rejectCount
        }
        if(param.uncollected!=''){
          this.msg.OrderBy='a.Uncollected '+param.uncollected
        }
        if(param.lllegalModifyRemarkCount!=''){
          this.msg.OrderBy='a.LllegalModifyRemarkCount '+param.lllegalModifyRemarkCount
        }
        if(param.xiaoShouKaiTuan!=''){
          this.msg.OrderBy='a.XiaoShouKaiTuan '+param.xiaoShouKaiTuan
        }
        if(param.appletOrderCount!=''){

          this.msg.OrderBy='a.AppletOrderCount '+param.appletOrderCount
        }
        if(param.planDmcPriceCount!=''){

          this.msg.OrderBy='a.PlanDmcPriceCount '+param.planDmcPriceCount
        }
        //this.tableData = this.orderBy(d, ["incomeVal"], param.income).results;
        this.getList();
      // }else{
      //   let d=JSON.parse(JSON.stringify(this.dataList))
      //   this.dataList = this.orderBy(d, ["sumMoney"], param.sumMoney).results;
      // }
    },
    handleCurrentChange(val) {
      this.msg.pageIndex = val;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.apipost(
        "user_get_assessment_simple",
        this.msg,
        res => {
          this.loading = false;
          if (res.data.resultCode == 1) {
            this.dataList = res.data.data;
            this.total = res.data.data.count;
            this.dataListTwo = JSON.parse(JSON.stringify(this.dataList))
          } else {
            this.Error(res.data.message);
          }
        },
        null
      );
    },
    //切换排序
    handleClick(tab, event) {
      if (this.activeName == "first") {
        // this.commonName='姓名'
        this.msg.OrderStr = "UserId";
      } else {
        // this.commonName='公司名'
        this.msg.OrderStr = "RB_Branch_Id";
      }
      this.getList();
    },
    //跳转
    getInfo(item) {
      var dateStr = item.periods;
      var year = dateStr.substring(0, 4);
      var month = dateStr.substring(4, 6);

      var nextMonthFirstDay = new Date(year, month, 1);

      var oneDay = 1000 * 60 * 60 * 24;
      var entDay = new Date(nextMonthFirstDay - oneDay).Format("yyyy-MM-dd");
      var startDay = year + "-" + month + "-" + "01";
      var userId = item.userId;

      this.$router.push({
        path: "enrollTotal",
        query: {
          EmployeeId: userId,
          starTime: startDay,
          endTime: entDay,
          blank:'y'
        }
      });
    }
  },
  mounted() {
    this.msg.pageSize = 10000; //不分页
    this.msg.ParentId = this.$route.query.ParentId;
    let dt=new Date()
    this.stringPerons=(dt.getMonth()==0?(dt.getFullYear()-1):dt.getFullYear())+''+(dt.getMonth().toString().length<2?'0':'')+(dt.getMonth()==0?12:dt.getMonth()+1);
    
    let cont = dt.getMonth()
    for(let i = 1; i <= (cont+1); i ++){
      let o = i < 10 ? '0'+i : i;
      this.periodsList.push({
        label: `2019${o}`,
        value: `2019${o}`,
      })
    }
    // this.msg.Periods=dt.getFullYear()+(dt.getMonth()>9?dt.getMonth():"0"+dt.getMonth())
    this.getList();
    this.getCompanyList();
  },
  created(){
    let date=new Date;
    let year=date.getFullYear(); 
    let month=date.getMonth()+1;
    month =(month<10 ? "0"+month:month); 
    let mydate = (year.toString()+month.toString());
    this.msg.Periods = mydate;
      Vue.component('commission-table-operation',{
      template:`<div style='width:80px;height:40px;background:#fff;text-align:center;position: relative;left:-5px;padding-top: 6px;padding-top:6px;'><el-button type="primary" size='mini' icon="el-icon-view" circle @click="see(rowData,index)"></el-button></div>`,
      props:{
          rowData:{
              type:Object
          },
          field:{
              type:String
          },
          index:{
              type:Number
          }
      },
      methods:{
        see(){
          let params = {type:'see',data:this.rowData};
          this.$emit('on-custom-comp',params);
        }
      }
    })
  }
  
};
</script>
<style>

.commissionDetails-box .el-button.is-circle{padding: 5px !important;}
.commissionDetails-box .v-table-body-cell span {
    display: block;
    width: 100%;
}
</style>