// const app = getApp()
const app = {};
import moment from 'moment';
import arrowIcon from '../../static/images/arrows.png';
import noData from '../../static/images/no-invoice.svg';
import { mapState } from 'vuex';
import LoginDom from '@/components/Login/Login.vue';
// import authorize from '@/components/authorize/authorize.vue'
import MemberCacheTool from '@/utils/member-cache-tool.js';
import { REG_SOURCE } from '@/constants.js';
import uni from '@/utils/uniHooks';
import { myNotInvoicedList } from '../../list';
import { wxToLoginCallback } from '@/utils';
import CacheTool from '@/utils/cache-tool'
import { invoicesCompleted, invoicesNotapplied } from '@/api/parking';
import { Dialog } from 'vant';
export default {
  data() {
    return {
      globalData: app.globalData,
      picUrl: this.$picUrl,
      baseUrl: this.$baseURL,
      arrowIcon: arrowIcon,
      noData: noData,
      tabIndex: 1,
      invoiceList: ['未开票', '已开票'],
      list: [],
      isCheckTickets: [],
      total: 0,
      isLoadMore: false,
      loadStatus: 'loading',
      pagesize: 10,
      page: 0,
      current: -1,
      isCheckAll: 0,
      ids: [],
      totalNum: 0.0,
      options: null,
      preUrl: '',
      invoiceDetailList: [],
      boxids: [],
      choosekMax: 200,
      statusObj:{
        'COMPLETE': {
          name: '开票完成'
        },
        'SUBMITTED': {
          name: '开票中'
        },
        'FAILED': {
          name:'开票失败'
        },
        3: {
          name:'开票失败'
        },
        2: {
          name:'开票中'
        }
      }
    };
  },
  components: {
    // authorize,
    LoginDom,
  },
  computed: {
    height() {
      return this.list.length ? 'auto' : '100%';
    },
    isJingAn () {
      let mallid = this.mallId;
      if (!mallid) {
        mallid = uni.getStorageSync('mallId');
      }
      return CacheTool.isJingAnMallid(mallid);
    },
    ...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,
      member: (state) => state.member,
      mobile: (state) => state.mobile,
    }),
  },
  created() {
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    this.$store.dispatch('invoice/init')
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/parkingReceipt/parkingReceipt.vue'
    );
  },
  mounted() {
    // const member = uni.getStorageSync('member')
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '停车发票',
      });
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    const invoiceindex = Number.parseInt(uni.getStorageSync('invoiceindex') || 1)
    this.$store.dispatch('clearUnlicensed');
    if (JSON.stringify(this.member) !== '{}') {
      this.invoice(invoiceindex);
    } else {
      wxToLoginCallback('parkingReceipt', () => {
        this.$router.back();
      });
    }
  },
  watch: {},
  filters: {
    parkingTime(val) {
      const days = parseInt(val / 60 / 24);
      const hours = parseInt((val / 60) % 24);
      const minutes = parseInt(val % 60);
      if (days > 0) {
        return `${days}天 ${hours}小时 ${minutes}分钟`;
      }
      if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`;
      }
      return `${minutes}分钟`;
    },
  },
  methods: {
    checkboxchange2 (e, index) {
      if (this.boxids.length > this.choosekMax) {
        console.log(2222222222)
        this.$refs.checkboxes[index].toggle();
      }
      console.log('eeeeeeee:::', e, index)
    },
    invoice(e) {
      uni.setStorageSync('invoiceindex', e);
      this.tabIndex = e;
      this.current = -1;
      this.ids = [];
      this.totalNum = 0.00;
      this.page = 0;
      this.list = [];
      this.getInvoiceList();
    },
    goToDeatil(item) {
      if (this.tabIndex === 2 && item.status === 'COMPLETE') {
        this.$router.push({
          path: 'parkingInvoice?id=' + item.id,
        });
      }
    },
    goToInvoicing() {
      if (this.ids.length <= 0) {
        uni.showToast({
          title: '请选择您要开票的记录',
          icon: 'none',
        });
        return false;
      }
      if (this.totalNum <= 0) {
        uni.showToast({
          title: '请选择金额大于0的缴费记录',
          icon: 'none',
        });
        return false;
      }
      this.$router.push({
        path: 'parkingApplication',
        query: {
          ids: this.ids,
          invoiceDetailList: JSON.stringify(this.invoiceDetailList),
          money: this.totalNum
        }
      });
    },
    radioChange: function (evt) {
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].id === evt.detail.value) {
          this.current = i;
          this.ids = [this.list[i].id];
          this.totalNum = this.list[i].totalPaidAmount;
          if (this.ids > 2) {
            Dialog.confirm({
              message: '确认要删除该发票抬头吗？',
              confirmButtonColor: this.$theme[this.theme].primaryColor,
            })
              .then(() => {
                
              })
              .catch(() => {
                // on cancel
              });
          }
          break;
        }
      }
    },
    scrollLower() {
      console.log('到底了........');
      if (!this.isLoadMore) {
        this.isLoadMore = true;
        this.page += 1;
        this.getInvoiceList();
      }
    },
    getInvoiceList: async function (){
      const self = this;
      // const openId = MemberCacheTool.getOpenId(app)
      var params = {
        // openId: this.openid,
        // mallid: this.mallId,
        // vipcode: this.member?.vipcode,
        page: this.page,
        size: this.pagesize,
      };
      try {
        let res = null;
        if (this.tabIndex === 1) {
          res = await invoicesNotapplied(params)
        } else {
          res = await invoicesCompleted(params)
        }
          console.log('99', res)
          if (res) {
            this.total = res.size;
            const listarr = res.content
            if (listarr.length > 0) {
              this.list = this.list.concat(res.content)
            }
            // 返回数据量小于pagesize，则表示此为最后一页
            if (res.content.length < this.pagesize) {
              this.isLoadMore = true;
              this.loadStatus = 'nomore';
            } else {
              this.isLoadMore = false;
            }
            
          } else {
            this.isLoadMore = true;
            this.loadStatus = 'nomore';
          }
          
      } catch(err) {
        this.isLoadMore = false;
        if (this.page > 1) {
          this.page -= 1;
        }
      }
      // mock数据
      // this.list = [{
      //   orderNo: 'qqqqqqq',
      //   id: 'qqqqqqq',
      //   totalPaidAmount: 111,
      //   taxNo: 'qqqqqqq',
      //   status: 'FAILED',
      //   errorMessage: 'errorMessage',
      //   vehicleNo: 'qqqqqqq',
      //   enterTime: '2023-09-89',
      //   parkName: '111',
      //   serviceMin: '111',
      // }]
    },
    checkboxChange(ids) {
      this.boxids = ids
      console.log(423, ids);
      if (ids.length > this.choosekMax) {
        
        Dialog.alert({
          title: '选择上限提示',
          message: '合并开票订单数量上限为200条，超出的部分请多次开具',
          confirmButtonText: '关闭',
          confirmButtonColor: this.$theme[this.theme].primaryColor,
        }).then(() => {
          // on close
        });
          return;
      }
      this.calculatePrice(ids);
      return;
      const itemId = e.detail.value;
      let list = this.list;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (itemId.includes(item.id)) {
          this.$set(item, 'checked', true);
        } else {
          this.$set(item, 'checked', false);
        }
      }
      this.calculatePrice(list);
    },
    calculatePrice(list) {
      this.invoiceDetailList = []
      this.totalNum = 0
      if (list && list.length > 0) {
        this.list.forEach(element => {
          if (list.includes(element.id)) {
            const totalPaidAmount = element.totalPaidAmount;
            this.totalNum = this.totalNum + totalPaidAmount;
            this.invoiceDetailList.push(element)
          }
        });
        console.log('this.totalNum', this.totalNum)
      } else {
        this.totalNum = 0;
      }
    },
    showFailureReason(reson) {
      console.log('12345')
      this.$dialog({
        title: '开票失败原因',
        message: reson,
        confirmButtonText: '关闭',
        confirmButtonColor: this.$theme[this.theme].primaryColor,
      }).then(() => {
        // on confirm
        console.log('confirm');
      });
    },
    // 重新开票
    tryGoToInvoicing(item) {
      console.log(item, 'chooseHeaderchooseHeaderchooseHeader')
      this.$router.push({
        path: 'parkingApplication',
        query: {
          ids: item.ids,
          invoiceId: item.id,
          againInvoiceFlag: true
        },
      });
    },
  },
};
