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

// import checkOutQHResponse from '@/api/mockData/checkout.qh3.response.json'
// import checkOutQHResponse from '@/api/mockData/checkout.hz.response.json';
// import checkOutQHResponse from '@/api/mockData/checkout.qh5  .response.json'
// import unlicensedCarCheckInResponse from '@/api/mockData/unlicensedCarCheckIn.qh.response.json';

// 大于等于停车费
// 微服务接口字段
const state = {
  // 微服务接口字段
  orderDetail: {}, // 订单原始数据
  isShowDiscounts: false, // 是否展示会员登记优惠
  discountDesc: '', // 停车优惠(首停、会员减免、消费减免)
  checkedTotal: 0, // 选中count数
  enableNewMemberPoints: false, // 是否开启新会员积分
  enablePoints: false, // 是否开启积分减免
  usePoints: 0, // 用户已选择的积分
  isFirst: 0, // 判断用户是否首次进入
  integralDesc: '', // 积分减免说明文案
  pointsPerHour: 0, // 每小时兑换积分
  enableCoupon: false, // 电子优惠券是否启用
  maxOneDayCoupons: 0, // 单日可选优惠券上限
  coupons: [], // 可选优惠券数量
  couponCount: 0, // 已选择优惠券
  couponDesc: '', // 优惠券说明文案
  enablePaperCoupons: false, // 启动纸质优惠券
  usingTotalDiscount: 0, // 优惠金额
  actualPayFee: 0, // 应付金额
  availableDiscountFee: 0, // 当日剩余可使用优惠金额
  // 积分相关
  available: 0, // 用户可用积分
  maxPointsTime: '', // 积分最大兑换时长
  pointsTime: '', // 已兑换的积分时间
  unitAmount: 0,
  // 停车优惠：会员等级和消费减免
  memberLevelDiscount: false, // 是否开启会员等级
  enableConsume: false, // 是否开启消费减免
  pointsPerUnit: 0, //
  // unlicensed: false // true: 临时车牌；false：普通车牌
  // 无牌车逻辑
  unlicensedCar: '',
};

const mutations = {
  setOrderDetail(state, payload) {
    state.orderDetail = payload;
  },
  setIsShowDiscounts(state, payload) {
    state.isShowDiscounts = payload;
  },
  setCheckedTotal(state, payload) {
    state.checkedTotal = payload;
  },
  setDiscountDesc(state, payload) {
    state.discountDesc = payload;
  },
  setEnableNewMemberPoints(state, payload) {
    state.enableNewMemberPoints = payload;
  },
  setEnablePoints(state, payload) {
    state.enablePoints = payload;
  },
  setIsFirst(state, payload) {
    state.isFirst = payload;
  },
  setIntegralDesc(state, payload) {
    state.integralDesc = payload;
  },
  setUsePoints(state, payload) {
    state.usePoints = payload;
  },
  setEnableCoupon(state, payload) {
    state.enableCoupon = payload;
  },
  setMaxOneDayCoupons(state, payload) {
    state.maxOneDayCoupons = payload;
  },
  setCoupons(state, payload) {
    state.coupons = payload;
  },
  setCouponCount(state, payload) {
    state.couponCount = payload;
  },
  setCouponDesc(state, payload) {
    state.couponDesc = payload;
  },
  setEnablePaperCoupons(state, payload) {
    state.enablePaperCoupons = payload;
  },
  setUsingTotalDiscount(state, payload) {
    state.usingTotalDiscount = payload;
  },
  setActualPayFee(state, payload) {
    state.actualPayFee = payload;
  },
  setAvailableDiscountFee(state, payload) {
    state.availableDiscountFee = payload;
  },
  setPointsPerHour(state, payload) {
    state.pointsPerHour = payload;
  },
  setAvailable(state, payload) {
    state.available = payload;
  },
  setMaxPointsTime(state, payload) {
    state.maxPointsTime = payload;
  },
  setPointsTime(state, payload) {
    state.pointsTime = payload;
  },
  setEnableConsume(state, payload) {
    state.enableConsume = payload;
  },
  setMemberLevelDiscount(state, payload) {
    state.memberLevelDiscount = payload;
  },
  setPointsPerUnit(state, payload) {
    state.pointsPerUnit = payload;
  },
  setMaxOneDayDiscountFee(state, payload) {
    state.maxOneDayDiscountFee = payload;
  },
  setUnitAmount(state, payload) {
    state.unitAmount = payload;
  },
  setMaxDiscountFee(state, payload) {
    state.maxDiscountFee = payload;
  },
  setUnlicensedCar(state, payload) {
    state.unlicensedCar = payload;
  },
};

const actions = {
  /**
   * 车辆订单的缴费信息初始化
   * @param {*} param0
   * @param {*} param1.gateId  车场闸机口ID
   * @param {*} param1.vehicleNo  车牌号（包含临牌）
   * @param {*} param1.callback  回调函数，用于接口报错时，展示对应的信息
   * @param {*} param1.endlessLoop 用于判断当前用户是否扫码进入 
   */
  async orderInit({ commit, dispatch, state }, { gateId='124p3LK1', vehicleNo = '浙A616A1', callback, endlessLoop }) {
    try {
      const unlicensed = vehicleNo.indexOf('临') > -1; // true: 临时车牌；false：普通车牌
      // const res = await checkOut('浙A616A1');
      // const res = await checkOut('闽AAQ5519', unlicensed);
      // const res = await checkOut('粤A51113');
      // const res = await checkOut('沪DCJ986');
      // console.log('无牌车扫码出场', endlessLoop);
      // 场内缴费，调 check-out 接口，
      const method = unlicensed && endlessLoop ? unlicensedCarCheckout : checkOut
      const res = await method(vehicleNo, false, gateId);
      // console.log(vehicleNo, res);
      // 所有的优惠时间长转为金额
      // console.log(112, '所有的优惠时间长转为金额');
      // dispatch('orderInitRule', checkOutQHResponse);
      dispatch('orderInitRule', res);
    } catch (error) {
      // console.log('151151151151151', error);
      /* if (/NOT_FOUND|PARKING_RECORD_NOT_FOUND/.test(error.code)) {
        callback && callback(error)
      } */
      callback && callback(error); // 统一处理错误原因
    }
  },
  orderInitRule({ commit, dispatch, state }, checkOutResponse) {
    console.log(119, checkOutResponse);
    // 记录buildingId
    window.localStorage.setItem('buildingId', checkOutResponse.parkInfo.buildingId);
    commit('setOrderDetail', checkOutResponse);
    const isShowDiscounts = checkOutResponse?.parkingRule?.enableCoupon || false;
    // 是否展示优惠
    commit('setIsShowDiscounts', isShowDiscounts);
    if(isShowDiscounts) {
      // 会员等级减免
      // 停车优惠(首停、会员减免、消费减免)
      dispatch('getCheckedTotal', checkOutResponse);
      // 是否开启新会员积分(hold)
      commit('setEnableNewMemberPoints', checkOutResponse.parkingRule.enableNewMemberPoints);
      // 积分减免
      dispatch('pointsRule', checkOutResponse);
      // dispatch('getIntegralDesc', checkOutResponse.parkingRule.enablePoints);
      // 电子优惠券：是否启用
      // 处理电子优惠券相关逻辑
      dispatch('couponRule', checkOutResponse);
      // 纸质优惠券(hold)
      commit('setEnablePaperCoupons', checkOutResponse?.parkingRule?.enablePaperCoupons || []);
      // 其他数据收集
      commit('setUsingTotalDiscount', checkOutResponse?.discountInfo?.usingTotalDiscount || 0);
    }
    console.log('190190190190', checkOutResponse);
    commit('setActualPayFee', checkOutResponse.parkingRecord?.actualPayFee || checkOutResponse.parkingRecord?.totalFeeInYuan || 0.00);
  },
  // 停车优惠(首停、会员减免、消费减免)
  getCheckedTotal({ commit, dispatch }, orderDetail) {
    let checkedTotal = 0;
    console.log(orderDetail);
    if (orderDetail?.discountInfo?.memberLevelDiscount && orderDetail?.discountInfo?.memberGrade.length) {
      orderDetail.discountInfo.memberGrade.forEach((elm) => {
        if (elm.defaultSelected) {
          checkedTotal++;
        }
      });
    }
    if (orderDetail?.discountInfo?.consume?.length) {
      orderDetail.discountInfo.consume.forEach((elm) => {
        if (elm.defaultSelected) {
          checkedTotal++;
        }
      });
    }
    commit('setMemberLevelDiscount', orderDetail.discountInfo.memberLevelDiscount);
    commit('setCheckedTotal', checkedTotal);
    dispatch('getDiscountDesc', {
      orderDetail,
      checkedTotal,
    });
  },
  getDiscountDesc({ commit, dispatch }, { orderDetail, checkedTotal }) {
    if (orderDetail.parkingRule.enableConsume) {
      commit('setEnableConsume', orderDetail.parkingRule.enableConsume);
      if (checkedTotal > 0) {
        return commit('setDiscountDesc', `已选择${checkedTotal}项优惠`);
      }
      return commit('setDiscountDesc', `立即使用`);
    } else {
      return commit('setDiscountDesc', `暂无可用优惠`);
    }
  },
  // 积分相关计算(仅计算用户可使用的积分)
  pointsRule({ commit, dispatch, state }, checkOutResponse) {
    const { discountInfo, parkingRule, parkInfo } = checkOutResponse
    const {
      points,
      usingTotalDiscount, // 当前车辆的已使用优惠的总上限
    } = discountInfo;
    const {
      maxPointsTime = 0, // 最大积分
      enablePoints,
      availableDiscountFee,
      maxOneDayDiscountFee, // 每日最大优惠金额(深圳车场)
      remainConsumeTime, // 当前订单剩余可使用的优惠
    } = parkingRule;
    const [
      {
        pointsPerHour,
        available, // 用户可用的积分（当前车辆在） available是用户选择抵扣N小时后剩余的可用积分
        maxDiscountFee, // 单次上限（元）
        unitAmount, // 兑换值（元）
        pointsPerUnit = 0, // 500积分对应的价值
        discountFee,
        label,
      },
    ] = points;
    commit('setAvailableDiscountFee', availableDiscountFee);
    dispatch('maxPointsTimeMath', checkOutResponse) // 剩余积分可兑换上限
    commit('setEnablePoints', enablePoints);
    commit('setAvailable', available);
    commit('setMaxPointsTime', maxPointsTime);
    commit('setMaxDiscountFee', maxDiscountFee);
    commit('setPointsTime', discountFee || 0);
    commit('setPointsPerUnit', pointsPerUnit);
    commit('setMaxOneDayDiscountFee', maxOneDayDiscountFee);
    commit('setPointsPerHour', pointsPerUnit);
    commit('setUnitAmount', unitAmount);
    commit('setIntegralDesc', label);
  },
  // 当前最大可选优惠时间
  /*
   * 当前最大可选优惠时间
   * 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 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 }) {
    /**
     * maxDiscountFee 单次最大可使用金额 
     * availableDiscountFee 当日剩余可使用优惠金额
     * available 当前用户的剩余积分，也可以说是可以抵扣的积分，如果有积分抵扣自动勾选，那么这个值=这个值-已勾选积分
     */

    // console.log('289289289289289289289289', state.available / (state.pointsPerUnit / state.unitAmount) + state.pointsTime);
    // 计算用户当前的最大可使用积分的总数（单位：元）
    let maxPointsTime = state.available / (state.pointsPerUnit / state.unitAmount) + state.pointsTime;
    if (maxPointsTime > state.maxDiscountFee) {
      maxPointsTime = state.maxDiscountFee
    }
    // 验证最大积分的总数（单位：元）
    if (maxPointsTime > state.availableDiscountFee) {
      maxPointsTime = state.availableDiscountFee
    }
    console.log(303, maxPointsTime);
    if (type === 'add' && state.pointsTime < maxPointsTime) {
      const pointsTime = state.pointsTime + state.unitAmount;
      // 如果是深圳车场
      commit('setAvailable', state.available - state.pointsPerUnit);
      commit('setPointsTime', pointsTime);
    }
    if (type === 'minus' && state.pointsTime > 0) {
      const pointsTime = state.pointsTime - state.unitAmount;
      // 如果是深圳车场
      commit('setAvailable', state.available + state.pointsPerUnit);
      commit('setPointsTime', pointsTime);
    }
  },
  cancelPointsMath({ commit, dispatch, state }, callback) {
    const {
      discountInfo: { points },
      parkingRule,
    } = state.orderDetail;
    const [{ pointsPerHour, available, discountFee }] = points;
    const { maxPointsTime, enablePoints } = parkingRule;
    commit('setAvailable', available);
    commit('setPointsTime', discountFee || 0);
    callback && callback();
  },
  async savePointsMath({ commit, dispatch, state }, callback) {
    try {
      const orderDetail = { ...state.orderDetail };
      // 如果是重复提交，则不做重新计算
      if (orderDetail.discountInfo.points[0].available === state.available) {
        callback && callback();
        return
      }
      // 计算积分修改之后的金额，返回给后端
      // orderDetail.discountInfo.points[0].discountFee = state.pointsTime * orderDetail.discountInfo.points[0].unitAmount;
      orderDetail.discountInfo.points[0].discountFee = state.pointsTime;
      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();
    }
    //
  },
  async saveCouponMath({ commit, dispatch, state }, { couponList, callback }) {
    const orderDetail = { ...state.orderDetail };
    orderDetail.discountInfo.coupons = couponList;
    if (orderDetail?.discountInfo?.points[0]?.discountFee) {
      orderDetail.discountInfo.points[0].selected = true;
    } else {
      orderDetail.discountInfo.points[0].selected = false;
    }
    try {
      const res = await calculateDiscount({
        ...orderDetail,
      });
      dispatch('orderInitRule', res);
      callback && callback();
    } catch (err) {
      console.log('积分修改失败！', err);
      callback && callback();
    }
    // commit('setCoupons', checkOutResponse.discountInfo.coupons);
  },
  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}积分可减免`;
    */
  },
  // 电子优惠券
  couponRule({ commit, dispatch, state }, checkOutResponse) {
    commit('setEnableCoupon', checkOutResponse.parkingRule.enableCoupon);
    if (checkOutResponse.parkingRule.enableCoupon) {
      // const {maxOneDayCoupons, remainConsumeTime, hourPrice} = checkOutResponse.parkingRule;
      // const {
      //   usingTotalDiscount, // 使用总抵扣
      //   coupons
      // } = checkOutResponse.discountInfo;
      // const {
      //   totalFee, // 应缴
      //   actualPayFee // 应付金额
      // } = checkOutResponse.parkingRecord;
      // // 剩余可使用的优惠金额，支持动态计算; 优惠时长，不可能全部使用，不能超过车费减去优惠的金额;不能超过单次的应付金额
      // let remainPrice = remainConsumeTime * hourPrice;
      // if ( remainPrice > actualPayFee ) {
      //   remainPrice = actualPayFee;
      // }
      // let couponPrice = 0
      // // 确认优惠券是否可选择
      // let couponsList = coupons.sort((itema,itemb) => itema.discountFee - itemb.discountFee)
      // couponsList = couponsList.map(elm => {
      //   if ( !elm.defaultSelected ) {
      //     if ( elm.discountFee <=  remainPrice && couponPrice <= remainPrice) {
      //       elm.disabled = false
      //     } else {
      //       elm.disabled = true
      //     }
      //   }
      // })
      // console.log(343, {couponsList});
      // commit('setCoupons', couponsList);
      commit('setMaxOneDayCoupons', checkOutResponse.parkingRule.maxOneDayCoupons); // 仅在杭州使用
      commit('setCoupons', checkOutResponse.discountInfo.coupons);
      // 统计已选择优惠券
      let couponCount = 0;
      checkOutResponse.discountInfo.coupons.forEach((elm) => {
        const selected = elm.hasOwnProperty('selected') ? elm.selected : elm.defaultSelected;
        if (selected) {
          couponCount++;
        }
      });
      commit('setCouponCount', couponCount);
      if (couponCount > 0) {
        return commit('setCouponDesc', `已选择${couponCount}张优惠劵`);
      } else {
        if (checkOutResponse.discountInfo.coupons.length) {
          return commit('setCouponDesc', `您有${checkOutResponse.discountInfo.coupons.length}张可用优惠劵`);
        }
        return commit('setCouponDesc', `暂无可用优惠券`);
      }
    }
  },

  // 无牌车逻辑
  async unlicensedRule({ commit, dispatch, state }, callback) {
    try {
      // const res = await currentUnlicensedPlate(); // 无牌车查询
      // const res = await unlicensedCarCheckIn({gateId: 1}); // 无牌车入场
      /**
       * CAR_NOT_FOUND 车场扫描道闸入口，发现无车
       * CAR_HAS_PLATE 车场扫描道闸入口，发现有牌车
       */
      // const res = unlicensedCarCheckInResponse;
      const res = await currentUnlicensedPlate();
      console.log('无牌车的查询记录', res);
      commit('setUnlicensedCar', res.vehicleNo);
      // 如果是扫码进入的用户，在出场时需要重新扫码，这时会在此处传入的一个回调函数，在获取到临牌时，返回给 qrCodesRule 函数
      if(res.vehicleNo && callback) {
        callback(res.vehicleNo);
      }
    } catch (err) {
      console.log(err);
    }
  }

  // 是否展示优惠
  // getIsShowDiscounts({commit, dispatch}, orderDetail) {
  //   params?.parkingRule?.enableCoupon
  // }
  // calculateDiscount

  /*
   如果积分发生变化
   */
};

export default {
  //开启命名模块
  namespaced: true,
  state,
  mutations,
  actions,
};
