const app = {};
import arrowIcon from '../../static/images/arrows.png';
import { mapState } from 'vuex';
import uni from '@/utils/uniHooks';
import { getUrlParams } from '@/utils/index.js';
import { Toast } from 'vant';
import { invoicesDetail, submitInvoice, invoiceEmails, invoicesOrders } from '@/api/parking';

export default {
  data() {
    return {
      picUrl: this.$picUrl,
      globalData: app.globalData,
      arrowIcon: arrowIcon,
      isShow: false,
      isDefaultEMail: false,
      ids: [],
      condition: {
        invoiceType: 'GVATE', // 发票类型：gvat-增值税普通发票svat-增值税专⽤发票gvate-增值税电⼦普票发票svate-增值税电⼦专⽤发票
        remark: '',
        invoiceTitle: {}, // long|发票抬头id
        parkOrderList: [], // 被选中的缴费记录id
        email: '',
        id: '',
        emailAsDefault: true,
      },
      headerInfo: {},
      // 总金额，单位分
      invoiceAmount: 0,
      orderInfo: {},
      type: '', // 当前是活动还是停车
      isSubmitFlag: true, // 发票提交申请的flag,
      pageOptions: null,
      preUrl: '',
      orderQuantity: 0,
      parkingOrder: null,
      pagesize: 10,
      page: 0,
      parkingDetailList: [],
    };
  },
  created() {
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync('previousUrl', '/pages/parkingFee/parkingReceipt/parkingApplication.vue');
  },
  mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '发票申请',
      });
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    this.getEmail();
    const query = getUrlParams();
    this.pageOptions = query;
    if (this.pageOptions) {
      const options = this.pageOptions;
      if (this.pageOptions.againInvoiceFlag) {
        this.getInvoicesOrders(options.invoiceId);
      } else {
        this.invoiceAmount = Number(options.money).toFixed(2);
        this.$store.commit('setTempParkingOrder', options.invoiceDetailList);
        this.$store.commit('setTempParkingMoney', this.invoiceAmount);
        this.parkingDetailList = JSON.parse(options.invoiceDetailList);
      }
      if (options.ids) {
        const ids = options.ids;
        if (ids.indexOf(',') > -1) {
          this.ids = ids.split(',');
        } else {
          this.ids = typeof ids === 'string' ? (ids.indexOf('[') > -1 ? JSON.parse(ids) : [ids]) : ids;
        }
        this.orderQuantity = this.ids.length;
        this.getParkOrderInfo();
      }
      if (options.header) {
        if (typeof options.header == 'string') {
          this.headerInfo = JSON.parse(options.header);
        } else if (typeof options.header == 'object') {
          this.headerInfo = options.header;
        }
      } else {
        this.getInvoiceTitle();
      }
    }
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallId: (state) => state.mallId,
      kipUserId: (state) => state.kipUserId,
      userInfo: (state) => state.userInfo,
      storeEmail: (state) => state.invoice.email,
      storeOldEmail: (state) => state.invoice.oldEmail,
      storeEmailAsDefault: (state) => state.invoice.emailAsDefault,
      storeRemark: (state) => state.invoice.remark,
      storeOldRemark: (state) => state.invoice.oldrRemark,
      source: (state) => state.source, // 来源
    }),
  },
  methods: {
    getInvoicesOrders: async function (id) {
      try {
        const res = await invoicesOrders(id);
        this.invoiceAmount = res.invoiceTotalAmount;
        this.orderQuantity = res.invoicedOrders.length;
        this.parkingOrder = res.invoicedOrders;
        this.$store.commit('setTempParkingOrder', JSON.stringify(res.invoicedOrders));
        this.$store.commit('setTempParkingMoney', res.invoiceTotalAmount);
        this.ids = res.invoicedOrders.map((item) => {
          return item.id;
        });
      } catch {
        uni.showToast({
          title: '服务器开小差了呢，请您稍后再试',
          icon: 'none',
        });
      }
    },
    getEmail: async function () {
      try {
        const res = await invoiceEmails();
        this.condition.emailAsDefault = res.emailAsDefault || this.storeEmailAsDefault;
        if (res.email === this.storeOldEmail) {
          this.condition.email = this.storeEmail;
        } else {
          this.condition.email = res.email;
          this.$store.commit('invoice/set_email', res.email);
          this.$store.commit('invoice/set_old_email', res.email);
        }
        if (res.remark === this.storeOldRemark) {
          this.condition.remark = this.storeRemark;
        } else {
          this.condition.remark = res.remark;
          this.$store.commit('invoice/set_remark', res.remark);
          this.$store.commit('invoice/set_old_remark', res.remark);
        }
      } catch {
        uni.showToast({
          title: '服务器开小差了呢，请您稍后再试',
          icon: 'none',
        });
      }
    },
    changeShowMore() {
      this.isShow = !this.isShow;
    },
    changeDefaultEMail() {
      this.emailAsDefault = !this.emailAsDefault;
    },
    changeHeader() {
      this.$router.push({
        path: 'parkingChooseHeader',
        query: {
          ids: this.ids,
          invoiceDetailList: JSON.stringify(this.invoiceDetailList),
          money: this.invoiceAmount,
          invoiceId: this.pageOptions?.invoiceId,
        },
      });
    },
    gotoDetail() {
      this.$router.push({
        path: 'parkingOrderDetail?useParkingOrderCache=true',
        query: {
          invoiceDetailList: this.pageOptions.againInvoiceFlag ? JSON.stringify(this.parkingOrder) : this.pageOptions.invoiceDetailList,
          money: this.invoiceAmount,
        },
      });
    },
    // 查询全部抬头列表信息
    getInvoiceTitle: async function () {
      const self = this;
      const params = {
        page: this.page,
        size: this.pagesize,
      };
      self.$md(params);
      try {
        const res = await invoicesDetail(params);
        if (res) {
          const list = res.content;
          let currentIndex = 0;
          list.map((item, index) => {
            if (item.defaultOrNot) currentIndex = index;
          });
          self.headerInfo = list[currentIndex] || {};
        }
      } catch (err) {
        uni.showToast({
          title: err.langMessage,
          icon: 'none',
        });
      }
    },
    // 根据选中的停车缴费记录id获取详情信息
    getParkOrderInfo() {
      // 如果当前是活动开票的话，则不差详情
      if (this.type) return;
      this.parkingOrder = this.pageOptions.invoiceDetailList;
    },
    submit: async function () {
      const self = this;
      if (!self.condition.email) {
        Toast({
          message: '请输入电子邮箱地址',
        });
        return false;
      }
      const params = self.condition;
      params.parkOrderList = self.ids.map((item) => {
        return (item = {
          id: item,
        });
      });

      params.invoiceTitle.id = this.headerInfo.id;
      params.totalAmount = Number(this.invoiceAmount);
      if (this.pageOptions.invoiceId) {
        params.id = this.pageOptions.invoiceId;
      }
      if (self.isSubmitFlag) {
        self.isSubmitFlag = false;
        try {
          const res = await submitInvoice(params);
          if (res) {
            Toast({
              message: '开票成功',
            });
            uni.setStorageSync('invoiceindex', 2)
            // vue.router router.replace点两次返回问题及解决方案: https://blog.csdn.net/william_jzy/article/details/85760660
            this.$router.replace({
              path: 'parkingReceipt',
            });
            setTimeout(() => {
              this.$router.go(-1)
            }, 300)
          }
        } catch (err) {
          console.log(111, err);
        }
      }
    },
    mailboxChange() {
      if (this.storeOldEmail !== this.condition.email) {
        this.$store.commit('invoice/set_email', this.condition.email);
      }
    },
    emailAsDefaultChange() {
      this.$store.commit('invoice/set_emailAsDefault', this.condition.emailAsDefault);
    },
    storeRemarkChange() {
      this.$store.commit('invoice/set_remark', this.condition.remark);
    }
  },
};
