<template>
  <div class='container'>
    <el-form :inline="true"
             v-model="topForm">

        <el-form-item label="分部">
            <el-select v-model="topForm.team" @change="handleItemChange"  placeholder="请选择分部名称">
                <el-option v-for='(item,index) in brancheList'
                        :key='index'
                        :label="item.label"
                        :value="item.value"></el-option>
            </el-select>
            <!-- <el-select v-model="topForm.instruments"  placeholder="请选择乐团名称">
                <el-option v-for='(item,index) in instrumentList'
                        :key='index'
                        :label="item.label"
                        :value="item.value"></el-option>
            </el-select> -->
        </el-form-item>

      <el-form-item label="支付时间">
        <el-date-picker
            v-model="paymentTime"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
        </el-date-picker>
      </el-form-item>
      <el-button type="primary"
                 icon="el-icon-search"
                 plain
                 @click="getstudentList">搜索</el-button>
      <el-button type="success"
                 icon="el-icon-refresh"
                 plain
                 @click="resetStudentList">重置</el-button>
      <el-button plain
                 @click="exportis">导出</el-button>
      <br />
        <p>
            <span style="padding-right: 12px;">总金额：{{ amountAll.amount }}元</span>
            <span style="padding-right: 12px;">课程：{{ amountAll.tuiFeeAmount }}元</span>
            <span style="padding-right: 12px;">商品：{{ amountAll.goodsFeeAmount }}元</span>
            <span style="padding-right: 12px;">教辅：{{ amountAll.sdFeeAmount }}元</span>
            <span style="padding-right: 12px;">手续费：{{ amountAll.commissionAmount }}元</span>
            <span style="padding-right: 12px;">实际到账：{{ (parseFloat(amountAll.amount) - parseFloat(amountAll.commissionAmount)).toFixed(2) }}元</span>
        </p>
    </el-form>
    <div class="tableWrap">
        <!-- height="calc(100vh - 174px)"
                show-summary
                :summary-method="getSummaries" -->
      <el-table :data='tableList'
                id='tableid'>
        <el-table-column type="index"
                           width="55"></el-table-column>
        <el-table-column align="center"
                         label="学生姓名"
                         prop='userName'></el-table-column>
        <el-table-column align="center"
                         label="订单编号"
                         width="200"
                         prop='orderNo'></el-table-column>
        <el-table-column align="center"
                         label="收款账户"
                         prop='account'></el-table-column>
        <el-table-column align="center"
                         label="支付金额"
                         prop='amount'></el-table-column>
        <el-table-column align="center"
                         label="到账时间"
                         prop='payTime'></el-table-column>
        <el-table-column align="center"
                         label="课程费用"
                         prop='tuiFee'></el-table-column>
        <el-table-column align="center"
                         label="商品"
                         prop="goodsFee"></el-table-column>
        <el-table-column align="center"
                         label="教辅费用"
                         prop="sdFee"></el-table-column>
        <el-table-column align="center"
                         label="手续费"
                         prop="commission"></el-table-column>
        <el-table-column align="center"
                         label="专业"
                         prop="voicyPart"></el-table-column>
        <el-table-column align="center"
                         label="分部"
                         prop="branchName"></el-table-column>
        <el-table-column align="left"
                         label="单位/学校"
                         prop="poName"></el-table-column>
        <el-table-column align="left"
                         label="备注"
                         width="300"
                         :formatter="filterRemark">
        </el-table-column>
      </el-table>
      <div class="paginationWrap">
      <el-pagination background
                       class="pagination"
                       layout="prev, pager, next"
                       :total="total"
                       :current-page.sync="currentPage"
                       :page-size.sync="rows"
                       @current-change="handleCurrentChange"></el-pagination>
      </div>

    </div>
  </div>
</template>
<script>
import { getBranches, orderListPage, getMusicTeams } from "@/api/table";
import qs from "qs";
import { scrollTo } from '@/utils/scroll-to'
export default {
  data () {
    return {
        pickerOptions: {
            shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                }
            }, {
                text: '最近一个月',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                }
            }, {
                text: '最近三个月',
                onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                }
            }]
        },
        paymentTime: '',
        topForm: {},
        tableList: [],
        rows: 20,
        total: 0,
        page: 1,
        brancheList: [],// 分部列表
        instrumentList: [], // 乐团列表
        idTmr: '',
        tableId: '',
        props: {
            value: 'value',
            label: 'label',
            children: 'children'
        },//cascader 数据格式化
        branchId: '',
        classId: '',
        account: this.$route.query.account, // 财务唯一标识
        amountAll: {
            amoun: 0,
            tuiFeeAmount: 0,
            goodsFeeAmount: 0,
            sdFeeAmount: 0,
            commissionAmount: 0,
        }, // 金额集合
    }
  },
  computed: {
    currentPage: {
      get () {
        return this.page
      },
      set (val) {
        this.$emit('update:page', val)
      }
    },
  },
  mounted() {
      if(this.account) {
        this.getBranches();
        this.getstudentList()
    }
  },
  methods: {
    handleCurrentChange (val) {
      this.page = val;
    //   this.rows = pageSize;
      this.getstudentList();
    },
    // 获取选项卡
    getBranches () {
      getBranches().then(res => {
        if (res.code == 200) {
          let arr = [];
          res.data.map(item => {
            arr.push({
              value: item.branchId,
              label: item.branchName,
              children: []
            })
          })
          this.brancheList = arr
        }
      });
    },
    getstudentList (rows, callBack) {
        if(!this.account) {
            this.$message.error('您没有权限')
            return false
        }
        if(this.account != 'per' && this.account != 'com') {
            this.$message.error('您没有权限')
            return false
        }
        if(rows && typeof rows == 'number' ) {
            this.rows = rows
        } else {
            this.rows = 20
        }
        let startTime = '', endTime = ''
        if(this.paymentTime) {
            startTime = this.paymentTime[0]
            endTime = this.paymentTime[1]
        }
        let params = this.topForm
        orderListPage(qs.stringify({ 
            account: this.account,
            page: this.page,
            rows: this.rows,
            branchId: params.team, 
            classId: params.instruments, 
            type: params.money,
            startTime: startTime,
            endTime: endTime})).then(res => {
              let data = res.data
              this.tableList = data.rows;
              this.total = data.total;
              this.amountAll = {
                amount: data.amount,
                tuiFeeAmount: data.tuiFeeAmount,
                goodsFeeAmount: data.goodsFeeAmount,
                sdFeeAmount: data.sdFeeAmount,
                commissionAmount: data.commissionAmount
              }
            // 回调函数
            if(callBack && typeof callBack == 'function') {
                callBack()
            }
        })
    },
    resetStudentList () {
      this.branchId = "";
      this.classId = '';
      this.topForm.money = "";
      this.topForm.team = '';
      this.topForm.instruments = '';
      this.page = 1;
      this.getstudentList();
    },
    filterRemark (val) {
      let remark = val.remark ? val.remark : '';
      let sdName = val.sdName ? val.sdName : '';
      return remark + ' ' + sdName;
    },
    exportis () {
        //   this.topForm.money = "";
        //   this.topForm.team = '';
        //   this.topForm.instruments = '';
        this.rows = 9999
        this.page = 1
        this.getstudentList(9999, () => {
              setTimeout(() => {
                  this.method5('tableid');
              }, 100);
        })
        // this.method5('tableid');
    },

    // 导出
    getExplorer () {
      var explorer = window.navigator.userAgent;
      //ie
      if (explorer.indexOf("MSIE") >= 0) {
        return 'ie';
      }
      //firefox
      else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
      }
      //Chrome
      else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
      }
      //Opera
      else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
      }
      //Safari
      else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
      }
    },
    method5 (tableid) {

      if (this.getExplorer() == 'ie') {
        var curTbl = document.getElementById(tableid);
        var oXL = new ActiveXObject("Excel.Application");
        var oWB = oXL.Workbooks.Add();
        var xlsheet = oWB.Worksheets(1);
        var sel = document.body.createTextRange();
        sel.moveToElementText(curTbl);
        sel.select();
        sel.execCommand("Copy");
        xlsheet.Paste();
        oXL.Visible = true;
        try {

          var fname = oXL.Application.GetSaveAsFilename("哈哈哈.xls", "Excel Spreadsheets (*.xls), *.xls");
        } catch (e) {
          print("Nested catch caught " + e);
        } finally {
          oWB.SaveAs(fname);
          oWB.Close(savechanges = false);
          oXL.Quit();
          oXL = null;
          this.idTmr = window.setInterval("Cleanup();", 1);
        }

      }
      else {
        this.tableToExcel();
      }
    },
    Cleanup () {
      window.clearInterval(this.idTmr);
      this.CollectGarbage();
    },
    tableToExcel () {

      (function () {
        var uri = 'data:application/vnd.ms-excel;base64,',
          template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
          base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
          format = function (s, c) {
            return s.replace(/{(\w+)}/g,
              function (m, p) { return c[p]; })          }
        // table name
        let table = document.getElementById('tableid')
        // || name
        var ctx = { worksheet: 'Worksheet', table: table.innerHTML }
        window.location.href = uri + base64(format(template, ctx))
        // 
        // return function () {


        // }
      })()
    },
    // 多选框选项卡
    handleItemChange (val) {
        // 发请求 获取分部下的乐团
        if (!val) {
            return false
        }
        // getMusicTeams(qs.stringify({ branchId: val })).then(res => {
        //     this.topForm.instruments = ''
        //     if (res.code == 200) {
        //         let arr = [];
        //         res.data.rows.map(item => {
        //             arr.push({
        //                 label: item.name,
        //                 value: item.id
        //             })
        //         })
        //         this.instrumentList = arr
        //         for (let item in this.brancheList) {
        //             if (this.brancheList[item].value == val) {
        //                 this.brancheList[item].children = arr;
        //             }
        //         }
        //     }

        // })
    },
    handleChange (val) {
      if (val) {
        this.branchId = val[0];
        this.classId = val[1];
      }
    },

    getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
            if (index === 0) {
                sums[index] = '总价';
                return;
            }
            if(index === 2 || index === 3 || index === 9 || index === 10) {
                sums[index] = 'N/A'
                return
            }
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    let temp
                    if (!isNaN(value)) {
                        temp = parseFloat(prev) + parseFloat(curr);
                    } else {
                        temp = prev;
                    }
                    return parseFloat(temp).toFixed(2)
                }, 0);
                sums[index] += ' 元';
            } else {
                sums[index] = 'N/A';
            }
        });

        return sums;
    }
  }
}
</script>
<style lang="scss">
.container {
  padding: 30px;
  .paginationWrap {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }
  .pagination {
    margin-top: 20px;
  }
}
</style>