<template>
  <div class="commissionDetails-box">
    <div class="query-box">
      <ul>
        <li>
          <!-- <input type="button" class="normalBtn" :value="$t('visa.v_daochu')" @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

      @on-custom-comp="customCompFunc"
    ></v-table>
    <div style="height:20px;"> </div>
     <!-- @sort-change="sortChange" -->
  </div>
</template>
<script>
import moment from "moment"
import Vue from 'vue'
import XLSX from 'xlsx'
var FileSaver = require('file-saver')
export default {
  data() {
    return {
      activeName: "first",
      commonName:
 this.$t('system.query_name'),
      loading: false,
      msg: {
        pageIndex: 1,
        pageSize: 20,
        ParentId: 0,
        OrderStr: "RB_Branch_Id asc",
        BName:-1
      },
      total: 0,
      currentPage: 1,
      columns: [],
      remoteLoading: false,
      total: 0,
      dataList: [],
      isReady: false,
      multipleSort: false,
      loading: true,
      CompanyList:[],
      dataListTwo: [],
      stringPerons:'',
      oPComissionPeriods:{},
    };
  },
  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: [this.$t('objFill.v101.administrative.tichengtongji')], 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.BranchName!='' && filters.BranchName!='__all__'){
        data = data.filter(item => item.BranchName.indexOf(filters.BranchName)!=-1);


      }
      if (filters.DepartmentName!=''){
        data = data.filter(item => item.DepartmentName.indexOf(filters.DepartmentName)!=-1);
      }
      if (filters.EmployeeName!=''){
        data = data.filter(item => item.EmployeeName.indexOf(filters.EmployeeName)!=-1);
      }
      if ((filters.BranchName === '' || filters.BranchName==='__all__') && filters.DepartmentName === '' && filters.EmployeeName === ''){

        data = dataListTwo
      }
      this.dataList = data
    },
    customCompFunc(params) {
      if (params.type === "see") {
        this.getInfo(params.data)
      }else{
        this.voucher(params.data)
      }
    },
    voucher(data){
      let msg={
            TemplateId:27,
            RB_Branch_Id:data.RB_Branch_Id,
            IsPublic:6,
            BType:4,
            AccountId:23,
            CostTypeID:189,
            WBMoney:data.CommissionMoney,
            Remark:'',
            TCID:0,
            IsRelevanceTravel:1,
            OrderID:0,
            vorcherInos:[],
            Description:'',
            RemitterName:'',
            TradeDate:moment().format('YYYY-MM-DD'),
            OrderSource:14,

          };
          this.$confirm(this.$t('objFill.v101.administrative.tichengjesfzq'), this.$t('tips.tips'), {
						confirmButtonText: this.$t('pub.sureBtn'),
						cancelButtonText: this.$t('pub.cancelBtn'),
						type: 'warning'
					}).then(() => {
            this.loading = true;
              this.apipost(
                "Financial_post_SetFinanceInfoCommonForIn",
                msg,
                res => {
                  this.loading = false;
                  if (res.data.resultCode == 1) {
                    this.apipost(
                    "VisaCommission_UpdatePeriodsFrID",
                    {ID:this.oPComissionPeriods.ID,FrId:res.data.data},
                    res => {
                      if (res.data.resultCode == 1) {
                        this.Success(res.data.message);
                        this.getList();
                      } else {
                        this.Error(res.data.message);
                      }
                    },
                    null
                  );
                  } else {
                    this.Error(res.data.message);
                  }
                },
                null
              );
					}).catch(() => {

					});
    },
    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;

          } else {
          }
        },
        err => {}
      );
    },
    initColums() {
      let oPComissionPeriods=this.oPComissionPeriods;
      this.isReady = false;
      let that = this;
      let companyList = [];
      this.CompanyList.forEach(x => {
        let item = {};
        item.label = x.BName;
        item.value = x.BName;
        companyList.push(item);
      });
      let company = {
        field: "BranchName",
        title: this.$t('sm.company'),
        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: this.$t('admin.admin_Department'),
        width: 80,
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        result: "",
        filterMultiple: false,
        filters: companyList,
        type: "text"
      };
      let userName = {
        field: "EmployeeName",
        title: this.$t('system.query_name'),
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        result: "",
        filterMultiple: false,
        filters: [{}],
        type: "text"
      };
      let CommissionMoney = {
        field: "CommissionMoney",
        title: this.$t('salesModule.TCmoney'),
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.CommissionMoney.toFixed(2)}</span>`
        }
      };
    let Zhanbi = {
        field: "CommissionPercent",
        title: this.$t('salesModule.ZB'),
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        formatter: function(rowData, rowIndex, pagingIndex, field) {
            return `<span>${rowData.CommissionPercent}%</span>`
        }
        };
      let remark = {
        field: "remark",
        title: this.$t('pub.pubRemark'),
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        componentName: "commission-table-beizhu"
      };
      let opera = {
        title: this.$t('system.table_operation'),
        titleAlign: "left",
        columnAlign: "left",
        width: 80,
        isResize: false,
        componentName: "commission-table-operation"
      };
      this.columns = [];
      this.columns.push(company);
      this.columns.push(department);
      this.columns.push(userName);
      this.columns.push(CommissionMoney);
    //   this.columns.push(otherMoney);
    //   this.columns.push(backMoney);
    //   this.columns.push(sumMoney);
    //   this.columns.push(peopleCount);
    //   this.columns.push(visaPeopleCount);
      this.columns.push(Zhanbi);
      this.columns.push(remark);
      this.columns.push(opera);
      this.isReady = true;
    },
    sortChange(param) {
      if(param.sumMoney==''){
        if(param.BName!=''){
          this.msg.OrderStr='RB_Branch_Id '+param.bName
        }
        if(param.commissionMoney!=''){
          this.msg.OrderStr='CommissionMoney '+param.commissionMoney
        }
        if(param.peopleCount!=''){
          this.msg.OrderStr='PeopleCount '+param.peopleCount
        }
        if(param.backMoney!=''){
          this.msg.OrderStr='BackMoney '+param.backMoney
        }
        if(param.otherMoney!=''){
          this.msg.OrderStr='OtherMoney '+param.otherMoney
        }
        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(
        "VisaCommission_GetPeriodsDetailsList",
        this.msg,
        res => {
          this.loading = false;

          if (res.data.resultCode == 1) {
            let data = res.data.data.data;
            this.oPComissionPeriods=res.data.data.oPComissionPeriods;
            data.forEach(item=>{
              item.FRID=this.oPComissionPeriods.FRID;
              item.PeriodsDate=this.oPComissionPeriods.PeriodsDate;
            })
            this.total = res.data.data.data.length;
            this.dataList = data;
            // this.dataList.forEach(x=>{
            //   x.sumMoney=x.commissionMoney+x.otherMoney-x.backMoney
            // })
            this.dataListTwo = JSON.parse(JSON.stringify(this.dataList))
            this.initColums();
          } 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) {
      this.$router.push({
        path: "ClausesOrder",
        query: {
          StartDate: item.PeriodsDate,
          blank:'y'
        }
      });
    }
  },
  mounted() {
    this.msg.pageSize = 10000; //不分页
    this.msg.ID = this.$route.query.ID;
    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());

    this.getList();
    this.getCompanyList();

  },
  created(){
    Vue.component('commission-table-beizhu',{
      template:` <span v-if="rowData.EmployeeId==0 && rowData.FRID>0">
           单据号:{{rowData.FRID}}</span>`,
      props:{

          rowData:{
              type:Object
          },
          field:{
              type:String
          },
          index:{
              type:Number
          }
      },
      created(){
      },
      methods:{
        see(){
          let params = {type:'see',data:this.rowData};
          this.$emit('on-custom-comp',params);
        },
        ZhiDan(){
          let params = {type:'zhidan',data:this.rowData};
          this.$emit('on-custom-comp',params);

        },
      }
    })
      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 v-if="rowData.EmployeeId==0 && rowData.FRID==0" type="danger" size='mini' icon="el-icon-document" circle @click="ZhiDan(rowData,index)"></el-button>
      <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);
        },
        ZhiDan(){
          let params = {type:'zhidan',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>
