import uni from '@/utils/uniHooks';
import { Toast } from 'vant';
// const app = getApp()
const app = {};
import { mapState } from 'vuex';
import fuiToast from '@/components/fui-toast/fui-toast.vue';
import { initWxJsSdkConfig } from '@/utils/login';
import { getPlatform } from '@/utils';
import { paperCoupon } from '@/api/parking'

export default {
  components: {
    fuiToast,
  },
  created() {

  },
  data() {
    return {
      // parkFee: {}, // 停车规则相关信息
      // // parkPaperCouponRemark: '', // 纸质优惠券说明
      // servicefee: 0, // 应缴金额
      // paperDiscountFee: 0, // 纸质优惠券减免金额
      // paperDiscountTime: 0, // 纸质优惠券减免时长
      // parkDiscountTotal: {}, // 总停车优惠
      paperCouponList: [], // 纸质券list
      // paperCouponInfo: {}, // 页面缓存
      // maxonetimediscountFee: 0, // 每次优惠上限金额
      // maxonedaydiscountFee: 0, // 每天优惠上限金额
      // parkMallCode: 1, // 0静安 1浦东 2杭州 3北京 4沈阳 5深圳
      // parkInfo: {},
    };
  },
  async mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '纸质优惠券减免',
      });
    },300);
    const platform = getPlatform();
    if ( platform === 'micromessenger' ) {
      // this.getTicket();
      await initWxJsSdkConfig(['checkJsApi','scanQRCode']);
      // await initWxJsSdkConfig(['checkJsApi', 'scanQRCode']);
      // if (window.wxJsSdkConfigInitPromise) {
      //   await window.wxJsSdkConfigInitPromise;
      // }
    }
    this.pageInit()
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '优惠券',
      });
    },300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
  },
  computed: {
    ...mapState({
      custTypeId: ( state ) => state.custTypeId,
      mallid: ( state ) => state.mallId,
      openId: ( state ) => state.openid,
      member: ( state ) => state.member,
      groupId: ( state ) => state.groupId,
      orderDetail: ( state ) => state.order.orderDetail,
      paperCoupons: ( state ) => state.order.paperCoupons,
      paperDiscountFee: ( state ) => state.order.paperDiscountFee,
      paperDiscountTime: ( state ) => state.order.paperDiscountTime,
      paperCouponsDesc: ( state ) => state.order.paperCouponsDesc,
    }),
  },
  methods: {
    pageInit() {
      this.paperCouponList = [...this.paperCoupons]
    },
    showToast( text ) {
      let options = {};
      options.text = text;
      this.$refs.toast.show(options);
    },
    // 扫码
    scanCode() {
      const runScanFn = ( res ) => {
        if ( res.scanType == 'QR_CODE' && res.scanType ) {
          console.log(res.result);
          const url = res.result;
          if ( url.indexOf('auth/') === -1 ) {
            this.getPaperCouponInfo(res.result);
          } else {
            const start = url.indexOf('auth/');
            const end = url.indexOf('?');
            const params = url.slice(start,end).split('/');
            if ( params && params.length ) {
              const couponCode = params[1];
              this.getPaperCouponInfo(couponCode);
            }
          }
        }
      };
      // 微信小程序
      const platform = getPlatform();
      if ( platform === 'miniprogram' ) {
        window.toWXSendMsg({
          type: 'scanQRCode',
        });
        window.subscribe('scanQRCodeOver',( options ) => {
          console.log('微信扫码结束之后的返回参数',options);
          runScanFn(options);
        });
      } else {
        this.$wx.scanQRCode({
          desc: 'scanQRCode desc',
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          // scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
          success: ( res ) => {
            console.log(237,res);
            runScanFn(res);
            // this.formMsg.deviceCode = res.resultStr;
          },
          error: ( res ) => {
            console.log(242,res);
          },
        });
      }
    },

    // 根据卡券ID查询卡券信息
    async getPaperCouponInfo( couponCode ) {
      uni.showLoading({
        title: '加载中',
      });
      const res = await paperCoupon(couponCode, this.$route.query.vehicleNo);
      /*const res = {
        "status": "1",
        "discountCode": "91354260",
        "discountFee": 1,
        "used": "0",
        "content": "嘉里卡券测试"
      }*/
      if ( /0/.test(res.status)) {
        return Toast({
          message: '该纸质优惠券未激活',
        });
      }
      if (/1/.test(res.used)) {
        return Toast({
          message: '该纸质优惠券已领取',
        });
      }
      if (/2/.test(res.used)) {
        return Toast({
          message: '该纸质优惠券已使用',
        });
      }
      if (/3/.test(res.used)) {
        return Toast({
          message: '该纸质优惠券已核销',
        });
      }
      // console.log(157, res)
      if(res.code === "300000") {
        return Toast({
          message: res.message,
        });
      }
      // console.log(158, this.paperCoupons)
      // console.log(158, this.paperCoupons.findIndex(item => {
      //   console.log(160, item.discountCode, couponCode)
      //   return item.discountCode === couponCode
      // }))
      // 如果纸质优惠券不存在的话，则往 paperCoupons 添加
      if ( this.paperCouponList.findIndex(item => item.couponCode === couponCode) < 0 ) {
        // const {hourPrice} = this.orderDetail.parkingRule
        // const discountTime = Number(res.discountFee) / hourPrice
        const paperCouponList =  [
          ...this.paperCouponList,
          {
            ...res,
            couponCode: couponCode
            // discountTime: res.discountFee / hourPrice
          }
        ]
        this.paperCouponList = paperCouponList
        this.$store.commit('order/setPaperCoupons',paperCouponList)
        // 金额
        this.$store.commit('order/setPaperDiscountFee',this.paperDiscountFee + Number(res.discountFee))
        // 时间
        // this.$store.commit('order/setPaperDiscountTime',this.paperDiscountTime + discountTime)
      } else {
        return Toast({
          message: '优惠劵已添加，请勿重复扫码',
        });
      }
    },
    // 删除
    deleteCoupon( item ) {
      this.paperCouponList = this.paperCouponList.filter(elm => elm.couponCode !== item.couponCode)
      // const {hourPrice} = this.orderDetail.parkingRule
      // const discountTime = Number(item.discountFee) / hourPrice
      this.$store.commit('order/setPaperCoupons',this.paperCouponList)
      // 金额
      this.$store.commit('order/setPaperDiscountFee',this.paperDiscountFee - Number(item.discountFee))
      // 时间
      // this.$store.commit('order/setPaperDiscountTime',this.paperDiscountTime + discountTime)
    },

    // 确认
    confirm() {
      console.log(310,this.orderDetail);
      
      this.$store.dispatch('order/savePaperCoupon', {
        paperCoupons: this.paperCoupons,
        callback: () => {
          this.$router.back();
        },
      });
    },
  },
};
