<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" align="center"></el-table-column>
      <el-table-column prop="settleNo" label="结算单号" min-width="140" align="center" />
      <el-table-column prop="brokerageUserRealName" :label="type === 1 ? '分销员' : '分销商'" min-width="130" align="center" v-if="type === 1 || type === 2" />
      <el-table-column prop="brokerageUserOrg" label="所属企业" min-width="130" align="center" v-if="type === 1" />
      <el-table-column prop="channelName" label="渠道商" min-width="130" align="center" v-if="type === 3" />
      <el-table-column prop="departmentMemberName" label="部门成员" min-width="130" align="center" v-if="type === 5" />
      <el-table-column prop="departmentName" :label="type === 4 ? '部门名称' : '所属部门'" min-width="130" align="center" v-if="type === 4 || type === 5" />
      <el-table-column prop="billPeriod" label="账期" min-width="130" align="center" />
      <el-table-column prop="reportCount" label="结算数量(条)" min-width="100" align="center" />
      <el-table-column prop="totalPrice" 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 ? '待结算' : '已结算' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="brokerageSettledPrice" label="已结算佣金金额" min-width="140" align="center" />
        <el-table-column prop="brokerageNotSettledPrice" label="未结算佣金金额" min-width="140" align="center" />



      <el-table-column label="支付方式" min-width="130" align="center" v-if="tabActive == 1">
        <template slot-scope="scope">
          <span>{{
            scope.row.payWay === 1 ? '线下结算' :
            scope.row.payWay === 2 ? '企业钱包结算' : '第三方支付结算'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发票/结算凭证" min-width="130" align="center" v-if="tabActive == 1 || type >= 2">
        <template slot-scope="scope">
          <span>{{ scope.row.uploadAttachments === 1 ? '已上传' : '未上传' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算单生成时间" min-width="130" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="settleTime" label="结算时间" min-width="130" align="center" v-if="tabActive == 1" />
      <el-table-column label="操作" min-width="150" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button v-if="tabActive == 0" type="text" size="small"
            :disabled="bcxId" @click="openSettleDialog(scope.row)">
            确认结算
          </el-button>
          <span v-if="tabActive == 0">|</span>
          <el-button type="text" size="small"
            @click="openUploadVoucherDialog(scope.row.id)">
            上传凭证
          </el-button>
          <span>|</span>
          <el-button type="text" size="small"
            @click="navigateToSettleDetail(scope.row.id, scope.row.settleStatus)">
            账单详情
          </el-button>
          <span>|</span>
          <el-button type="text" size="small"
            @click="exportDetail(scope.row.id)">
            导出明细
          </el-button>
          <span v-if="tabActive == 0">|</span>
          <el-button type="text" size="small" class="mr10"
            v-if="tabActive == 0" @click="revoke(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" />
    <UploadVoucherDialog :showUploadVoucherDialog="showUploadVoucherDialog" :settleId="settleId" @closeUploadVoucherDialog="closeUploadVoucherDialog" />
  </div>
</template>

<script>
  import { batchExporSettltApi, batchExporBilltApi, revokeApi } from '@/api/distribution';
  import SettleDialog from './settleDialog.vue';
  import UploadVoucherDialog from './uploadVoucherDialog.vue';

  export default {
    components: { SettleDialog, UploadVoucherDialog },
    props: [
      'listLoading', 'billList', 'limit', 'total', 'page', 'tabActive', 'type',
      'searchInfo', 'bcxId', 'totalBrokeragePrice', 'totalCount', 'totalPayPrice'
    ],
    data() {
      return {
        showSettleDialog: false,
        showUploadVoucherDialog: false,
        settleId: null, // 上传凭证使用
        checkList: []
      };
    },
    watch: {
      tabActive(newVal) {
        console.info('/tabActive', newVal);
      }
    },
    methods: {
      batchSettleBill() {
        if (!this.checkList.length) {
          this.$message({
            message: '至少选中一条记录',
            type: 'warning',
            showClose: true
          });
          return;
        }
        this.showSettleDialog = true;
      },
      batchExport() {
        let params = {
          settleStatus: this.tabActive == 0 ? 1 : 2,
          bcxId: this.bcxId ? this.bcxId : null,
          billPeriodStart: this.searchInfo.billPeriodStart ? this.searchInfo.billPeriodStart : null,
          billPeriodEnd: this.searchInfo.billPeriodEnd ? this.searchInfo.billPeriodEnd : null,
          dateLimit: this.searchInfo.dateLimit,
          name: this.searchInfo.name,
          settleNo: this.searchInfo.settleNo,
          uploadAttachments: this.searchInfo.uploadAttachments,
        };
        batchExporSettltApi(this.type, 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对象
        });
      },
      selectOptions(selection) {
        this.checkList = selection;
      },
      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;
      },
      openUploadVoucherDialog(id) {
        this.settleId = id;
        this.showUploadVoucherDialog = true;
      },
      navigateToSettleDetail(id, settleStatus) {
        this.$router.push({
          path: '/distribution/settlementBill/settleBillDetail',
          query: {
            id,
            settleStatus,
            bcxId: this.bcxId,
            type: this.type
          }
        });
      },
      exportDetail(settleBillId) {
        let params = {
          settleBillId
        };
        batchExporBilltApi(this.type, 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(() => {});
      },
      revoke(id) {
        let params = {
          id
        };
        this.$confirm('结算单撤销后，各订单将会流转至业绩账单中，您可以再次生成对应的结算单', '撤销提醒', {
          confirmButtonText: '确定撤销',
          cancelButtonText: '取消'
        }).then(() => {
          revokeApi(params).then(() => {
            this.$message({
              message: '撤销成功',
              type: 'success',
              showClose: true
            });
            this.$emit('updateList');
          }).catch(() => {});
        }).catch(() => {});
      },
      handleSizeChange(val) {
        this.$emit('handleSizeChange', val);
      },
      pageChange(page) {
        this.$emit('pageChange', page);
      },
      closeSettleDialog(type) {
        if (type) {
          this.$emit('updateList');
        }
        this.showSettleDialog = false;
      },
      closeUploadVoucherDialog() {
        this.showUploadVoucherDialog = false;
      }
    },
  }
</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>
