<template>
  <div class="bill">
    <div :class="['bg', billActive === history && 'history']" />
    <cr-tabs v-model="billActive" sticky v-bind="tabsConfig">
      <cr-tab :title="billHead.shouldBillDesc">
        <bill-card v-bind="sCardData" />
        <list-content v-if="isOverdue" overdue>
          <list-item
            v-for="(item, idx) in overdueBillList"
            :key="idx"
            :item-data="item"
            :is-overdue="true"
            :user-id="userInfo.userId"
          />
        </list-content>
        <list-content v-if="sNoAmortizeOrderList.length > 0" title="账单分期">
          <list-item
            v-for="(item, idx) in sNoAmortizeOrderList"
            :key="idx"
            :item-data="item"
            :is-stages="true"
          />
        </list-content>
        <list-content
          v-if="sAmortizeOrderList.length > 0"
          title="本月账单明细"
          :bill-trade-cycle="shouldBill.billTradeCycle"
        >
          <list-item v-for="(item, idx) in sAmortizeOrderList" :key="idx" :item-data="item" />
        </list-content>
      </cr-tab>
      <cr-tab :title="billHead.awaitBillDesc">
        <bill-card v-bind="aCardData" />
        <list-content v-if="isOverdue" overdue>
          <list-item
            v-for="(item, idx) in aOverdueBillList"
            :key="idx"
            :item-data="item"
            :is-overdue="true"
            :user-id="userInfo.userId"
          />
        </list-content>
        <list-content v-if="aNoAmortizeOrderList.length > 0" title="账单分期">
          <list-item
            v-for="(item, idx) in aNoAmortizeOrderList"
            :key="idx"
            :item-data="item"
            :is-stages="true"
          />
        </list-content>
        <list-content
          v-if="aAmortizeOrderList.length > 0"
          title="本月账单明细"
          :bill-trade-cycle="awaitBill.billTradeCycle"
        >
          <list-item v-for="(item, idx) in aAmortizeOrderList" :key="idx" :item-data="item" />
        </list-content>
      </cr-tab>
      <cr-tab title="历史账单">
        <cr-collapse v-if="historyBillList.length > 0" v-model="historyActive">
          <cr-collapse-item
            v-for="(item, idx) in historyBillList"
            :key="idx"
            :title="item.billYear"
            :name="idx"
          >
            <div
              v-for="(h, hIdx) in item.value"
              :key="hIdx"
              class="history-item"
              @click="handleToDetails(h)"
            >
              <div class="text">
                <p class="time">{{ h.billMonth }}月账单</p>
                <p class="type">
                  {{ getStatus(h.status) }}
                </p>
              </div>
              <div class="money">
                {{ h.billAmount }}
                <i class="arrow iconfont icon-arrow" />
              </div>
            </div>
          </cr-collapse-item>
        </cr-collapse>
        <div v-else class="empty">暂无历史账单</div>
      </cr-tab>
    </cr-tabs>
    <botton-group
      v-if="isButton"
      :bill-head="billHead"
      :select-status="selectStatus"
      :bill-active="billActive"
      :balance-amount="balanceAmount"
      :bill-no="billNo"
      :add-price="shouldBill.balanceAmount"
    />
  </div>
</template>
<script>
import billCard from './components/billCard';
import bottonGroup from './components/bottonGroup';
import listContent from './components/listContent';
import listItem from './components/listItem';
import { getBill, getHistoryBill } from '@/api/bill.api';
import { getMonthAdd0 } from '@/service/utils.service';
import { mapState } from 'vuex';
import dayjs from 'dayjs';
import {
  AWAIT_BILL,
  SHOULD_BILL,
  HISTORY_BILL,
  SHOULD_ALSO,
  PAY_BACK,
  OVERDUE,
  PAY_COMPLETE
} from '@/constants/bill';
export default {
  components: {
    billCard,
    bottonGroup,
    listItem,
    listContent
  },
  data() {
    return {
      tabsConfig: {
        'title-inactive-color': '#eee',
        'title-bg-color': 'transparent',
        'title-active-color': '#fff',
        'sticky-active-color': '#fff',
        'sticky-inactive-color': '#eee',
        'sticky-line-color': '#fff',
        'sticky-bg-color': 'linear-gradient(269deg, #ff5d00 12%, #ff1900 86%)',
        color: '#fff'
      },
      awaitBill: {
        month: 0
      },
      shouldBill: {
        month: 0
      },
      billHead: {},
      overdueBillList: [],
      aAmortizeOrderList: [],
      aNoAmortizeOrderList: [],
      sNoAmortizeOrderList: [],
      sAmortizeOrderList: [],
      billActive: 0,
      historyActive: [0],
      isAdvance: false,
      isStages: true,
      history: 2,
      aCardData: {},
      sCardData: {},
      historyBillList: [],
      aOverdueBillList: []
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.pay.userInfo || {}
    }),
    isOverdue() {
      return this.shouldBill.status === OVERDUE;
    },
    isButton() {
      return !this.historyStatus;
    },
    shouldStatus() {
      return this.billActive === SHOULD_BILL;
    },
    awaitStatus() {
      return this.billActive === AWAIT_BILL;
    },
    historyStatus() {
      return this.billActive === HISTORY_BILL;
    },
    selectStatus() {
      let status;
      if (this.shouldStatus) {
        status = this.shouldBill.status;
      }
      if (this.awaitStatus) {
        status = this.awaitBill.status;
      }
      return status;
    },
    balanceAmount() {
      let balanceAmount;
      if (this.shouldStatus) {
        balanceAmount = this.shouldBill.balanceAmount;
      }
      if (this.awaitStatus) {
        balanceAmount = this.awaitBill.balanceAmount;
      }
      return balanceAmount;
    },
    billNo() {
      let billNo;
      if (this.shouldStatus) {
        billNo = this.shouldBill.billNo;
      }
      if (this.awaitStatus) {
        billNo = this.awaitBill.billNo;
      }
      return billNo;
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      const [billRes] = await getBill({
        userId: this.userInfo.userId
      });
      if (billRes) {
        const { awaitBill, shouldBill, billHead } = billRes || {};
        this.awaitBill = awaitBill;
        this.shouldBill = shouldBill;
        this.billHead = billHead;
        this.overdueBillList = this.formatOverdue(shouldBill.overdueBillList);
        this.aOverdueBillList = this.formatOverdue(awaitBill.overdueBillList);
        this.sNoAmortizeOrderList = this.formatNoAmortize(shouldBill.noAmortizeOrderList);
        this.sAmortizeOrderList = this.formatAmortize(shouldBill.amortizeOrderList);
        this.aAmortizeOrderList = this.formatAmortize(awaitBill.amortizeOrderList);
        this.aNoAmortizeOrderList = this.formatNoAmortize(awaitBill.noAmortizeOrderList);

        this.sCardData = this.formtCardData(shouldBill);
        this.aCardData = this.formtCardData(awaitBill);
        const [historyBillRes] = await getHistoryBill();
        const { historyBillList } = historyBillRes || {};
        this.historyBillList = this.formatHistory(historyBillList);
      }
    },
    handleToDetails(item) {
      const { year, month, billNo } = item || {};
      const date = year + getMonthAdd0(month) + '01';
      this.$router.push({
        name: 'billDetails',
        query: {
          yearMonth: date,
          billNo,
          userId: this.userInfo.userId
        }
      });
    },
    formatOverdue(data) {
      return (
        data?.map(item => {
          const { amount, billName, billNo } = item;
          return {
            title: amount,
            text: billName,
            rightText: billNo,
            overdue: true,
            ...item
          };
        }) || []
      );
    },
    formtCardData(data) {
      const { lastDay, status, balanceAmount, repayAmountDetail } = data;
      return {
        status,
        orderAmount: balanceAmount,
        lastDay: dayjs(lastDay).format('YYYY-MM-DD HH:mm'),
        repayAmountDetail
      };
    },
    formatAmortize(data) {
      return (
        data?.map(item => {
          const { orderName, orderAmount, orderTime, orderUrl, refundFlag } = item;
          return {
            title: dayjs(orderTime).format('YYYY-MM-DD HH:mm'),
            text: orderName,
            rightTitle: refundFlag,
            rightText: orderAmount,
            orderUrl
          };
        }) || []
      );
    },
    formatNoAmortize(data) {
      return (
        data?.map(item => {
          const { orderName, orderAmount, term, currTerm } = item;
          const title = `第${currTerm}/${term}期`;
          return {
            title,
            text: orderName,
            rightText: orderAmount,
            term,
            currTerm,
            stages: true,
            ...item
          };
        }) || []
      );
    },
    formatHistory(data) {
      let result = [];
      data?.forEach(item => {
        let { billYear } = item;
        if (!result[billYear]) {
          result[billYear] = {
            billYear,
            value: []
          };
        }
        result[billYear].value.push({ ...item });
      });
      return Object.values(result).reverse();
    },

    getStatus(type) {
      let str = '';
      switch (type) {
        case SHOULD_ALSO:
          str = '应还';
          break;
        case PAY_BACK:
          str = '还款中';
          break;
        case OVERDUE:
          str = '逾期';
          break;
        case PAY_COMPLETE:
          str = '已完成';
          break;
      }
      return str;
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
