import { checkOut,calculateDiscount,ordersAndPrepay,currentUnlicensedPlate,unlicensedCarCheckIn,unlicensedCarCheckout } from '@/api/parking';
import { setSelected } from './utils'

export default {

  // 积分相关计算(仅计算用户可使用的积分)
  pointsRule( {commit,dispatch,state},checkOutResponse ) {
    const {discountInfo,parkingRule,parkInfo} = checkOutResponse
    const {
      points,
      usingTotalDiscount, // 当前车辆的已使用优惠的总上限
    } = discountInfo;
    const {
      parkMallCode
    } = parkInfo
    const {
      maxPointsTime = 0, // 最大积分
      enablePoints,
      availableDiscountFee,
      unLimitWeekendPoints = false,
      maxOneDayDiscountFee, // 每日最大优惠金额(深圳车场)
      remainConsumeTime, // 当前订单剩余可使用的优惠
    } = parkingRule;
    commit('setEnablePoints',enablePoints);
    if ( !points ) return commit('setIntegralDesc','暂无可用积分'); // 积分优惠处的描述
    const [
      {
        pointsPerHour,
        available, // 用户可用的积分（当前车辆在） available是用户选择抵扣N小时后剩余的可用积分
        maxDiscountFee, // 单次上限（元）
        unitAmount, // 兑换值（元）
        unlimitUsePoints= "LIMIT", // 前海积分最大上限
        unitHour, // 兑换值（小时）
        pointsPerUnit = 0, // 500积分对应的价值
        discountFee,
        label,
      },
    ] = points;
    commit('setAvailableDiscountFee',availableDiscountFee);
    dispatch('maxPointsTimeMath',checkOutResponse) // 剩余积分可兑换上限
    
    commit('setAvailable',available);
    commit('setMaxPointsTime',maxPointsTime);
    commit('setMaxDiscountFee',maxDiscountFee);
    let pointsTime = 0
    // 深圳
    if ( parkMallCode === 5 ) {
      pointsTime = discountFee || 0
    } else  {
      pointsTime = discountFee ?  discountFee / unitAmount: 0
    }
    commit('setPointsTime',pointsTime);
    commit('setPointsPerUnit',pointsPerUnit);
    commit('setMaxOneDayDiscountFee',maxOneDayDiscountFee);
    commit('setPointsPerHour',pointsPerUnit);
    commit('setUnitAmount',unitAmount);
    commit('setUnlimitUsePoints', unlimitUsePoints);
    commit('setUnLimitWeekendPoints', unLimitWeekendPoints);
    commit('setUnitHour', unitHour);
    commit('setIntegralDesc',pointsTime ? `已选择兑换${ pointsTime }${parkMallCode === 5 ? '元' : '小时'}` : available > pointsPerUnit ? `${ available }积分可减免` : `${ pointsPerUnit }积分可停车1小时`); // 积分优惠处的描述
  },
  // 当前最大可选优惠时间
  /*
   * 当前最大可选优惠时间
   * 1、不能超过积分上限
   * 2、
   * */
  maxPointsTimeMath( {commit,dispatch,state},checkOutResponse ) {
    const {discountInfo,parkingRule,parkInfo} = checkOutResponse
    const {
      points: [{
        available, // 用户可用的积分（当前车辆在） available是用户选择抵扣N小时后剩余的可用积分
        unitAmount, // 兑换值（元）
        pointsPerUnit = 0, // 500 积分对应的价值
        discountFee,
        maxDiscountFee,
      }]
    } = discountInfo
    const {
      parkMallCode
    } = parkInfo
    // 总积分
    const max = available / pointsPerUnit * unitAmount;
    const timeNum = maxDiscountFee / unitAmount;
    console.log(';999988888;',timeNum);

    /**
     * maxDiscountFee 单次最大可使用金额
     * availableDiscountFee 当日剩余可使用优惠金额
     * available 当前用户的剩余积分，也可以说是可以抵扣的积分，如果有积分抵扣自动勾选，那么这个值=这个值-已勾选积分
     *
     */

    // if ( !state.maxPointsTime ) {
    //   commit('setMaxPointsTime', discountFee || max)
    // }
    // if (
    //   parkInfo.parkMallCode === 3 &&
    //   enablePoints && !maxPointsTime
    // ) {
    //   return commit('setIntegralDesc', `今日已达上限`);
    // }
    // return commit('setIntegralDesc', `${available}积分可减免`);
  },
  // 积分减免
  pointsMath( {commit,dispatch,state},{type,callback} ) {
    const {parkInfo,parkingRule,parkingRecord} = state.orderDetail
    const {maxOneTimeDiscountTime,oneTimeLimitation,oneDayLimitation,hourPrice,remainConsumeTime, maxOneDayDiscountFee} = parkingRule
    const {parkMallCode} = parkInfo
    console.log(376,maxOneTimeDiscountTime,state.availableDiscountFee)
    /**
     * maxDiscountFee 单次最大可使用金额
     * availableDiscountFee 当日剩余可使用优惠金额
     * available 当前用户的剩余积分，也可以说是可以抵扣的积分，如果有积分抵扣自动勾选，那么这个值=这个值-已勾选积分
     */
      // 计算用户当前的最大可使用积分的总数（单位：元）
    let maxPointsTime = state.available / ( state.pointsPerUnit / state.unitAmount ) + state.pointsTime;
    if ( maxPointsTime > state.maxDiscountFee ) {
      maxPointsTime = state.maxDiscountFee
    }
    let msg = ''
    // 验证最大积分的总数（单位：元）
    if ( maxPointsTime > state.availableDiscountFee ) {
      maxPointsTime = state.availableDiscountFee
    }
    // if ( parkMallCode === 5 && state.unlimitUsePoints === 'LIMIT' ) {
    if ( parkMallCode === 5 && !state.unLimitWeekendPoints ) {
      if ( type === 'add' && (state.pointsTime >= maxPointsTime || state.usingTotalDiscount >= state.availableDiscountFee) ) {
        // 以下是深圳积分上限规则
        // 超出抵扣上限,每日最高可抵扣${this.parkFee.parkInfoEntity.maxOneDayHour}元 '优惠金额' >= '每日最高可抵扣'
        // if ( state.usingTotalDiscount >= state.availableDiscountFee && !msg ) {
        //   msg = `超出抵扣上限,每日最高可抵扣${ state.maxOneDayDiscountFee }元`
        // }
        // 超出抵扣上限,每次最高可抵扣${this.integralMaxMoney}元 '积分兑换时长' >= '深圳前海停车积分上限'q
        if ( state.pointsTime >= state.maxDiscountFee && !msg ) {
          msg = `超出抵扣上限,每次最高可抵扣${ state.maxDiscountFee }元`
        }
      }
    }
    // 单日上限限制
    if ( oneDayLimitation && !msg && parkMallCode !== 5 && parkMallCode !== 4 && parkMallCode !== 2 && type === 'add') {
      // const maxOneTimeDiscountFee = maxOneDayDiscountFee
      // const remainConsumeTimeFee = remainConsumeTime * hourPrice
      // 计算单日剩余 remainConsumeTime
      // 当前使用优惠 state.usingTotalDiscount
      // 判断符合上限
      // 浦东积分上限判断
      if ( (parkMallCode === 1 && state.usingTotalDiscount >= maxOneDayDiscountFee) 
      || (parkMallCode === 6 && state.usingTotalDiscount >= state.availableDiscountFee ) ) {
        msg = `超出抵扣上限,每次最高可抵扣${ maxOneDayDiscountFee }元`
      }
    }
    // 单次上限限制
    if ( oneTimeLimitation && !msg && parkMallCode !== 5 && parkMallCode !== 4 && parkMallCode !== 2 && type === 'add') {
      const maxOneTimeDiscountFee = maxOneTimeDiscountTime * hourPrice // 计算时间对应的金额
      // const remainConsumeTimeFee = remainConsumeTime * hourPrice
      // 计算单日剩余 remainConsumeTime
      // 当前使用优惠 state.usingTotalDiscount
      // 判断符合上限
      // 浦东积分上限判断: 减去纸质优惠券的金额
      if ( (parkMallCode === 1 && state.usingTotalDiscount >= maxOneTimeDiscountFee) || (parkMallCode === 6 && state.usingTotalDiscount >= state.availableDiscountFee) ) {
        msg = `超出抵扣上限,每次最高可抵扣${ maxOneTimeDiscountTime }小时`
      }
    }
    if ( msg ) {
      callback({
        message: msg
      });
      return
    }
    // 计算浦东的上限
    // if ( type === 'add' && state.usingTotalDiscount >= state.availableDiscountFee && parkMallCode === 5 && state.unlimitUsePoints === 'LIMIT') {
    // if ( type === 'add' && state.usingTotalDiscount >= state.availableDiscountFee && parkMallCode === 5 && !state.unLimitWeekendPoints) {
    //   return;
    // }
    // 如果天津的积分参与的抵扣金额大于等于当前车辆的总的停车费用，则阻止用户继续使用积分
    // if(parkMallCode === 6 && state?.usingTotalDiscount>= parkingRecord?.totalFeeInYuan) {
    //   return
    // }
    if ( type === 'add' ) {
      // 如果天津的积分参与的抵扣金额大于等于当前车辆的总的停车费用，则阻止用户继续使用积分
      // if(parkMallCode === 6 && state?.usingTotalDiscount>= parkingRecord?.totalFeeInYuan) {
      //   return
      // }
      let pointsTime = 0;
      pointsTime = state.pointsTime + (parkMallCode === 5 ? state.unitAmount : state.unitHour);
      const available = state.available - state.pointsPerUnit;
      const usingTotalDiscount = state.usingTotalDiscount + (state?.unitHour ? state.unitHour * hourPrice : state.unitAmount); // 重新计算已经使用的优惠逻辑
      if ( available > -1 ) {
        // 如果是深圳车场
        commit('setAvailable',available);
        commit('setPointsTime',pointsTime);
        commit('setUsingTotalDiscount',usingTotalDiscount);
      }
    }
    if ( type === 'minus' && state.pointsTime > 0 ) {
      const pointsTime = state.pointsTime - (parkMallCode === 5 ? state.unitAmount : state.unitHour);
      const usingTotalDiscount = state.usingTotalDiscount - (state?.unitHour ? state.unitHour * hourPrice : state.unitAmount); // 重新计算已经使用的优惠逻辑
      // 如果是深圳车场
      commit('setAvailable',state.available + state.pointsPerUnit);
      commit('setPointsTime',pointsTime);
      commit('setUsingTotalDiscount',usingTotalDiscount);
    }
  },
  cancelPointsMath( {commit,dispatch,state},callback ) {
    const {
      discountInfo: {points},
      parkInfo: {parkMallCode},
      parkingRule,
    } = state.orderDetail;
    const [{pointsPerHour,available,discountFee, unitAmount}] = points;
    const {maxPointsTime,enablePoints} = parkingRule;
    if ( !points ) {
      callback && callback();
      return
    }
    let pointsTime = 0
    // 深圳
    if ( parkMallCode === 5 ) {
      pointsTime = discountFee || 0
    } else  {
      pointsTime = discountFee ?  discountFee / unitAmount : 0
    }
    commit('setAvailable',available);
    commit('setPointsTime',pointsTime || 0);
    callback && callback();
  },
  async savePointsMath( {commit,dispatch,state},callback ) {
    try {
      let orderDetail = {...state.orderDetail};

      const {parkInfo,parkingRule} = state.orderDetail
      const {maxOneTimeDiscountTime,oneTimeLimitation,oneDayLimitation,hourPrice,remainConsumeTime} = parkingRule
      const {parkMallCode} = parkInfo
      // 如果是重复提交，则不做重新计算
      if ( orderDetail.discountInfo.points[0].available === state.available ) {
        callback && callback();
        return
      }
      // 如果是会员等级减免\如果是消费减免\如果是纸质优惠券\电子券的话
      setSelected(['memberGrade','consume','paperCoupons','coupons'],orderDetail)
      // 计算积分修改之后的金额，返回给后端
      // orderDetail.discountInfo.points[0].discountFee = state.pointsTime * orderDetail.discountInfo.points[0].unitAmount;
      orderDetail.discountInfo.points[0].discountFee = parkMallCode === 5 ? state.pointsTime : state.pointsTime * orderDetail.discountInfo.points[0].unitAmount;
      orderDetail.discountInfo.points[0].available = state.available;
      orderDetail.discountInfo.points[0].selected = true;
      /* 其他优惠统计 */
      // 优惠券: 如果没有添加 selected 字段，则增加 selected; 默认取 defaultSelected；
      if ( orderDetail?.discountInfo?.hasOwnProperty('coupons') && !orderDetail?.discountInfo?.coupons[0]?.hasOwnProperty('selected') ) {
        orderDetail.discountInfo.coupons = orderDetail.discountInfo.coupons.map(elm => {
          elm.selected = elm.defaultSelected || false;
          return elm;
        })
      }
      const res = await calculateDiscount({
        ...orderDetail,
      });
      console.log('积分修改失败',{res});
      dispatch('orderInitRule',res);
      callback && callback();
    } catch ( err ) {
      console.log('积分修改失败！',err);
      callback && callback();
    }
    //
  },

  getIntegralDesc() {
    // 自动勾选积分优惠
    // 深圳是最大抵扣金额
    // available
    /*
     if (this.duration > 0) {
     // 深圳特殊处理(单位:金额)
     if (this.parkMallCode === 5) {
     return `已选择兑换${this.duration}元`;
     }
     return `已选择兑换${this.duration}小时`;
     }
     if (this.bonusCopy < this.integral) {
     return `${this.integral}积分可停车1小时`;
     }
     if (
     this.parkMallCode === 3 &&
     this.member?.currnentintegral >= this.integral &&
     !this.bonus
     ) {
     return `今日已达上限`;
     }
     return `${this.bonus}积分可减免`;
     */
  },
}