<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix" v-hasPermi="['platform:bcx:settle:department: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:department: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:department: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" :tabActive="tabActive" :type="4" @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="4" @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 } from '@/api/distribution';
import cardsData from '@/components/cards/index';
import tableComp from './component/tableComp.vue';
import { checkPermi } from '@/utils/permission'; // 权限判断函数
export default {
  name: 'settleDepartmentBill',
  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,
      totalPage: null,
      bcxId: null,
      tabActive: 0
    };
  },
  mounted() {
    if (checkPermi(['platform:bcx:settle:department: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
      };

      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.settleNo ? params.settleNo = this.searchInfo.settleNo : null;
      this.searchInfo.uploadAttachments > 0 ? params.uploadAttachments = this.searchInfo.uploadAttachments : null;

      getSettlementDocApi(4, params).then(res => {
        let { limit, total, totalPage, page, list } = res;
        this.limit = limit;
        this.total = total;
        this.totalPage = totalPage;
        this.page = page;
        this.billList = list;
        this.listLoading = false;
      }).catch(() => {
        this.listLoading = false;
      })
    },

    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 = {};
      this.bcxId ? params.bcxId = this.bcxId : null
      this.searchInfo.billPeriodStart ? params.billPeriodStart = this.searchInfo.billPeriodStart : null;
      this.searchInfo.billPeriodEnd ? params.billPeriodEnd = this.searchInfo.billPeriodEnd : null;
      this.searchInfo.name ? params.name = this.searchInfo.name : null;
      this.searchInfo.settleStatus > 0 ? params.settleStatus = this.searchInfo.settleStatus : null;

      batchExporBilltApi(1, 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;
    },

    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(3, 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(() => {});
    },

    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>
