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, // 剩余可用优惠额度
    };
  },
  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, // 当前已使用优惠
    }),
  },

  mounted() {
    console.log('parkingFeeCoupon.js');
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '优惠券',
      });
      if (isInWeixinH5()) {
        initWxJsSdkConfig(['checkJsApi', 'chooseImage'], ['wx-open-launch-weapp']);
        // this.launchPathInit();
      }
    }, 300);
    this.pageInit();
  },
  methods: {
    pageInit() {
      /*
       * 电子优惠券初始化逻辑(后端处理)
       *
       * 1、每次change之后，需要重新计算每个电子优惠券的逻辑
       * 2、superposition  叠加使用规则 （1不可叠加，2仅同类型可叠加，3可叠加）;
       * */
      this.couponList = [...this.coupons];
      this.remainPrice = this.usingTotalDiscount * 1;
      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;
          });
        }
        // 验证剩余优惠券是否可勾选(无需验证：后端已计算可勾选的优惠券)
      }
    },
    item2Number(i) {
      return Number.parseInt(i.replace(/coupon/g, ''));
    },
    checkboxItemChange(name, index) {
      // 取消勾选时
      if (this.checkedCouponList.indexOf(name) > -1) {
        this.checkedCouponList = this.checkedCouponList.filter((i) => i !== name);
        setTimeout(() => {
          // console.log(158, this.checkedCouponList);
          // this.groupedCouponData();
          this.remainPrice = this.remainPrice - this.couponList[index].discountFee
          this.newGroupedCouponData()
        }, 100)
        return;
      }
      // 如果有选中项
      const item = this.couponList[index];
      this.remainPrice = this.remainPrice + this.couponList[index].discountFee
      if (!item.disabled) {
        this.checkedCouponList.push(`coupon${index}`);
        setTimeout(() => {
          // 根据电子券规则判断是否可选
          this.isDisabledByRule(item, index);
        }, 100)
      }
    },
    // 对不同类型的优惠券进行汇总统计
    groupedCouponData() {
      const groupedData = {}; // 所有的电子券按照批次分组；
      let couponList = [...this.couponList]; // 获取目前用户的电子券
      couponList.forEach((elm, index) => {
        // 初始化数据
        const elmName = `coupon${index}`;
        const newElm = { ...elm };
        if (!groupedData[elm.name] || !groupedData[elm.name].hasOwnProperty('noSelectedList')) {
          groupedData[newElm.name] = {
            noSelectedList: [], // 未选择的
            selectedList: [], // 已选择的
          }
        }
        newElm.index = index; // 记录每张电子券的顺序
        // 所有的电子券按照 已选择 和 未选择的分组，存储到同批次下
        if (this.checkedCouponList.indexOf(elmName) > -1) {
          newElm.selected = true;
          groupedData[newElm.name]['selectedList'].push(newElm)
        } else {
          newElm.selected = false;
          groupedData[newElm.name]['noSelectedList'].push(newElm)
        }
      })
      // 对分好组的优惠券进行不同规则处理
      Object.keys(groupedData).forEach(key => {
        const { selectedList, noSelectedList } = groupedData[key]; // 取出已选择的和未选择的
        const { superposition, limitCountPerOrder = 0 } = [...selectedList, ...noSelectedList][0]; // 获取当前批次兑换的类型和可选上限
        switch (superposition) {
          case '1': // 不可叠加
            couponList = couponList.map((item, index) => {
              const elmName = `coupon${index}`;
              // 如果是不可叠加的电子优惠券，设置未选中的为不可选择
              if (item?.superposition === '1') {
                if (selectedList.length) {// 如果存在已选择项，设置未选中的为不可选择
                  item.disabled = this.checkedCouponList.indexOf(elmName) < 0;
                  /* 
                  TODO: 如果不可叠加电子券的选择规则改变为，选中某一项不可叠加券，其他券不可选择，则打开此处注释
                  if (item.superposition === '2') {
                    item.disabled = selectedList.length > 0
                  } */
                } else {
                  item.disabled = this.checkedCouponList.length > 0;
                }
              }
              /* 
              // TODO: 如果不可叠加电子券的选择规则改变为，选中某一项不可叠加券，其他券不可选择，则打开此处注释
              // 如果存在已选的电子优惠券，将其他类型的优惠券设置为不可选中
              if ( item.superposition === '2' && selectedList.length) {
                item.disabled = true
              } */
              return item
            })
            break
          case '2':
            // 统计未选择项是否需要禁用
            noSelectedList.forEach(elm => {
              const _elm = { ...couponList[elm.index] };
              couponList = couponList.map((item, index) => {
                if (index === elm.index && limitCountPerOrder > 0) {
                  // elm.disabled = selectedList.length >= limitCountPerOrder;
                  _elm.disabled = selectedList.length >= limitCountPerOrder;
                  return _elm
                }
                return item
              })
            })
            break
        }
      })
      this.couponList = [...couponList];
    },
    // 对不同类型的优惠券进行汇总统计
    newGroupedCouponData() {
      let couponList = [...this.couponList]; // 获取目前用户的电子券
      if (!this.checkedCouponList.length) {
        this.couponList = couponList.map(elm => {
          elm.disabled = false
          return elm;
        })
        return
      }
      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) => {
            elm.disabled = false; // 默认可选
            const elmName = `coupon${i}`;
            if (elm.name === name) {
              if (limitCountPerOrder) { // 是否存在上限
                if (this.checkedCouponList.length >= limitCountPerOrder) {
                  elm.disabled = this.checkedCouponList.indexOf(elmName) < 0
                }
              }
            } else {
              elm.disabled = true; // 非同批次的优惠券设置为不可选择
            }
            return elm
          })
          break;
      }
      console.log(282, couponList);
      this.couponList = [...couponList];
    },
    // 根据电子券规则判断是否可选
    isDisabledByRule(item) {
      const { parkMallCode } = this.orderDetail.parkInfo;
      // 杭州电子券使用上限(单位: 张)
      /*if (this.parkMallCode === 2) {
       // 达到上限
       if (
       this.checkedCouponList.length ===
       this.parkFee.parkInfoEntity.useTicketNum -
       this.parkFee.parkInfoEntity.couponcodeNum
       ) {
       this.list.forEach((e, i) => {
       if (this.checkedCouponList.findIndex((c) => c == i) === -1) {
       e.disabled = true;
       } else {
       e.checked = true;
       }
       });
       return uni.showToast({
       title: `电子券每天最多可使用${this.parkFee.parkInfoEntity.useTicketNum}张`,
       icon: "none",
       });
       } else {
       this.list.forEach((e) => {
       e.disabled = false;
       });
       }
       }*/

      // 浦东每次缴费超限控制、沈阳每日超限控制
      if ((parkMallCode === 1 || parkMallCode === 4 || parkMallCode === 5 || parkMallCode === 999 || parkMallCode === 6) && this.crossMessage()) {
        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() {
      const { parkMallCode } = this.orderDetail.parkInfo;
      const { maxOneDayCoupons, maxonedaydiscountFee, remainConsumeTime, hourPrice, availableDiscountFee } = this.orderDetail.parkingRule;
      const {
        usingTotalDiscount, // 使用总抵扣
        coupons,
      } = this.orderDetail.discountInfo;
      const {
        // totalFee, // 应缴
        actualPayFee, // 应付金额
      } = this.orderDetail.parkingRecord;
      // 剩余可使用的优惠金额，支持动态计算; 优惠时长，不可能全部使用，不能超过车费减去优惠的金额;不能超过单次的应付金额
      let remainPrice = remainConsumeTime * hourPrice;
      if (remainPrice > actualPayFee) {
        remainPrice = actualPayFee;
      }
      // let totalFee = this.parkDiscountTotal.feeCopy;
      // totalFee += this.totalFee;
      // 电子券优惠金额总计
      // 浦东每次优惠上限
      /*if (
       parkMallCode === 1 &&
       totalFee - this.paperCouponFee >= this.maxonetimediscountFee
       ) {
       //  uni.showToast({
       //   title: `超出抵扣上限,每次最高可抵扣${this.parkFee.parkInfoEntity.maxonetimediscount}小时`,
       //   icon: 'none',
       // });
       return Toast({
       message: `超出抵扣上限,每次最高可抵扣${this.parkFee.parkInfoEntity.maxonetimediscount}小时`,
       icon: 'none',
       });
       return;
       }*/
      // 沈阳超限处理(maxonedaydiscountFee 会员、消费、电子券减免)
      /*if (
       parkMallCode === 4 &&
       totalFee - this.paperCouponFee - this.parkDiscountTotal.bonusfee >=
       this.maxonedaydiscountFee
       ) {
       return Toast({
       message: `(会员等级、消费、电子券)每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}小时`,
       icon: 'none',
       });
       // return uni.showToast({
       //   title: `(会员等级、消费、电子券)每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}小时`,
       //   icon: 'none',
       // });
       }*/
      // 深圳超限处理
      if (parkMallCode === 5 && this.remainPrice  > actualPayFee) {
        return Toast({
          message: `每日最高可抵扣${this.remainPrice}元`,
          icon: 'none',
        });
      }
    },
    // 确认
    confirm() {
      console.log(336, this.checkedCouponList);
      // 重新计算兑换券优惠
      const checkedCouponList = this.checkedCouponList.map((i) => this.item2Number(i));
      console.log(checkedCouponList);
      const couponList = this.couponList.map((elm, index) => {
        elm.selected = false;
        console.log(checkedCouponList, index);
        if (this.checkedCouponList.indexOf(`coupon${index}`) > -1) {
          elm.selected = true;
        }
        return elm;
      });
      console.log(348, couponList);
      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`;
    },
    // 跳转小程序
    navigateToMiniProgram() {
      if (this.platform === 'miniprogram') {
        // const { projectId } = getAppIdByGroupIdAndMallId({
        //   groupId: this.$route.params.groupId,
        //   mallId: this.$route.params.mallId,
        //   type: 'all',
        // });
        // this.launchPathInit();
        window.toWXSendMsg({
          type: 'navigateToMiniProgram',
          options: {
            launchPath: this.launchPath,
          },
        });
        // 订阅微信小程序端的回调
        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 跳转到 嘉里中心小程序 的标签 渲染了');
    },
  },
};
