<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix" v-hasPermi="['platform:retail:store:people:list']">
        <div class="container">
          <el-form size="small" label-width="100px">
            <div class="time-keyword-search">
              <div>
                <el-form-item label="账期：">
                  <el-date-picker v-model="timeVal" value-format="yyyy-MM"
                    format="yyyy-MM" size="small" type="monthrange" placement="bottom-end"
                    start-placeholder="账单开始时间" end-placeholder="账单结束时间"
                    style="width: 300px" @change="onchangeTime" />
                </el-form-item>
              </div>
              <div class="keyword-search">
                <el-form-item label="结算状态">
                  <el-select v-model="searchInfo.settleStatus" @change="searchList">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option label="待结算" :value="1"></el-option>
                    <el-option label="部分结算" :value="2"></el-option>
                    <el-option label="已结算" :value="3"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="分销商名称：">
              <el-input v-model.trim="searchInfo.name" placeholder="请输入分销商名称"
                class="selWidth" size="small" clearable>
                <el-button v-hasPermi="['platform:retail:store:people:list']"
                  slot="append" icon="el-icon-search" size="small" @click="searchList" />
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="btns">
        <div class="batch-settle-btn" @click="batchSettleBill">批量结算</div>
        <div class="batch-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="selectOption">
        <el-table-column type="selection" width="55" :selectable="selectable" align="center"></el-table-column>
        <el-table-column prop="brokerageUserRealName" label="分销商" min-width="130" align="center" />
        <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="['platform:retail:store:sub:user:list']"
              :disabled="scope.row.settleStatus === 3"
              @click="openSettleDialog(scope.row)">
              生成结算单
            </el-button>
            <span>|</span>
            <el-button type="text" size="small"
              v-hasPermi="['platform:retail:store:sub:user:list']"
              @click="navigateToSettleDetail(scope.row.id)">
              账单详情
            </el-button>
            <span>|</span>
            <el-button type="text" size="small" class="mr10"
              v-hasPermi="['platform:retail:store:sub:user:list']"
              @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>
    </el-card>
    <settleDialog :showSettleDialog="showSettleDialog" :checkList="checkList" @updateList="getList" @closeSettleDialog="closeSettleDialog" />
  </div>
</template>

<script>
  // +---------------------------------------------------------------------
  // | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
  // +---------------------------------------------------------------------
  // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  // +---------------------------------------------------------------------
  // | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
  // +---------------------------------------------------------------------
  // | Author: CRMEB Team <admin@crmeb.com>
  // +---------------------------------------------------------------------
  import { companyPerformanceBillApi, generateSettleApi, batchExporBilltApi, batchExportApi, settleBillApi } from '@/api/distribution';
  import cardsData from '@/components/cards/index';
  import { checkPermi } from '@/utils/permission'; // 权限判断函数
  import settleDialog from './component/settleDialog.vue';

  export default {
    name: 'performanceCompanyBill',
    components: { cardsData, settleDialog },
    data() {
      return {
        listLoading: false,
        showSettleDialog: false,
        timeVal: [],
        billList: [],
        checkList: [],
        searchInfo: {
          name: '',
          settleStatus: null,
          billPeriodStart: '',
          billPeriodEnd: ''
        },
        limit: 20,
        page: 1,
        total: 0,
        bcxId: null,
        totalBrokeragePrice: '',
        totalCount: '',
        totalPayPrice: ''
      };
    },
    mounted() {
      if (checkPermi(['platform:retail:store:people:list'])) {
        this.getList()
      }
      this.bcxId = this.$route.query.bcxId;
    },
    methods: {
      checkPermi,
      getList() {
        this.listLoading = true;
        let params = {
          limit: this.limit,
          page: this.page,
          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,
        };
        companyPerformanceBillApi(params).then(res => {
          this.getStatistics()
          this.limit = res.limit;
          this.total = res.total;
          this.page = res.page;
          this.billList = res.list;
          this.listLoading = false;
        }).catch(() => {
          this.listLoading = false;
        })
      },
      getStatistics() {
        let params = {
          searchType: 4,
          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,
        };
        settleBillApi(params).then((res) => {
          this.totalBrokeragePrice = res.totalBrokeragePrice
          this.totalCount = res.totalCount
          this.totalPayPrice = res.totalPayPrice
        })
      },
      searchList() {
        this.page = 1;
        this.getList();
      },
      // 账单周期
      onchangeTime() {
        [this.searchInfo.billPeriodStart, this.searchInfo.billPeriodEnd] = this.timeVal
        this.getList();
      },
      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,
        };
        batchExporBilltApi(2, 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(() => {});
      },
      selectOption(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: 2
          }
        });
      },
      exportDetail(settleBillId) {
        let params = {
          settleBillId
        };
        batchExportApi(2, 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.limit = val;
        this.page = 1;
        this.getList();
      },
      pageChange(page) {
        this.page = page;
        this.getList();
      },
    },
  };
</script>

<style lang="scss" scoped>
  .selWidth {
    width: 350px;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    font-size: 12px;
  }

  .el-icon-arrow-down {
    font-size: 12px;
  }

  /* update  */
  .time-keyword-search {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .btns {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;

    .batch-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;
    }

    .batch-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>
