import { Toast } from "vant";
import { mapState } from 'vuex';
import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue';
import { cloneDeep } from 'lodash'
// import uni from '@/utils/uniHooks';
// const app = getApp()
export default {
  components: { uniNumberBox },
  created() {
    // 超限提示
    // this.crossMessage();
  },
  // beforeRouteLeave(to, from, next) {
  //   console.log(251251251251251251, to, from,);
  //   // 设置下一个路由的 meta
  //   to.meta.keepAlive = true; // 让 A 不缓存，即刷新
  //   next();
  // },
  data() {
    return {
      checkedList: [], // 已选优惠列表
      oldCheckedList: [], // 已选优惠列表备份
      isMember: true, // member
      isReduces: true, // reduces
      memberLevelReduce: [],
      memberGrade: {},
      consume: {},
      // todayReduceDiscountMessage: '',
      isMemberDiscountDisabled: false,
      maxDiscountTime: 0,
      enableConsumeSplit: false,
      maxReduceDiscount: 0,
      reduceHours: 0,
      remainPrice: 0,
      isInit: 1,
    };
  },
  computed: {
    ...mapState({
      orderDetail: (state) => state.order.orderDetail,
      custTypeId: (state) => state.custTypeId,
      groupId: (state) => state.groupId,
      enableConsume: (state) => state.order.enableConsume,
      actualPayFee: (state) => state.order.actualPayFee,
      usingTotalDiscount: (state) => state.order.usingTotalDiscount,
      memberLevelDiscount: (state) => state.order.memberLevelDiscount,
      checkedTotal: (state) => state.order.checkedTotal,
      parkMallCode: (state) => state.order.parkMallCode,
      paperDiscountTime: (state) => state.order.paperDiscountTime,
      paperDiscountFee: (state) => state.order.paperDiscountTime,
      availableDiscountFee: (state) => state.order.availableDiscountFee,
    }),
    enableConsumeNonSplit() {
      return this.orderDetail.parkingRule.enableConsumeNonSplit
    },
    stepperMin() {
      // 如果是合集车场，不存在拆分，默认返回用户可使用的消费抵扣时间
      if (this.parkMallCode === 7 || this.enableConsumeNonSplit) {
        return this.reduceHours || 0
      }
      // 如果不存消费减免，默认展示0
      if (JSON.stringify(this.consume) === '{}') {
        return 0
      }
      // 如果存在消费减免并且是可拆分的，则设置最低拆分单位是 1
      return 1
    },
    stepperMax() {
      if (this.parkMallCode === 4 || this.parkMallCode === 6) {
        // 如果存在消费减免并且是可拆分的，则设置最低拆分单位是 1
        return this.maxReduceDiscount
      }
      // 如果是合集车场，不存在拆分，默认返回用户可使用的消费抵扣时间
      if (this.parkMallCode === 7 || this.enableConsumeNonSplit) {
        return this.reduceHours || 0
      }
      // 如果不存消费减免，默认展示0
      if (JSON.stringify(this.consume) === '{}') {
        return 0
      }
      // 如果存在消费减免并且是可拆分的，则设置最低拆分单位是 1
      return this.maxReduceDiscount
    },
    // maxReduceDiscount() {
    //   const {maxOneDayCoupons,maxConsumeTime,maxonedaydiscountFee,maxOneTimeDiscountTime,remainConsumeTime,hourPrice,availableDiscountFee,oneTimeLimitation,oneDayLimitation,maxOneDayDiscountFee} = this.orderDetail.parkingRule;
    //   let newMaxConsumeTime = maxConsumeTime
    //   const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice
    //   console.log(52, this.remainPrice)
    //   if ( this.remainPrice + (newMaxConsumeTime * hourPrice) > maxOneTimeDiscountFee ) {
    //     newMaxConsumeTime = (maxOneTimeDiscountFee - this.remainPrice) / hourPrice
    //   }
    //   return maxConsumeTime
    // },
    // remainPrice() {
    //   let remainPrice = this.usingTotalDiscount
    //   const {maxOneDayCoupons,maxConsumeTime,maxonedaydiscountFee,maxOneTimeDiscountTime,remainConsumeTime,hourPrice,availableDiscountFee,oneTimeLimitation,oneDayLimitation,maxOneDayDiscountFee} = this.orderDetail.parkingRule;
    //   let newMaxConsumeTime = maxConsumeTime
    //   if ( this.checkedList.indexOf('member') > -1) {
    //     remainPrice = remainPrice + this.memberGrade.discountFee
    //   }
    //   if ( this.checkedList.indexOf('reduces') > -1) {
    //
    //   }
    //
    //
    //
    //
    //   return remainPrice
    // }
    // 消费减免(拆分部分)提示文本
    reduceSplitMessage() {
      // console.log(106, this.reduceHours);
      if (!this.enableConsumeNonSplit) {
        return `选择${this.reduceHours}小时，`;
      }
      return '';
    },
    // 消费减免金额
    reducesDiscountFee() {
      return this.reduceHours * this.orderDetail.parkingRule.hourPrice;
    },
    // 消费减免说明文案
    todayReduceDiscountMessage() {
      // 静安浦东没有内容
      if (this.parkMallCode === 0 || this.parkMallCode === 1) {
        return ''
      }
      // 消费减免余额为 0 时
      if (!this.orderDetail.parkingRule.remainConsumeTime || !this.consume.hasOwnProperty('redeemSalesAmount')) {
        return `您暂无可用的消费减免`
        // return `您今日消费减免已达${this.orderDetail.parkingRule.maxConsumeTime}小时上限`
      }
      // 消费减免不存在时
      if (JSON.stringify(this.consume) === '{}') {
        return '消费金额未达到最低优惠要求'
      }

      // 静安存在消费减免时
      if (this.parkMallCode === 0) {
        return `今日可减免${this.consume.defaultDiscountTime}小时`;
      }

      // 沈阳提示信息
      if (this.parkMallCode === 4 || this.parkMallCode === 6) {
        return `未达上限时今日可减免${this.stepperMax}小时`;
      }
      if (this.consume.defaultDiscountTime > this.orderDetail.parkingRule.remainConsumeTime) {
        return `消费已满${this.consume.redeemSalesAmount}元，减免${this.consume.defaultDiscountTime}小时。超出优惠上限，可减免${this.maxReduceDiscount}小时，${this.reduceSplitMessage}可优惠${this.reducesDiscountFee}元`
      }
      return `消费已满${this.consume.redeemSalesAmount}元，减免${this.consume.defaultDiscountTime}小时。${this.reduceSplitMessage}可优惠${this.reducesDiscountFee}元`
    }
  },
  mounted() {
    try {
      this.isCheck(() => this.pageInit()); // 验证是否可选
    } catch (err) {
      // console.log(err);
      this.$router.back();
    }
  },
  watch: {
    remainPrice() {
      const { maxOneDayCoupons, maxonedaydiscountFee, maxOneTimeDiscountTime, remainConsumeTime, hourPrice, oneTimeLimitation, oneDayLimitation, maxOneDayDiscountFee } = this.orderDetail.parkingRule;
      const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice;
      // console.log('hourPrice + this.remainPrice',this.remainPrice)
      // 单日上限
      // if ( oneDayLimitation && this.remainPrice >= maxOneDayDiscountFee ) {
      //   return Toast({
      //     message: `每日最高可抵扣${ maxOneDayDiscountFee }元`,
      //     icon: 'none',
      //   });
      //
      // }
      // 单次上限限制
      if (oneTimeLimitation) {
        if (this.remainPrice <= maxOneTimeDiscountFee) {
          if (this.isMember) {
            this.isMember = !this.isMember;
          }
          if (this.isReduces) {
            this.isReduces = false;
            // console.log(109);
          }
        } else {
          this.isMember = this.checkedList.indexOf('member') < 0;
          this.isReduces = this.checkedList.indexOf('reduces') < 0;
        }
      }
    },
    checkedList(newVal, oldVal) {
      // console.log(190, { newVal, oldVal });
      if ((this.parkMallCode === 4 || this.parkMallCode === 6) && this.isInit > 1) {
        const { maxOneDayCoupons, maxonedaydiscountFee, maxOneTimeDiscountTime, remainConsumeTime, hourPrice, oneTimeLimitation, oneDayLimitation, maxOneDayDiscountFee } = this.orderDetail.parkingRule;
        // 会员等级选中了
        if (newVal.indexOf('member') > -1 && oldVal.indexOf('member') < 0) {
          // console.log(193, '会员等级选中了');
          // this.remainPrice = this.remainPrice + this.memberGrade.discountFee;
          // this.maxReduceDiscountInit();
        }
        if (oldVal.indexOf('member') > -1 && newVal.indexOf('member') < 0) {
          // 会员等级未选中了
          // console.log(193, '会员等级未选中了');
          // this.remainPrice = this.remainPrice - this.memberGrade.discountFee;
          // this.maxReduceDiscountInit();
        }
        // 消费减免选中了
        if (newVal.indexOf('reduces') > -1 && oldVal.indexOf('reduces') < 0) {
          // console.log(193, '消费减免选中了');
          this.consume.discountFee = this.reduceHours * hourPrice
          this.remainPrice = this.remainPrice + this.consume.discountFee;
        }
        if (oldVal.indexOf('reduces') > -1 && newVal.indexOf('reduces') < 0) {
          // 消费减免未选中了
          // console.log(193, '消费减免未选中了');
          this.consume.discountFee = this.reduceHours * hourPrice
          this.remainPrice = this.remainPrice - this.consume.discountFee;
        }
      }
      // const {hourPrice} = this.orderDetail.parkingRule;
      // if ( this.checkedList.indexOf('reduces') > -1 ) {
      //   this.remainPrice = this.reduceHours * hourPrice + this.remainPrice
      // } else {
      //   this.remainPrice = this.remainPrice - this.reduceHours * hourPrice
      // }
    },
  },
  methods: {
    pageInit() {
      if (this.orderDetail?.parkingRule?.enableConsumeSplit) {
        this.enableConsumeSplit = this.orderDetail.parkingRule.enableConsumeSplit;
      }
      this.checkedList = [];
      const { memberGrade = [{}], consume = [], memberLevelDiscount, points = [{}] } = this.orderDetail.discountInfo;
      const { maxConsumeTime, remainConsumeTime, hourPrice } = this.orderDetail.parkingRule;
      // 如果积分存在的话，则移除积分的优惠(天津除外)
      if (JSON.stringify(points) !== {}) {
        this.remainPrice = this.usingTotalDiscount - points[0].discountFee;
      }
      this.memberGrade = { ...memberGrade[0] };
      this.consume = { ...consume[0] };
      if (JSON.stringify(this.memberGrade) !== '{}' && this.memberGrade && this.memberGrade.hasOwnProperty('selected') ? this.memberGrade.selected : this.memberGrade.defaultSelected) {
        this.checkedList.push('member');
      }
      this.isMember = JSON.stringify(this.memberGrade) === '{}';
      // console.log(140, this.consume, this.consume.hasOwnProperty('selected'), JSON.stringify(this.consume) !== '{}' && this.consume.hasOwnProperty('selected') ? this.consume.selected : this.consume.defaultSelected, this.consume.defaultSelected)
      // console.log(143, JSON.stringify(this.consume) !== '{}' && this.consume.hasOwnProperty('selected') ? this.consume.selected !== undefined : this.consume.defaultSelected !== undefined);
      if (JSON.stringify(this.consume) !== '{}' && this.consume.hasOwnProperty('selected') ? this.consume.selected : this.consume.defaultSelected !== undefined) {
        this.checkedList.push('reduces');
        // this.isReduces = false;
        // 如果存在拆分逻辑的话
        // this.consume.
      }
      this.isReduces = this.consume.hasOwnProperty('selected') || this.consume.hasOwnProperty('defaultSelected') ? false : true;
      this.reduceHours = this.consume.hasOwnProperty('discountFee') ? this.consume.discountFee / this.orderDetail.parkingRule.hourPrice : this.consume.defaultDiscountTime;
      if (JSON.stringify(this.consume) !== '{}') {
        const isSelected = this.consume.hasOwnProperty('selected') ? this.consume.selected : this.consume.defaultSelected;
        this.maxReduceDiscount = this.consume.hasOwnProperty('discountFee') ? this.consume.discountFee / hourPrice : this.consume.defaultDiscountTime;
        // const remainingLimitToIncrease = Math.abs(this.remainPrice - this.availableDiscountFee) / hourPrice
        // if (remainingLimitToIncrease) {
        //   this.maxReduceDiscountInit();
        // }
        this.maxReduceDiscountInit();
 
      }
      this.oldCheckedList = [...this.checkedList];
      // 如果是杭州、沈阳可以选择
      // if (this.parkMallCode === 2 || this.parkMallCode === 4 || this.parkMallCode === 7) {
      //   this.isReduces = JSON.stringify(this.consume) === '{}';
      // }
      // https://kerryprops.atlassian.net/browse/SCRM-4016?focusedCommentId=117842: 只要存在消费减免情况，都允许用户进行操作
      this.isReduces = JSON.stringify(this.consume) === '{}';
      this.discountInit()
      setTimeout(() => {
        this.isInit = this.isInit + 1
        
      }, 300)
    },
    discountInit() {
      if(this.parkMallCode === 4 || this.parkMallCode === 6 ) {
        const { maxConsumeTime, remainConsumeTime, hourPrice } = this.orderDetail.parkingRule;
        const remainingLimitToIncrease = Math.abs(this.remainPrice - this.availableDiscountFee) / hourPrice
        if(!remainingLimitToIncrease) {
          this.isMember = this.memberGrade.hasOwnProperty('selected')? !this.memberGrade.selected : !this.memberGrade.defaultSelected
          this.isReduces = this.consume.hasOwnProperty('selected')? !this.consume.selected : !this.consume.defaultSelected
        }
      }
    },
    maxReduceDiscountInit() {
      if(JSON.stringify(this.consume) === '{}' || !this.consume.hasOwnProperty('redeemSalesAmount')) {
        return
      }
      const { maxConsumeTime, remainConsumeTime, hourPrice } = this.orderDetail.parkingRule;
      const remainingLimitToIncrease = Math.abs(this.remainPrice - this.availableDiscountFee) / hourPrice
      if (!remainingLimitToIncrease) {
        // if(!this.consume.selected) {
        //   this.isReduces = true
        // }
        return
      }
      this.isReduces = false
      const {maxDiscountTime} = this.consume
      if (this.remainPrice >= this.availableDiscountFee) {
        // console.log('过大', this.maxReduceDiscount, remainingLimitToIncrease);
        this.maxReduceDiscount = this.maxReduceDiscount - remainingLimitToIncrease > maxDiscountTime ? maxDiscountTime : this.maxReduceDiscount - remainingLimitToIncrease
        this.consume.discountFee = this.consume.discountFee - (remainingLimitToIncrease * hourPrice)
        this.remainPrice = this.remainPrice - (remainingLimitToIncrease * hourPrice);
        this.reduceHours = this.maxReduceDiscount
      }
      if(this.checkedList.indexOf('reduces') < 0) {
        // 如果没被选中
        this.maxReduceDiscount = remainingLimitToIncrease > maxDiscountTime ?  maxDiscountTime : remainingLimitToIncrease
        this.reduceHours = this.maxReduceDiscount
        this.consume.discountFee = remainingLimitToIncrease * hourPrice
        return
      }
      // 如果被选中
      // console.log('过小?', this.consume.discountFee, remainingLimitToIncrease);
        const maxReduceDiscount = this.consume.discountFee / hourPrice + remainingLimitToIncrease
        // console.log('过小', maxReduceDiscount);
        this.maxReduceDiscount = maxReduceDiscount <= remainConsumeTime ? maxReduceDiscount : remainConsumeTime
        this.maxReduceDiscount = this.maxReduceDiscount > maxDiscountTime ? maxDiscountTime: this.maxReduceDiscount
    },
    setIsMemberDiscountDisabled() {
      this.todayReduceDiscountMessage = '当日';
    },
    checkboxChange() { },
    onReduceHoursChange(type) {
      if (this.checkedList.indexOf('reduces') < 0) {
        return;
      }
      const { maxOneDayCoupons, maxonedaydiscountFee, maxOneTimeDiscountTime, remainConsumeTime, hourPrice, availableDiscountFee, oneTimeLimitation, oneDayLimitation, maxOneDayDiscountFee } = this.orderDetail.parkingRule;
      // console.log(133,this.reduceHours)
      // console.log(166, this.maxReduceDiscount);
      if (type === 'plus') {
        const [isCrossMessage = false, maxReduceDiscount = this.maxReduceDiscount] = this.crossMessage('onReduceHoursChange');
        if (isCrossMessage) {
          // this.remainPrice = this.remainPrice - hourPrice;
          // this.reduceHours = this.reduceHours - 1;
          return
        }
        this.remainPrice = this.remainPrice + hourPrice;
        this.reduceHours = this.reduceHours + 1;
        this.consume.discountFee = this.reduceHours * hourPrice
        return;
      }
      if (type === 'minus' && this.reduceHours > 1) {
        this.reduceHours = this.reduceHours - 1;
        this.remainPrice = this.remainPrice - hourPrice;
        this.consume.discountFee = this.reduceHours * hourPrice
        return;
      }
    },
    memberClick() {
      // debugger
      const { maxConsumeTime, remainConsumeTime, availableDiscountFee, hourPrice } = this.orderDetail.parkingRule;
      if (this.checkedList.indexOf('member') > -1) {
        this.remainPrice = this.memberGrade.discountFee + this.remainPrice;
        // console.log(331, this.remainPrice);
        // 沈阳
        if (this.parkMallCode === 4 || this.parkMallCode === 6) {
          // console.log(322);
          this.maxReduceDiscountInit();
        }
      } else if (!this.isMember) {
        this.remainPrice = this.remainPrice - this.memberGrade.discountFee;
        // 如果不是沈阳，重新计算优惠
        if (this.parkMallCode !== 4 && this.parkMallCode !== 6) {
          this.maxReduceDiscount = remainConsumeTime;
        }
        // 如果不是沈阳，重新计算优惠
        if (this.parkMallCode === 4 || this.parkMallCode === 6) {
          this.maxReduceDiscountInit();
        }
      }
      // 如果不是沈阳
      if (this.parkMallCode !== 4 && this.parkMallCode !== 6) {
        const [isCrossMessage = false, maxReduceDiscount = this.maxReduceDiscount] = this.crossMessage();
        if (isCrossMessage) {
          this.checkedList = this.checkedList.filter((elm) => elm !== 'member');
          this.remainPrice = this.remainPrice - this.memberGrade.discountFee;
          this.isMember = false;
        }
      }
    },
    reducesClick() {
      const { maxOneTimeDiscountTime, hourPrice, oneTimeLimitation, maxConsumeTime, remainConsumeTime, oneDayLimitation, maxOneDayDiscountFee, availableDiscountFee } = this.orderDetail.parkingRule;
      const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice;
      if (this.checkedList.indexOf('reduces') > -1) {
        // this.remainPrice = hourPrice + this.remainPrice;
        // 如果不是沈阳，重新计算计算最大上限
        if (this.parkMallCode !== 4 && this.parkMallCode !== 6) {
          this.remainPrice = hourPrice + this.remainPrice;
          this.maxReduceDiscount = remainConsumeTime > maxOneTimeDiscountFee / hourPrice ? maxOneTimeDiscountFee / hourPrice : remainConsumeTime;
        }
      } else {
        // this.remainPrice = this.remainPrice - hourPrice;
        // 如果不是沈阳，重新计算计算最大上限
        if (this.parkMallCode !== 4 && this.parkMallCode !== 6) {
          this.remainPrice = this.remainPrice - hourPrice;
          this.maxReduceDiscount = remainConsumeTime > maxOneTimeDiscountFee / hourPrice ? maxOneTimeDiscountFee / hourPrice : remainConsumeTime;
        }
      }
      if (this.parkMallCode !== 4 && this.parkMallCode !== 6) {
        const [isCrossMessage = false, maxReduceDiscount = 0] = this.crossMessage();
        if (isCrossMessage) {
          this.remainPrice = this.remainPrice - maxReduceDiscount * hourPrice;
        }
      }
    },
    // 超限提示
    crossMessage(type) {
      const { maxOneTimeDiscountTime, hourPrice, oneTimeLimitation, oneDayLimitation, maxOneDayDiscountFee } = this.orderDetail.parkingRule;
      const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice;
      // console.log(373, this.remainPrice, this.availableDiscountFee);
      // 单日上限
      if (oneDayLimitation && this.remainPrice >= this.availableDiscountFee) {

        Toast({
          message: `每日最高可抵扣${maxOneDayDiscountFee}元`,
          icon: 'none',
        });
        return [true, (maxOneDayDiscountFee - (this.reduceHours - 1) * hourPrice) / hourPrice];
      }
      // 单次上限限制
      if (oneTimeLimitation && this.remainPrice >= maxOneTimeDiscountFee) {
        Toast({
          message: `超出抵扣上限,每次最高可抵扣${maxOneTimeDiscountTime}小时`,
          icon: 'none',
        });
        // return [true,( maxOneTimeDiscountFee - (this.reduceHours - 1) * hourPrice ) / hourPrice]
        return [true, (this.remainPrice - maxOneTimeDiscountFee) / hourPrice];
      }
      return [false, 0];
    },
    // 验证当前的选项是否可选择
    isCheck(callback) {
      if (!this?.orderDetail?.parkingRule) {
        return;
      }
      // const {parkInfo,parkingRule,discountInfo} = this.orderDetail
      const { maxOneTimeDiscountTime, maxOneDayDiscountFee, oneTimeLimitation, oneDayLimitation, hourPrice, remainConsumeTime } = this.orderDetail.parkingRule;
      // 浦东
      if (this.parkMallCode === 1) {
        const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice;
        const remainConsumeTimeFee = remainConsumeTime * hourPrice;

        // TODO: 统计纸质优惠券的总金额， usingTotalDiscount，才是用户当前订单使用的优惠总数
        this.isMember = !(this.usingTotalDiscount < (oneTimeLimitation ? maxOneTimeDiscountFee : maxOneDayDiscountFee) && this.memberLevelDiscount);
        this.isReduces = !(this.usingTotalDiscount < (oneTimeLimitation ? maxOneTimeDiscountFee : maxOneDayDiscountFee) && this.enableConsume);
      }
      if (callback) callback();
    },
    reducesChange(value) {
      // console.log(149,value)
    },
    async confirm() {
      let orderDetail = cloneDeep(this.orderDetail);
      // 如果初次进来操作的跟原来的不一样则重新计算优惠
      if (this.checkedList.length !== this.checkedTotal || true) {
        ['member', 'reduces'].forEach((key) => {
          if (key === 'member') {
            this.memberGrade = {
              ...this.memberGrade,
              selected: this.checkedList.indexOf(key) > -1,
            };
            orderDetail.discountInfo.memberGrade = [this.memberGrade];
          }
          if (key === 'reduces') {
            this.consume = {
              ...this.consume,
              discountTime: this.reduceHours,
              discountFee: this.reduceHours * this.orderDetail.parkingRule.hourPrice,
              selected: this.checkedList.indexOf(key) > -1,
            };
            orderDetail.discountInfo.consume = [this.consume];
          }
        });
        await this.$store.dispatch('order/saveDiscounts', { orderDetail, callback: () => this.$router.back() });
      } else {
        this.$router.back();
      }
    },
  },
};
