<template>
  <div class="table-comp">
    <div class="btns">
      <div class="settle-btn" @click="batchSettleBill">批量结算</div>
      <div class="export-btn" @click="batchExport">批量导出</div>
    </div>
    <div class="total-amount">总笔数：{{totalCount}}笔 | 总成交金额：{{totalPayPrice}}元 | 总佣金：{{totalBrokeragePrice}}元</div>
    <el-table v-loading="listLoading" :data="billList"
      style="width: 100%" size="mini" class="table" ref="tableComp"
      highlight-current-row @selection-change="selectOptions">
      <el-table-column type="selection" width="55" :selectable="selectable" align="center"></el-table-column>
      <el-table-column prop="departmentName" label="部门名称" min-width="130" align="center" v-if="tabActive == 0" />
      <el-table-column prop="departmentMemberName" label="部门成员" min-width="130" align="center" v-else />
      <el-table-column prop="departmentName" label="所属部门" min-width="130" align="center" v-if="tabActive != 0" />
      <el-table-column prop="billPeriod" label="账期" min-width="130" align="center" />
      <el-table-column prop="orderCount" label="订单数(笔)" min-width="100" align="center" />
      <el-table-column prop="orderTotalPrice" label="实付总金额(元)" min-width="130" align="center" />
      <el-table-column prop="brokerageTotalPrice" label="佣金总额(元)" min-width="130" align="center" />
      <el-table-column label="结算状态" min-width="100" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.settleStatus === 1 ? '待结算' :
            scope.row.settleStatus === 2 ? '部分结算' : '已结算'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="账单生成时间" min-width="130" align="center" />
      <el-table-column label="操作" min-width="150" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small"
            v-hasPermi="['*:*:*']"
            :disabled="scope.row.settleStatus === 3"
            @click="openSettleDialog(scope.row)">
            生成结算单
          </el-button>
          <span v-hasPermi="['*:*:*']">|</span>
          <el-button type="text" size="small"
            @click="navigateToSettleDetail(scope.row.id)">
            账单详情
          </el-button>
          <span v-hasPermi="['*:*:*']">|</span>
          <el-button type="text" size="small" class="mr10"
            v-hasPermi="['*:*:*']"
            @click="exportDetail(scope.row.id)">
            导出明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination :page-sizes="[20, 40, 60, 80]" :page-size="limit"
        :current-page="page" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="pageChange" />
    </div>
    <settleDialog :showSettleDialog="showSettleDialog" :checkList="checkList"
      @closeSettleDialog="closeSettleDialog" @updateList="updateList" />
  </div>
</template>

<script>
  import { batchExporBilltApi, batchExportApi } from '@/api/distribution';
  import settleDialog from './settleDialog.vue';

  export default {
    components: { settleDialog },
    props: [
      'listLoading', 'billList', 'tabActive', 'limit', 'total', 'page', 'tabActive',
      'searchInfo', 'bcxId', 'totalBrokeragePrice', 'totalCount', 'totalPayPrice'
    ],
    data() {
      return {
        showSettleDialog: false,
        checkList: []
      };
    },
    methods: {
      batchSettleBill() {
        if (!this.checkList.length) {
          this.$message({
            message: '至少选中一条记录',
            type: 'warning',
            showClose: true
          });
          return;
        }
        this.showSettleDialog = true;
      },
      batchExport() {
        let ids = [];
        if (this.checkList.length) {
          this.checkList.forEach(el => {
            ids.push(el.id);
          });
        }
        let params = {
          bcxId: this.bcxId ? this.bcxId : null,
          billPeriodStart: this.searchInfo.billPeriodStart ? this.searchInfo.billPeriodStart : null,
          billPeriodEnd: this.searchInfo.billPeriodEnd ? this.searchInfo.billPeriodEnd : null,
          settleStatus: this.searchInfo.settleStatus,
          name: this.searchInfo.name,
        };
        let num = this.tabActive == 0 ? 4 : 5;
        batchExporBilltApi(num, params).then(res => {
          let fileName = decodeURIComponent(res.headers["content-disposition"].split("=")[1])
          let url = window.URL.createObjectURL(new Blob([res.data], {
            type: 'application/vnd.ms-excel'
          }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName) //对文件进行命名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }).catch(() => {});
      },
      selectOptions(selection) {
        this.checkList = selection;
      },
      selectable(row) {
        return this.billList.findIndex(item => row.settleStatus === 3);
      },
      openSettleDialog(row) {
        if (this.checkList.length === 0) {
          this.checkList.push(row);
          this.$refs.tableComp.selection.push(row);
        } else if (this.checkList.length === 1) {
          if (this.checkList[0].id !== row.id) {
            this.$refs.tableComp.clearSelection();
            this.$refs.tableComp.selection.push(row);
            this.checkList = [];
            this.checkList.push(row);
          }
        } else {
          this.$refs.tableComp.clearSelection();
          this.$refs.tableComp.selection.push(row);
          this.checkList = [];
          this.checkList.push(row);
        }
        this.showSettleDialog = true;
      },
      closeSettleDialog() {
        this.showSettleDialog = false;
      },
      navigateToSettleDetail(id) {
        this.$router.push({
          path: '/distribution/performanceBill/performanceBillDetail',
          query: {
            id,
            bcxId: this.bcxId,
            type: this.tabActive == 0 ? 4 : 5
          }
        });
      },
      exportDetail(settleBillId) {
        let params = {
          settleBillId
        };
        let num = this.tabActive == 0 ? 4 : 5;
        batchExportApi(num, params).then(res => {
          let fileName = decodeURIComponent(res.headers["content-disposition"].split("=")[1])
          let url = window.URL.createObjectURL(new Blob([res.data], {
            type: 'application/vnd.ms-excel'
          }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName) //对文件进行命名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }).then(() => {});
      },
      handleSizeChange(val) {
        this.$emit('handleSizeChange', val)
      },
      pageChange(page) {
        this.$emit('pageChange', page);
      },
      updateList() {
        this.$emit("updateList");
      }
    }
  }
</script>

<style lang="scss" scoped>
  .table-comp {
    .btns {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-bottom: 20px;
      margin-top: 10px;

      .settle-btn {
        width: 100px;
        height: 30px;
        background-color: #409eff;
        border-radius: 5px;
        box-sizing: border-box;
        font-size: 12px;
        color: white;
        text-align: center;
        line-height: 30px;
      }

      .export-btn {
        width: 100px;
        height: 30px;
        border-radius: 5px;
        border: 1px solid #CCCCCC;
        box-sizing: border-box;
        font-size: 12px;
        color: #333333;
        text-align: center;
        line-height: 30px;
        margin-left: 15px;
      }
    }
  }

  .total-amount {
    margin-bottom: 20px;
    font-size: 16px;
  }
</style>
