<template>
  <div class="table-comp">
    <div class="btns">
      <div class="settle-btn" @click="batchSettleBill">批量结算</div>
      <div class="export-btn" @click="batchExport">批量导出</div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="billList"
      style="width: 100%"
      size="mini"
      class="table"
      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 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
              type="text"
              size="small"
              @click="openSettleDialog(scope.row)"
              :disabled="bcxId"
              v-if="tabActive == 0"
              >确认结算</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'],

    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 ids = [];
            if (this.checkList.length) {
                this.checkList.forEach(el => {
                    ids.push(el.id);
                });
            }

            let params = {};
            this.searchInfo.billPeriodStart ? params.billPeriodStart = this.searchInfo.billPeriodStart : null;
            this.searchInfo.billPeriodEnd ? params.billPeriodEnd = this.searchInfo.billPeriodEnd : null;
            this.searchInfo.dateLimit ? params.dateLimit = this.searchInfo.dateLimit : null;
            this.searchInfo.name ? params.name = this.searchInfo.name : null;
            this.searchInfo.uploadAttachments > 0 ? params.uploadAttachments = this.searchInfo.uploadAttachments : null
            this.tabActive == 0 ? params.settleStatus = 1 : params.settleStatus = 2;

            batchExporSettltApi(this.type, params).then(res => {
                const blob = new Blob([res], {
                    type: 'application/vnd.ms-excel;charset=utf-8'
                });
                const a = document.createElement('a');
                const href = window.URL.createObjectURL(blob);
                a.href = href;
                a.download = localStorage.getItem('filename');
                localStorage.removeItem('filename');
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(href);
            }).catch(() => { });
        },

        selectOptions(selection) {
            this.checkList = selection;
        },

        openSettleDialog(row) {
          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 => {
                const blob = new Blob([res], {
                    type: 'application/vnd.ms-excel;charset=utf-8'
                });
                const a = document.createElement('a');
                const href = window.URL.createObjectURL(blob);
                a.href = href;
                a.download = localStorage.getItem('filename');
                localStorage.removeItem('filename');
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(href);
            }).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;
    }
  }
}
</style>