<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix" v-hasPermi="['platform:bcx:settle:fxs:list']">
        <div class="container">
          <el-form size="small" label-width="100px">
            <div class="time-keyword-search">
              <div class="top-search">
                <el-form-item label="分销商：">
                  <el-input v-model.trim="searchInfo.name" placeholder="请输入分销商名称"
                    class="selWidth" size="small" clearable>
                    <el-button v-hasPermi="['platform:bcx:settle:fxs:list']"
                      slot="append" icon="el-icon-search" size="small" @click="searchList" />
                  </el-input>
                </el-form-item>
                <el-form-item label="结算单号：">
                  <el-input v-model.trim="searchInfo.settleNo" placeholder="请输入结算单号"
                    class="selWidth" size="small" clearable>
                    <el-button v-hasPermi="['platform:bcx:settle:fxs:list']"
                      slot="append" icon="el-icon-search" size="small" @click="searchList" />
                  </el-input>
                </el-form-item>
                <el-form-item label="账期：">
                  <el-date-picker v-model="timePeriodVal" value-format="yyyy-MM"
                    format="yyyy-MM" size="small" type="monthrange" placement="bottom-end"
                    start-placeholder="账单开始时间" end-placeholder="账单结束时间"
                    style="width: 300px" @change="onchangePeriod" />
                </el-form-item>
                <el-form-item label="凭证上传状态" style="margin-left: 10PX;">
                  <el-select v-model="searchInfo.uploadAttachments" @change="searchList">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option label="全部" :value="1">已上传</el-option>
                    <el-option label="全部" :value="2">未上传</el-option>
                  </el-select>
                </el-form-item>
              </div>
              <el-form-item label="时间选择：">
                <el-radio-group v-model="searchInfo.dateLimit" type="button"
                  class="mr20" size="small" @change="searchList">
                  <el-radio-button v-for="(item, i) in fromList.fromTxt"
                    :key="i" :label="item.val">
                    {{ item.text }}
                  </el-radio-button>
                </el-radio-group>
                <el-date-picker v-model="timeVal" value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd" size="small" type="daterange"
                  placement="bottom-end" placeholder="自定义时间"
                  style="width: 250px" @change="onchangeTime" />
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <el-tabs v-model="tabActive" @tab-click="changeTab">
        <el-tab-pane label="待结算" name="0">
          <tableComp :bcxId="bcxId" :billList="billList" :listLoading="listLoading" :page="page"
            :total="total" :limit="limit" :searchInfo="searchInfo" :type="2" :tabActive="tabActive"
            :totalBrokeragePrice="totalBrokeragePrice" :totalCount="totalCount" :totalPayPrice="totalPayPrice"
            @updateList="getList" @handleSizeChange="handleSizeChange" @pageChange="pageChange" />
        </el-tab-pane>
        <el-tab-pane label="已结算" name="1">
          <tableComp :bcxId="bcxId" :billList="billList" :listLoading="listLoading" :page="page"
            :total="total" :limit="limit" :searchInfo="searchInfo" :tabActive="tabActive" :type="2"
            :totalBrokeragePrice="totalBrokeragePrice" :totalCount="totalCount" :totalPayPrice="totalPayPrice"
            @updateList="getList" @handleSizeChange="handleSizeChange" @pageChange="pageChange" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </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 { getSettlementDocApi, confirmSettleApi, batchExporBilltApi, batchExportApi, settleStatisticsApi } from '@/api/distribution';
  import cardsData from '@/components/cards/index';
  import tableComp from './component/tableComp.vue';
  import { checkPermi } from '@/utils/permission'; // 权限判断函数

  export default {
    name: 'settleCompanyBill',
    components: { cardsData, tableComp },
    data() {
      return {
        listLoading: false,
        fromList: this.$constants.fromList,
        timePeriodVal: [],
        timeVal: [],
        billList: [],
        checkList: [],
        searchInfo: {
          name: '',
          settleStatus: null,
          billPeriodStart: '',
          billPeriodEnd: '',
          uploadAttachments: null,
          dateLimit: ''
        },
        limit: 20,
        page: 1,
        total: 0,
        bcxId: null,
        tabActive: 0,
        totalBrokeragePrice: '',
        totalCount: '',
        totalPayPrice: ''
      };
    },
    mounted() {
      if (checkPermi(['platform:bcx:settle:fxs:list'])) {
        this.getList()
      }
      this.bcxId = this.$route.query.bcxId;
    },
    methods: {
      checkPermi,
      getList() {
        this.listLoading = true;
        let params = {
          limit: this.limit,
          page: this.page,
          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,
        };
        getSettlementDocApi(2, 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,
          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,
        };
        settleStatisticsApi(params).then((res) => {
          this.totalBrokeragePrice = res.totalBrokeragePrice
          this.totalCount = res.totalCount
          this.totalPayPrice = res.totalPayPrice
        })
      },
      searchList() {
        this.page = 1;
        this.getList();
      },
      // 账单周期
      onchangePeriod() {
        [this.searchInfo.billPeriodStart, this.searchInfo.billPeriodEnd] = this.timePeriodVal;
        this.getList();
      },
      // 具体日期
      onchangeTime(e) {
        this.timeVal = e;
        this.searchInfo.dateLimit = e ? this.timeVal.join(',') : '';
        console.info('xxx', this.searchInfo.dateLimit);
        this.getList();
      },
      changeTab() {
        this.getList();
      },
      batchSettleBill() {
        if (!this.checkList.length) {
          this.$message({
            message: '至少选中一条记录',
            type: 'warning',
            showClose: true
          });
          return;
        }
        let ids = [];
        this.checkList.forEach(el => {
          ids.push(el.id);
        });
        let params = {
          settleBillIdList: ids
        };
        confirmSettleApi(params).then(res => {
          this.$message({
            message: '结算成功',
            type: 'success',
            showClose: true
          });
          this.getList();
        }).catch(() => {});
      },
      batchExport() {
        let ids = [];
        if (this.checkList.length) {
          this.checkList.forEach(el => {
            ids.push(el.id);
          });
        }
        let params = {
          searchType: 4,
          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,
        };
        batchExporBilltApi(1, 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;
      },
      confirmSettle(index, id) {
        let params = {
          settleBillIdList: [id]
        }
        confirmSettleApi(params).then(res => {
          this.$message({
            message: '结算成功',
            type: 'success',
            showClose: true
          });
          this.billList[index].settleStatus = 3;
        }).catch(() => {});
      },
      navigateToSettleDetail(id) {
        this.$router.push({
          path: '/distribution/settlementBill/settleBillDetail',
          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: 250px;
  }

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

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

  /* update  */
  .time-keyword-search {
    .top-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;
    }
  }
</style>
