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

export default {
  // 电子优惠券
  couponRule( {commit,dispatch,state},checkOutResponse ) {
    commit('setEnableCoupon',checkOutResponse.parkingRule.enableCoupon);
    if ( checkOutResponse.parkingRule.enableCoupon ) {
      commit('setMaxOneDayCoupons',checkOutResponse.parkingRule.maxOneDayCoupons); // 仅在杭州使用
      commit('setRemainCoupons',checkOutResponse.parkingRule.remainCoupons); // 仅在杭州使用
      // 根据时间排序电子兑换券
      const couponSort = ( a,b ) => {
        let aTime = new Date(`${ a.expirationDate }`.replace(/-/g,'/'));
        let bTime = new Date(`${ b.expirationDate }`.replace(/-/g,'/'));
        let aN = aTime.getTime(aTime) // 方法1
        let bN = bTime.getTime(bTime) // 方法2
        return aN - bN;
      }
      if ( checkOutResponse?.discountInfo?.coupons?.length ) {
        const coupons = checkOutResponse.discountInfo.coupons.sort(couponSort)
        commit('setCoupons',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 }张优惠劵`);
        }
        if ( checkOutResponse.discountInfo.coupons.length ) {
          return commit('setCouponDesc',`您有${ checkOutResponse.discountInfo.coupons.length }张可用优惠劵`);
        }  
      }
      commit('setCouponDesc',`暂无可用优惠券`);
    } else {
      commit('setCouponDesc',`暂无可用优惠券`);
    }
  },
  async saveCouponMath( {commit,dispatch,state},{couponList,callback} ) {
    const orderDetail = {...state.orderDetail};
    orderDetail.discountInfo.coupons = couponList;
    setSelected(['paperCoupons','consume','points','memberGrade'],orderDetail)
    try {
      const res = await calculateDiscount({
        ...orderDetail,
      });
      dispatch('orderInitRule',res);
      callback && callback();
    } catch ( err ) {
      console.log('积分修改失败！',err);
      callback && callback();
    }
  },
}