import { mapState } from 'vuex';
import uni from '@/utils/uniHooks';
// import { initWxJsSdkConfig } from '@/utils/login';
import { Toast } from 'vant';
import { getPlatform, getAppIdByGroupIdAndMallId, isInWeixinH5 } from '@/utils';
import { initWxJsSdkConfig } from '@/utils/login';
// import { compare } from '@/utils/location.js';
// import { isArray } from 'lodash';
// import { v4 as uuidv4 } from 'uuid';

export default {
  data() {
    return {
      checkedCouponList: [],
      couponList: [],
      launchPath: '', // H5跳转CRM微信小程序
      envVersion: window.env === 'qa' ? 'trial' : 'release', // 所需跳转的小程序版本，合法值为：正式版release、开发版develop、体验版trial（支持的微信版本：iOS 8.0.18及以上、Android 8.0.19及以上）
      platform: getPlatform(),
      maxCouponFee: 0, // 计算优惠券已选的总金额
      remainPrice: 0, // 剩余可用优惠额度
      newAvailableDiscountFee: 0, // 可使用的电子券的优惠金额上限
      extraData: {}
    };
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      actualPayFee: (state) => state.order.actualPayFee,
      orderDetail: (state) => state.order.orderDetail,
      coupons: (state) => state.order.coupons,
      maxOneDayDiscountFee: (state) => state.order.maxOneDayDiscountFee, // 深圳单日单次使用上限
      usingTotalDiscount: (state) => state.order.usingTotalDiscount, // 当前已使用优惠
      availableDiscountFee: (state) => state.order.availableDiscountFee, // 当前已使用优惠
      paperDiscountFee: (state) => state.order.paperDiscountFee, // 当前已使用优惠
      unLimitWeekendPoints: (state) => state.order.unLimitWeekendPoints, // 新的积分上限, 默认为false（不开启）, unLimitWeekendPoints： true # 开启无上限功能；   unLimitWeekendPoints： false # 关闭无上限功能；
      lbsId: (state) => state.lbsId, // 楼栋ID
      groupId: (state) => state.groupId, // 楼盘ID
      remainCoupons: ( state ) => state.order.remainCoupons, // 仅限杭州当前剩余可选电子券上限
      parkMallCode: ( state ) => state.order.parkMallCode, // 当前车场的数据
      maxOneDayCoupons: ( state ) => state.order.maxOneDayCoupons,// 仅限杭州当日电子券可选上限
    }),
  },

  mounted() {
    // console.log('parkingFeeCoupon.js');
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '优惠券',
      });
      if (isInWeixinH5()) {
        initWxJsSdkConfig(['checkJsApi', 'chooseImage'], ['wx-open-launch-weapp']);
        this.launchPathInit();
      }
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    this.pageInit();
  },
  methods: {
    pageInit() {
      const {parkInfo} = this.orderDetail
      const { parkMallCode } = parkInfo;
      /*
       * 电子优惠券初始化逻辑(后端处理)
       *
       * 1、每次change之后，需要重新计算每个电子优惠券的逻辑
       * 2、superposition  叠加使用规则 （1不可叠加，2仅同类型可叠加，3可叠加）;
       * */
      this.couponList = [...this.coupons];
      this.remainPrice = this.usingTotalDiscount;
      if ((this.parkMallCode === 4 || this.parkMallCode === 6) && this.orderDetail?.discountInfo?.points[0]?.discountFee) {
        this.remainPrice = this.remainPrice - this.orderDetail.discountInfo.points[0].discountFee
      }   
      // 如果前海开启无积分上限的话，则
      if ( parkMallCode === 5 && this.unLimitWeekendPoints && this.orderDetail.discountInfo?.points[0]?.discountFee) {
        this.remainPrice = this.remainPrice - this.orderDetail?.discountInfo?.points[0]?.discountFee
      }
      this.newAvailableDiscountFee = this.availableDiscountFee
      // console.log(878787, this.newAvailableDiscountFee);
      if (this.couponList.length) {
        this.couponList = this.couponList.map((elm, index) => {
          elm.disabled = true;
          const selected = elm.hasOwnProperty('selected') ? elm.selected : elm.defaultSelected;
          if (selected) {
            this.maxCouponFee = this.maxCouponFee + elm.discountFee;
            this.checkedCouponList.push(`coupon${index}`);
            elm.disabled = false;
          } else {
            // elm.disabled = !elm.defaultSelected
          }
          return elm;
        });
        if (!this.checkedCouponList.length) {
          this.couponList = this.couponList.map((elm) => {
            elm.disabled = false;
            return elm;
          });
        }
        this.$nextTick(() => {
          // 验证剩余优惠券是否可勾选(无需验证：后端已计算可勾选的优惠券)
          this.newGroupedCouponData()
          this.setAllDisabled()
          if (this.parkMallCode === 4 || this.parkMallCode === 6) {
            this.isDisabledByRule(this.couponList[0], 0, 'showMsg');
          }          
        })
      }
    },
    item2Number(i) {
      return Number.parseInt(i.replace(/coupon/g, ''));
    },
    checkboxItemChange(name, index) {
      const coupon  = this.couponList[index];
      if ( coupon.disabled ) {
        setTimeout(() => {
          // 根据电子券规则判断是否可选
          this.isDisabledByRule(coupon, index);
        }, 100)
        return;
      }
      // 取消勾选时
      if (this.checkedCouponList.indexOf(name) > -1) {
        this.checkedCouponList = this.checkedCouponList.filter((i) => i !== name);
        setTimeout(() => {
          this.remainPrice = this.remainPrice - this.couponList[index].discountFee
          this.newAvailableDiscountFee = this.newAvailableDiscountFee + this.couponList[index].discountFee
          this.newGroupedCouponData()
          this.isDisabledByRule(coupon, index, 'showMsg');
        }, 100)
        return;
      }
      // 如果有选中项
      const item = this.couponList[index];
      this.remainPrice = this.remainPrice + this.couponList[index].discountFee
      this.newAvailableDiscountFee = this.newAvailableDiscountFee - this.couponList[index].discountFee
      if (!item.disabled) {
        this.checkedCouponList.push(`coupon${index}`);
      }
      this.$nextTick(() => {
        this.newGroupedCouponData()
        this.setAllDisabled()
        this.isDisabledByRule(coupon, index, 'showMsg');
      })

    },
    // 针对达到优惠的上限制
    setAllDisabled() {
      const {parkInfo,parkingRule} = this.orderDetail
      const { parkMallCode } = parkInfo;
      const {maxOneTimeDiscountTime,oneTimeLimitation,oneDayLimitation,hourPrice,remainConsumeTime} = parkingRule
      // 设置深圳的达到优惠金额的上限，置灰剩下未选择的金额
      if ( parkMallCode === 5 && this.remainPrice >= this.newAvailableDiscountFee) {
        this.couponList = this.couponList.map((elm,iemi) => {
          if ( !elm.disabled && this.checkedCouponList.indexOf(`coupon${iemi}`) < 0) {
            elm.disabled = true
          }
          return elm
        })
        return true
      }
      // 单日上限限制
      if ( oneDayLimitation  && parkMallCode !== 5) {
        const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice
        const remainConsumeTimeFee = remainConsumeTime * hourPrice
        
        // 计算单日剩余 remainConsumeTime
        // 当前使用优惠 state.usingTotalDiscount
        // 判断符合上限
        if ( this.remainPrice >= maxOneTimeDiscountFee) {
          this.couponList = this.couponList.map((elm,iemi) => {
            if ( !elm.disabled && this.checkedCouponList.indexOf(`coupon${iemi}`) < 0) {
              elm.disabled = true
            }
            return elm
          })
        }
      }
      // 单次上限限制
      if ( oneTimeLimitation && parkMallCode !== 5 ) {
        const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice
        // const remainConsumeTimeFee = remainConsumeTime * hourPrice
        // 计算单日剩余 remainConsumeTime
        // 当前使用优惠 state.usingTotalDiscount
        // 判断符合上限
        if ( this.remainPrice >= maxOneTimeDiscountFee ) {
          this.couponList = this.couponList.map((elm,iemi) => {
            if ( !elm.disabled && this.checkedCouponList.indexOf(`coupon${iemi}`) < 0) {
              elm.disabled = true
            }
            return elm
          })
        }
      }
      // 杭州电子券选择上限判断
      if ( parkMallCode === 2 && this.checkedCouponList.length === this.remainCoupons ) {
        this.couponList = this.couponList.map(( elm,iemi ) => {
          if ( !elm.disabled && this.checkedCouponList.indexOf(`coupon${ iemi }`) < 0 ) {
            elm.disabled = true
          }
          return elm
        })
      }
      return false
    },
    // 对不同类型的优惠券进行汇总统计
    newGroupedCouponData() {
      let couponList = [...this.couponList]; // 获取目前用户的电子券
      if (!this.checkedCouponList.length) {
        this.couponList = couponList.map(elm => {
          elm.disabled = elm?.status !== 'available';
          return elm;
        })
        return
      }
      // 如果杭州的使用券打到上限则不自动计算其余券是否可选
      if ( this.checkedCouponList.length >= this.remainCoupons && this.parkMallCode === 2 ) {
        return
      }
      // console.log(292,this.couponList);
      const index = this.item2Number(this.checkedCouponList[0])
      const item = this.couponList[index];
      const { superposition, limitCountPerOrder = 0, name } = item;
      switch (superposition) {
        case '1': // 不可叠加
          couponList = couponList.map((elm, i) => {
            elm.disabled = i !== index
            return elm;
          })
          break;
        case '2': // 同类型可叠加
                  // 找到
          couponList = couponList.map((elm, i) => {
            // 只有 status === 'available' 的才会赋值为 false
            elm.disabled = elm?.status !== 'available'; // 默认可选
            // 找到所以 superposition === 2 的同类型的券
            if ( elm?.status === 'unavailable' ) {
              // 这里是做一个阻断，就是避免程序往下执行，没有别的意思
              elm.disabled = true
            } else if (elm.superposition === superposition) { // 这里是找到一样类型的券
              const selectCouponIds = couponList.filter((iem, iemi) => iem.couponId === elm.couponId && this.checkedCouponList.indexOf(`coupon${iemi}`) > -1); // 筛选出相同批次（couponId一样）的电子券，并且是已经选中的
              if (elm.limitCountPerOrder > 1) { // 是否存在上限
                if (selectCouponIds.length >= elm.limitCountPerOrder) { // 如果这个批次的券已经选了一部分，并且超过了可选上限的话。
                  elm.disabled = selectCouponIds.findIndex(iem => iem.code === elm.code) < 0 // 置灰剩余没有选中的电子券
                }
              } else {
                elm.disabled = selectCouponIds.findIndex(iem => iem.code === elm.code) < 0 && selectCouponIds.length > 0 // 同类型可选的券，如果可选上限是1，就设为不可选择
              }
            } else {
              elm.disabled = true; // 非同批次的优惠券设置为不可选择
            }
            return elm
          })
          break;
      }
      this.couponList = [...couponList];
    },
    // 根据电子券规则判断是否可选
    isDisabledByRule(item, index, showMsg) {
      const { parkMallCode } = this.orderDetail.parkInfo;
      // 最高优先级，提示未生效的电子券
      if (item.status === 'unavailable') {
        return Toast({
          className: 'top300',
          message: `当前电子券暂未生效，不可用`,
          icon: 'none',
        });
      }
      if ( this.checkedCouponList.length >= this.remainCoupons && this.parkMallCode === 2 ) {
        if ( showMsg ) return true
        return Toast({
          className: 'top300',
          message: `电子券每天最多可使用${ this.maxOneDayCoupons }张`,
          icon: 'none',
        });
      }

      // 浦东每次缴费超限控制、沈阳每日超限控制
      if ((parkMallCode === 1 || parkMallCode === 4 || parkMallCode === 5 || parkMallCode === 999 || parkMallCode === 6) && this.crossMessage(showMsg)) {
        this.couponList = this.couponList.map((e, i) => {
          if (this.checkedCouponList.findIndex((c) => c === `coupon${i}`) === -1) {
            e.disabled = true;
          }
          return e
        });
        return;
      }

      // 选中状态赋值
      // this.groupedCouponData();
      this.newGroupedCouponData();
    },
    // 是否选中
    isCheck(val) {
      return this.checkedCouponList.findIndex((e) => e == val) !== -1;
    },
    // 超限提示
    crossMessage(showMsg = '') {
      const { parkMallCode } = this.orderDetail.parkInfo;
      const { maxOneDayCoupons, maxonedaydiscountFee, maxOneTimeDiscountTime, remainConsumeTime, hourPrice, availableDiscountFee, oneTimeLimitation,oneDayLimitation, maxOneDayDiscountFee } = this.orderDetail.parkingRule;
      const {
        usingTotalDiscount, // 使用总抵扣
        coupons,
      } = this.orderDetail.discountInfo;
      const {
        // totalFee, // 应缴
        actualPayFee, // 应付金额
      } = this.orderDetail.parkingRecord;
      // 剩余可使用的优惠金额，支持动态计算; 优惠时长，不可能全部使用，不能超过车费减去优惠的金额;不能超过单次的应付金额
      let remainPrice = remainConsumeTime * hourPrice;
      if (parkMallCode === 5) {
        if (remainPrice - this.paperDiscountFee > actualPayFee) {
          remainPrice = actualPayFee;
        }
      }
      // 深圳超限处理
      if (parkMallCode === 5 && this.remainPrice  >= this.availableDiscountFee) {
        if ( showMsg ) return true
        return Toast({
          message: `每日最高可抵扣${this.maxOneDayDiscountFee}元`,
          icon: 'none',
        });
      }

      // 单日上限
      if (oneDayLimitation && this.remainPrice >= this.availableDiscountFee) {
        if ( showMsg ) return true
        return Toast({
          message: `每日最高可抵扣${maxOneDayDiscountFee}元`,
          icon: 'none',
        });
      }
      const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice
      // 单次上限限制
      if ( oneTimeLimitation && parkMallCode !== 5 && this.remainPrice >= maxOneTimeDiscountFee) {
        if ( showMsg ) return true
        return Toast({
          message: `超出抵扣上限,每次最高可抵扣${maxOneTimeDiscountTime}小时`,
          icon: 'none',
        });
      }
      return false
    },
    // 确认
    confirm() {
      // 重新计算兑换券优惠
      const checkedCouponList = this.checkedCouponList.map((i) => this.item2Number(i));
      const couponList = this.couponList.map((elm, index) => {
        elm.selected = false;
        if (this.checkedCouponList.indexOf(`coupon${index}`) > -1) {
          elm.selected = true;
        }
        return elm;
      });
      this.$store.dispatch('order/saveCouponMath', {
        couponList: couponList,
        callback: () => {
          this.$router.back();
        },
      });

      /*uni.setStorageSync('checkedCouponList', this.checkedCouponList);
       uni.setStorageSync('list', this.list);
       uni.setStorageSync('couponInfo', {
       couponfee: this.totalFee,
       couponcode: this.couponCode.join('#'),
       });
       this.$router.back();*/
    },
    launchPathInit() {
      const groupId = uni.getStorageSync('groupId');
      const mallId = uni.getStorageSync('mallId');
      const { projectId } = getAppIdByGroupIdAndMallId({
        groupId: groupId,
        mallId: mallId,
        type: 'all',
      });
      this.launchPath = `?trackSourceType=运营位&trackSourceName=功能球&projectId=${projectId}&groupId=${groupId}&mallId=${mallId}&source=tparkingH5`;

      let isLogin = false
      const member = uni.getStorageSync('member');
      if (member && JSON.stringify(this.member) !== '{}') {
        isLogin = true
      }
      this.extraData = {
        brandId: this.groupId,
        lbsId: this.lbsId,
        isLogin: isLogin,
        navigate_time:new Date().getTime()
      }
    },
    // 跳转小程序
    navigateToMiniProgram() {
      if (this.platform === 'miniprogram') {
        window.toWXSendMsg({
          type: 'navigateToMiniProgram',
          options: {
            retailLbsId: this.lbsId,
          },
        });
        // 订阅微信小程序端的回调
        window.subscribe('navigateToMiniProgramOver', (options) => {
          if (options.navigateToMiniProgramOver === 'ok') {
            this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
              name: 'parkingFeeDetail',
            });
            this.$router.go(-2);
          }
        });
      }
      if (isInWeixinH5()) {
        // this.$wx.chooseWXPay({
        //   timestamp: params?.timeStamp,
        //   nonceStr: params?.nonceStr,
        //   package: params?.package,
        //   signType: params?.signType,
        //   paySign: params?.paySign,
        //   success: function (res) {
        //     // alert('success: ' + JSON.stringify(res));
        //     // res: {"errMsg":"chooseWXPay:cancel"}
        //     if (res.errMsg === 'chooseWXPay:ok') {
        //       resolve({ errMsg: 'requestPayment:ok' });
        //     } else {
        //       reject(res);
        //     }
        //   },
        //   cancel: function (res) {
        //     // alert('cancel: ' + JSON.stringify(res));
        //     // res: {"errMsg":"chooseWXPay:cancel"}
        //     resolve({ errMsg: 'requestPayment:cancel' });
        //   },
        //   fail: function (err) {
        //     // eslint-disable-next-line no-console
        //     console.error(err);
        //     reject(err);
        //   },
        // });
      }
    },
    // H5 跳转到小程序
    launchFn({ appId, extInfo }) {
      // console.log(584, JSON.stringify({ appId, extInfo }));
      this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
        name: 'parkingFeeDetail',
      });
      this.$router.go(-2);
      // console.log('H5 跳转到 嘉里中心小程序： success');
    },
    launchErrorFn({ errMsg, appId, extInfo }) {
      // console.log('H5 跳转到 嘉里中心小程序： fail', JSON.stringify({ errMsg, appId, extInfo }));
    },
    onLaunchReady() {
      // console.log('H5 跳转到 嘉里中心小程序 的标签 渲染了');
    },
  },
};
