<template>
  <div class="riselist">
    <RiseCard
      v-if="enterpriseList.length"
      type-title="企业抬头"
      :list="enterpriseList"
      @on-update="onUpdateTitleEvent"
      @on-delete="onDeleteTitleEvent"
    />
    <RiseCard
      v-if="personalList.length"
      type-title="个人抬头"
      :list="personalList"
      @on-update="onUpdateTitleEvent"
      @on-delete="onDeleteTitleEvent"
    />
    <Empy v-if="showEmpy" />
    <footer-button :fixed="true" btn-text="添加发票抬头" @btn-click="addOpenReceipt" />
  </div>
</template>
<script>
import api from '@/api/receipts';
import RiseCard from '../components/riseCard.vue';
import Empy from '../components/empy.vue';
import FooterButton from '../components/footerButton.vue';
import checkOpenMixin from '../mixins/checkOpen.mixin';
import jumpAppMixin from '../mixins/jumpApp.mixin';
export default {
  components: {
    RiseCard,
    Empy,
    FooterButton
  },
  mixins: [checkOpenMixin, jumpAppMixin],
  data() {
    return {
      isFished: false,
      enterpriseList: [],
      personalList: []
    };
  },
  computed: {
    showEmpy() {
      return this.isFished && !this.enterpriseList.length && !this.personalList.length;
    }
  },
  created() {
    this.userInoviceTitleList();
  },
  methods: {
    refreshChange() {
      this.userInoviceTitleList();
    },

    onUpdateTitleEvent({ id, invoiceTitleType }) {
      this.openAppUrl(`/electronicReceipt/invoiceHeader`, { id, invoiceTitleType });
    },

    async onDeleteTitleEvent({ id }) {
      const [, error] = await api.userInoviceTitleDisable(id);
      if (!error) {
        this.$toast('删除成功！');
        this.userInoviceTitleList();
      }
    },
    async userInoviceTitleList() {
      const [res, error] = await api.userInoviceTitleList();
      if (!error) {
        this.filterInvoiceTitleType(res || []);
        if (!res?.length) {
          this.isFished = true;
        }
        return;
      }
      this.isFished = true;
    },
    filterInvoiceTitleType(list) {
      // this.$set(this, 'enterpriseList', []);
      // this.$set(this, 'personalList', []);
      const { enterpriseList, personalList } = list.reduce(
        (origin, item) => {
          if (item.invoiceTitleType === 2) {
            origin.enterpriseList.push(item);
          } else {
            origin.personalList.push(item);
          }
          return origin;
        },
        {
          enterpriseList: [],
          personalList: []
        }
      );
      this.$set(this, 'enterpriseList', enterpriseList);
      this.$set(this, 'personalList', personalList);
    },
    addOpenReceipt() {
      this.openAppUrl('/electronicReceipt/invoiceHeader', { from: 'rise' });
    }
  }
};
</script>
<style lang="less" scoped>
.riselist {
  padding-bottom: calc(58px + constant(safe-area-inset-bottom));
  padding-bottom: calc(58px + env(safe-area-inset-bottom));
}
</style>
