<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>
    <el-dialog
      :title="`设置:${setform.CreateByStr}`"
      :visible.sync="setopVisible"
      width="30%">
      <div>
        <el-form ref="setform" :model="setform" label-width="80px">
          <el-form-item :label="$t('system.query_type')">
            <el-select v-model="setform.Type" :placeholder="$t('pub.pleaseSel')">
              <el-option label="奖励" :value="1"></el-option>
              <el-option label="扣除" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('fnc.jine')" >
            <el-input style="width:220px" @keyup.native="checkPrice(setform,'Money')" v-model="setform.Money"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="setform.Description"></el-input>
          </el-form-item>
          
    </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="setopVisible = false">{{$t('pub.cancelBtn')}}</el-button>
        <el-button size="mini" type="danger" @click=" SetOPOK">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="查看详情"
      :visible.sync="opdatails"
      width="30%">
      <div>
        <p style="text-align:center;margin-bottom:15px">{{detailsMsg.CreateByStr}}</p>
        <table class="singeRowTable" border="0" cellspacing="0" cellpadding="0" v-loading="loading">
      <tr>
        <th>类型</th>
        <th>{{$t('fnc.jine')}}</th>
        <th>描述</th>
      </tr>
      <tr v-for="(item,index) in detailsMsg.detailList" :key="index">
        <td>
          <span v-if="item.Type==1">奖励</span>
          <span v-if="item.Type==2">扣除</span>
          </td>
        <td>{{item.Money}}</td>
        <td>
          {{item.Description}}
        </td>
       
      </tr>
      <tr>
        <td v-show="detailsMsg.detailList.length==0" colspan="3" align="center">{{$t('system.content_noData')}}</td>
      </tr>
    </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="opdatails = false">{{$t('pub.cancelBtn')}}</el-button>
      </span>
    </el-dialog>
  </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,
        PeriodsId: 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:'',
      setopVisible:false,
      setform:{
        CreateByStr:'',
      },
      opdatails:false,
      detailsMsg:{
        detailList:[],
      },
      btnShow:true,
    };
  },
  
  methods: {
    SetOPOK(){
      if(!this.setform.Type){
        this.Error("请选择类型！");
        return;
      }
      if(!this.setform.Money || this.setform.Money==0){
        this.Error("请填写金额！");
        return;
      }
      if(!this.setform.Description || this.setform.Description==''){
        this.Error("请填写描述！");
        return;
      }
      this.apipost(
        "sellcommission_SetOPCommissionRewards",
        this.setform,
        res => {
          this.loading = false;
          if (res.data.resultCode == 1) {
            this.setopVisible=false;
            this.getList();
          } else {
            this.Error(res.data.message);
          }
        },
        null
      );

    },
    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.PeopleCount,
          '奖励金额':x.JLMoney,
          '扣除金额':x.KCMoney,
          '最终提成':x.LastMoney,
          '所属期数':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!='__all__'){
        data = data.filter(item => item.BName.indexOf(filters.BName)!=-1);
      }
      if (filters.DepartmentName!=''){
        data = data.filter(item => item.DepartmentName.indexOf(filters.DepartmentName)!=-1);
      }
      if (filters.CreateByStr!=''){
        data = data.filter(item => item.CreateByStr.indexOf(filters.CreateByStr)!=-1);
      }
      if ((filters.BName === '' || filters.BName==='__all__') && filters.DepartmentName === '' && filters.CreateByStr === ''){
        data = dataListTwo
      }
      this.dataList = data
    },
    customCompFunc(params) {
      if (params.type === "see") {
        this.getInfo(params.data)
      } 
      else if (params.type === "setop") {
        // 设置OP提成
        this.setopVisible=true;
        this.setform.PeriodsId=this.msg.PeriodsId;
        this.setform.EmployeeId=params.data.EmployeeId;
        this.setform.CreateByStr=params.data.CreateByStr;
      } 
      else{
        this.opdatails=true;
        this.detailsMsg.CreateByStr=params.data.CreateByStr;
        this.detailsMsg.detailList=params.data.OtherList;

        
      }
    },
    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 = [];
      this.CompanyList.forEach(x => {
        let item = {};
        item.label = x.BName;
        item.value = x.BName;
        companyList.push(item);
      });
      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: "CreateByStr",
        title: "姓名",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        result: "",
        filterMultiple: false,
        filters: [{}],
        type: "text"
      };
      let commissionMoney = {
        field: "CommissionMoney",
        title: "提成金额",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span>${rowData.CommissionMoney.toFixed(2)}</span>`
        }
      };
      let JLMoney = {
        field: "JLMoney",
        title: "奖励金额",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 70,
        type: "text"
      };
      let KCMoney = {
        field: "KCMoney",
        title: "扣除金额",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 70,
        type: "text"
      };
      let LastMoney = {
        field: "LastMoney",
        title: "最终提成",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        type: "text"
      };
      
    //   let otherMoney = {
    //     field: "otherMoney",
    //     title: "额外奖励",
    //     titleAlign: "left",
    //     columnAlign: "left",
    //     isResize: true,
    //     width: 80,
    //     orderBy: "",
    //     formatter: function(rowData, rowIndex, pagingIndex, field) {
    //       return `<span>${rowData.otherMoney.toFixed(2)}</span>`
    //     }
    //   };
    //   let backMoney = {
    //     field: "backMoney",
    //     title: "额外扣除",
    //     titleAlign: "left",
    //     columnAlign: "left",
    //     isResize: true,
    //     width: 80,
    //     orderBy: "",
    //     formatter: function(rowData, rowIndex, pagingIndex, field) {
    //       return `<span>${rowData.backMoney.toFixed(2)}</span>`
    //     }
    //   };
    //   let sumMoney = {
    //     title: "应发提成",
    //     field: "CommissionMoney",
    //     titleAlign: "left",
    //     columnAlign: "left",
    //     isResize: true,
    //     width: 80,
    //     orderBy: "",
    //     formatter: function(rowData, rowIndex, pagingIndex, field) {
    //       return `<span style='color:red'>${(rowData.CommissionMoney).toFixed(2)}</span>`
    //     }
    //   };
      let peopleCount = {
        field: "PeopleCount",
        title: "收客人数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 80,
        orderBy: "",
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          return `<span style='color:blue'>${rowData.PeopleCount}人</span>`
        }
      };
    //   let visaPeopleCount = {
    //     field: "visaPeopleCount",
    //     title: "单签证人数",
    //     titleAlign: "left",
    //     columnAlign: "left",
    //     isResize: true,
    //     width: 80,
    //     formatter: function(rowData, rowIndex, pagingIndex, field) {
    //       if(rowData.visaPeopleCount>0)
    //         return `<span style='color:orange'>${rowData.visaPeopleCount}人</span>`
    //       else
    //         return ''
    //     }
    //   };
      let periods = {
        field: "Periods",
        title: "期数",
        titleAlign: "left",
        columnAlign: "left",
        isResize: true,
        width: 70,
        formatter: function(rowData, rowIndex, pagingIndex, field) {
          if(rowData.Periods!=that.stringPerons)
            return `<div style='height:40px;line-height:40px;color:#f1f1f1;background: red;margin: 0 -10px;padding-left: 10px;'>${rowData.Periods}</div>`
          else
            return rowData.Periods
        }
      };
    //   let remark = {
    //     field: "remark",
    //     title: "备注",
    //     titleAlign: "left",
    //     columnAlign: "left",
    //     isResize: true,
    //     width: 80,
    //     formatter: function(rowData, rowIndex, pagingIndex, field) {
    //       return ``;
    //     }
    //   };
      let opera = {
        title: "操作",
        titleAlign: "left",
        columnAlign: "left",
        width: 110,
        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(JLMoney);
      this.columns.push(KCMoney);
      this.columns.push(LastMoney);
    //   this.columns.push(otherMoney);
    //   this.columns.push(backMoney);
    //   this.columns.push(sumMoney);
      this.columns.push(peopleCount);
    //   this.columns.push(visaPeopleCount);
      this.columns.push(periods);
    //   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.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(
        "sellcommission_GetOPCommissionDetailsList",
        this.msg,
        res => {
          this.loading = false;
          if (res.data.resultCode == 1) {
            this.dataList = res.data.data.pageData;
            this.total = res.data.data.count;
            this.dataList.forEach(x=>{
              x.sumMoney=x.CommissionMoney
              x.btnShow=this.btnShow;
            })
            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: "OpComPersonDetails",
        query: {
          EmployeeId: item.EmployeeId,
          PeriodsId:this.msg.PeriodsId,
          blank:'y'
        }
      });
    }
  },
  mounted() {
    
    this.msg.pageSize = 10000; //不分页
    this.msg.PeriodsId = this.$route.query.PeriodsId?this.$route.query.PeriodsId:0;
    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(){
      let userInfo = this.getLocalStorage();
      let ActionMenuCode=userInfo.ActionMenuCode;
        if(ActionMenuCode.indexOf('P_OPCommissionSend')!=-1){
          this.btnShow=true;
        }
      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>
      <el-button v-show="rowData.btnShow" type="danger" size='mini' style="font-size:10px" class="iconfont icon-nav-xitongguanli" circle @click="SetOP(rowData,index)"></el-button>
      <el-button type="danger" size='mini' style="font-size:10px" class="iconfont icon-nav-hangzheng" circle @click="SeeDetails(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);
        },
        SetOP(){
          let params = {type:'setop',data:this.rowData};
          this.$emit('on-custom-comp',params);
        },
        SeeDetails(){
          let params = {type:'SeeDetails',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>
