<template>
<div class="wrap">
  <div class="navBar">
    <van-nav-bar
        title="工单批次"
        left-arrow
        left-arrow-color="#FFFFFF"
        :border="false"
        :fixed="true"
        :safe-area-inset-top="true"
        @click-left="goBack"
    />
  </div>
  <van-tabs v-model="active" sticky @click="changeTabHandler" background="#2C395F" color="#ffffff" title-active-color="#ffffff" title-inactive-color="#BDC1CD">
    <van-tab title="全部" name="1"></van-tab>
    <van-tab title="未开票" name="2"></van-tab>
    <van-tab title="已开票" name="3"></van-tab>
  </van-tabs>
  <div class="content_wrap" :class="{ 'pd_cls': active == 2 }">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="getMore"
      >
        <van-search
          v-model="batchCode"
          show-action
          placeholder="请输入批次号或开票编号"
        >
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
        </van-search>
        <van-checkbox-group v-model="checkList">
          <div class="itemWrap" v-for="(item,index) in notifyList" :key="index" @click="toggle(index)">
            <div class="item line1">
              <div class="itemTime">
                <span class="title">批次号:</span>
                <span class="content">{{ item.batchCode }}</span>
              </div>
              <div class="orderNum">
                <span class="title">总案件数:</span>
                <span class="content">{{ item?.orderNum || '' }}</span>
              </div>
              <div class="checkBtn" @click="goPage('invoicingDetail',{id:item.id, batchCode: item.batchCode})">查看</div>
            </div>
            <div class="item">
              <span class="title">开票月份:</span>
              <span class="content">{{ getMonth(item) }}</span>
            </div>
            <div class="item">
              <span class="title">结算总金额:</span>
              <span class="content">{{ item?.totalMoney ? item.totalMoney : 0 }}元</span>
            </div>
            <div class="item">
              <span class="title">扣款金额:</span>
              <span class="content">{{ item?.cutMoney || 0 }}元</span>
            </div>
            <div class="item">
              <span class="title">扣款原因:</span>
              <span class="content" style="color: #FF8F37;">{{ item.remark }}</span>
            </div>
            <div class="item">
              <span class="title">最终开票金额:</span>
              <span class="content">{{ item?.invoiceMoney || 0 }}元</span>
            </div>
            <van-checkbox class="checkbox_cls" v-if="active == 2" :name="item" ref="checkboxes" />
          </div>
        </van-checkbox-group>
      </van-list>
    </van-pull-refresh>
  </div>
  <div class="invoice_btn_wrap" v-if="active == 2 && totalCount > 0">
    <div class="invoice_btn_info">
      <span class="invoice_btn_title">开票总金额</span>
      <span class="invoice_btn_money">￥{{totalCount}}</span>
    </div>
    <div class="btn" @click="goUploadPage">去开票</div>
  </div>
  <div v-show="show" class="bgShow">
    <img src="@/assets/empty.png">
  </div>
</div>
</template>

<script>
import { Decimal } from 'decimal.js';
import {myMixins} from "@/utils/myMixins"
import {notifyInvoiceList, jumpPage} from  "@/api/mine"
import {Dialog} from "vant";
export default {
  name: "invoicingNotify",
  mixins:[myMixins],
  data(){
    return{
      notifyList:[],
      pageNum:1,
      pageSize:10,
      total: 0,
      show:false,
      isLoading: false,
      loading: false,
      active: 1,
      status: '',
      dispatchAppSearchInvoiced: '',
      batchCode: '',
      finished: false,
      checkList: [],
      supplierId: '',
    }
  },
  computed: {
   /* totalCount () {
      let total = 0;
      this.checkList.map(item => {
        total += item.invoiceMoney
      })
      return total
    },*/
    totalCount() {
      // 使用 Decimal 来计算总金额
      let total = new Decimal(0);

      this.checkList.forEach(item => {
        total = total.plus(new Decimal(item.invoiceMoney));
      });

      // 返回总金额，保留两位小数
      return total.toNumber()
    },
  },
  mounted() {
    this.supplierId = this.$route.query?.supplierId;
  },
  methods:{
    goUploadPage() {
      localStorage.setItem('list', JSON.stringify(this.checkList));
      this.goPage('uploadInvoice', { supplierId : this.supplierId })
    },
    async onSearch() {
      this.pageNum=1
      await this.getNotifyList()
    },
    async getMore(){
      if ( this.active != 2 ) {
        await this.getNotifyList()
        this.pageNum++;
        // 加载状态结束
        this.loading = false;
        // 数据全部加载完成
        if (this.notifyList.length >= this.total) {
          this.finished = true;
        }
      } else {
        // 未开票不需要分页，直接标记加载完成
        this.loading = false;
        this.finished = true;
      }
    },
    async changeTabHandler() {
      this.pageNum = 1;
      this.notifyList = [];
      this.checkList = [];
      this.finished = false;
      if (this.active == 1) {   // 全部， 需要分页
        this.status = '';
        this.dispatchAppSearchInvoiced = '';
        this.pageSize = 10;
      } else if(this.active == 2) {   // 未开票, 不需要分页
        this.status = 2;
        this.dispatchAppSearchInvoiced = '';
        this.pageSize = 10000
        let res = await this.getJumpHandler();
        if(res?.data?.jump) {
          Dialog.alert({
            message: '您有暂未完成的培训，请在中道调度APP上完成培训，再进行发票上传',
            confirmButtonText: '去培训',
            confirmButtonColor: '#0E76F4',
            showCancelButton: false,
          }).then(async() => {
            this.goPage('newTrainingList', { supplierId : this.supplierId, type: 'invoice' })
          }).catch(() => {
            // on cancel
          });
          return false
        }
      } else if(this.active == 3) {   // 已开票，需要分页
        this.status = '';
        this.dispatchAppSearchInvoiced = 1;
        this.pageSize = 10
      }
      this.getNotifyList()
    },
    async getJumpHandler() {
      let res = await jumpPage({
        type: 'invoice'
      });
      return res
    },
    getMonth(item) {
      let str = '';
      let startTime = new Date(item.createTime);
      let endTime = new Date(item.overTime);
      str = startTime.getFullYear() + '年' + (startTime.getMonth() + 1 ) + '月 - ' + endTime.getFullYear() + '年' + (endTime.getMonth() + 1) + '月'
      return str
    },
    onRefresh() {
      this.pageNum=1
      this.getNotifyList()
      setTimeout(() => {
        this.$toast('刷新成功');
        this.isLoading = false;
      }, 1000);
    },
    async getNotifyList(){
      let res =  await notifyInvoiceList({
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        status: this.status,
        dispatchAppSearchInvoiced: this.dispatchAppSearchInvoiced,
        total: this.total,
        batchCode: this.batchCode,
        supplierId: this.supplierId,
        current: 1,
      })
      if(res.code == 200){
        this.total=res.total
        if(this.pageNum == 1){
          this.notifyList=res.data;
        }else{
          let preList = this.notifyList;
          let arr = res.data;
          this.notifyList = preList.concat(arr)
        }
        if (this.notifyList.length === 0) {
          this.show=true
        }else{
          this.show=false
        }
      }
    },
    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
  }
}
</script>

<style scoped lang="scss">
@import "@/styles/mixin.scss";
@import "@/styles/common.scss";
.van-checkbox {
  position: absolute;
  bottom: 20px;
  right: 15px;
}
.wrap{
  @include wh(100%,100%);
  background-color: #F4F5F7;
  overflow-y: auto;
  box-sizing: border-box;
  padding-bottom: 30px;
}
.navBar{
  margin-bottom: 46px;
}
.itemWrap{
  background: #FFFFFF;
  position: relative;
  @include wh(100%,194px);
  box-sizing: border-box;
  padding: 14px 25px 18px 29px;
  @include flexBetween;
  margin-bottom: 10px;
  .item{
    @include fontWeightSize(400,12px);
    span{
      display: inline-block;
    }
    .title{
      opacity: .5;
      margin-right: 5px;
    }
  }
  .line1{
    width: 100%;
    @include flexColBet;
    .checkBtn{
      @include bgFontColor(#FFFFFF,#354D93);
      @include wh(48px,18px);
      border-radius: 3px;
      line-height: 18px;
      text-align: center;
    }
  }
}
.bgShow{
  @include flexTwoCenter;
  /*height:calc(100% - 46px);*/
  background-color: #FAFAFA;
  img{
    width: 100%;
  }
}
.van-tabs {
  position: fixed;
  width: 100%;
  background-color: #2c395f;
  z-index: 1000000 !important;
}
  .content_wrap {
    padding-top: 1.17333rem;
  }
  .invoice_btn_wrap {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    background-color: #fff;
    .invoice_btn_info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .invoice_btn_title {
        font-size: 14px;
        font-weight: bold;
      }
      .invoice_btn_money {
        font-size: 26px;
        color: red;
      }
    }
    .btn {
      width: 100%;
      background-color: #2C395F;
      color: #fff;
      padding: 15px 0;
      text-align: center;
      border-radius: 6px;
    }
  }

  .pd_cls {
    padding-bottom: 40px;
  }
</style>
