import moment from 'moment';
import { mapState } from 'vuex';
import log from '@/utils/log.js';
import { compare } from '@/utils/location.js';
import uni from '@/utils/uniHooks';
import { initWxJsSdkConfig } from '@/utils/login';
import { getAppIdByGroupIdAndMallId, getIsWxh5, getPlatform, isAlipay } from '@/utils';
import { Dialog, Toast } from 'vant';
import { ordersAndPrepay } from '@/api/parking';
// import checkOutResponse from '@/api/mockData/checkout.hz.response'

export default {
  name: 'parkingFeeDetail',
  data() {
    return {
      hasDiscount: false,
      parkFee: {},
      refreshTime: 180, // 停车场重置费用倒计时3分钟
      // 微服务接口字段
      isShowDescription: true, // 缴费说明true:显示全部 false:显示部分
      btnLoading: false,
      isPay: false,
      popup: false,
      msData: {},
    };
  },
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    if (/index|home/.test(to.name)) {
      // 不在缓存列表中，从cachedViews缓存列表中移除
      this.$store.commit('cachedViews/DEL_CACHED_VIEW', from);
    }
    next();
  },
  created() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '停车支付',
      });
    }, 300);
    setTimeout(() => {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#FBFCFF',
        },
      });
    }, 500)
    setTimeout(() => {
      this.pageInit();
    }, 300)
  },
  
  computed: {
    ...mapState({
      orderDetail: (state) => state.order.orderDetail,
      discountDesc: (state) => state.order.discountDesc,
      enableNewMemberPoints: (state) => state.order.enableNewMemberPoints,
      enablePoints: (state) => state.order.enablePoints,
      integralDesc: (state) => state.order.integralDesc,
      enableCoupon: (state) => state.order.enableCoupon,
      maxOneDayCoupons: (state) => state.order.maxOneDayCoupons,
      coupons: (state) => state.order.coupons,
      couponDesc: (state) => state.order.couponDesc,
      enablePaperCoupons: (state) => state.order.enablePaperCoupons,
      custTypeId: (state) => state.custTypeId,
      usingTotalDiscount: (state) => state.order.usingTotalDiscount,
      actualPayFee: (state) => state.order.actualPayFee,
      available: (state) => state.order.available,
      member: (state) => state.member,
      maxPointsTime: (state) => state.order.maxPointsTime,
      pointsTime: (state) => state.order.pointsTime,
      pointsPerHour: (state) => state.order.pointsPerHour,
      usePoints: (state) => state.order.usePoints,
      usePointsTime: (state) => state.order.usePointsTime,
      enableConsume: (state) => state.order.enableConsume,
      memberLevelDiscount: (state) => state.order.memberLevelDiscount,
      unitAmount: (state) => state.order.unitAmount,
      unlicensedInfo: state => state.unlicensedInfo,
      endlessLoop: (state) => state.endlessLoop,
      appId: state => state.appId,
      source: state => state.source,
      parkMallCode: (state) => state.order.parkMallCode,
    }),
    isNoLogin() {
      return JSON.stringify(this.member) === '{}' || !this.member
    },
    // 支付按钮状态
    payBtnDisabled() {
      // 当存在待支付金额 或者 用户登陆
      return !this.orderDetail?.parkingRecord?.totalFeeInYuan || (JSON.stringify(this.member) !== '{}' && !this.orderDetail.parkInfo);
    },
    // integralDesc() {
    //   if (this.pointsTime > 0) {
    //     // 深圳特殊处理(单位:金额)
    //     if (this.orderDetail.parkInfo.parkMallCode === 5 || this.orderDetail.parkInfo.parkMallCode === 999) {
    //       return `已选择兑换${this.pointsTime}元`;
    //     }
    //     return `已选择兑换${this.pointsTime}小时`;
    //   }
    //   if (this.bonusCopy < this.integral) {
    //     return `${this.integral}积分可停车1小时`;
    //   }
    //   if (this.orderDetail.parkInfo.parkMallCode === 3 && app.globalData.member?.currnentintegral >= this.integral && !this.bonus) {
    //     return `今日已达上限`;
    //   }
    //   return `${this.available}积分可减免`;
    // },
  },
  filters: {
    parkingTime(val) {
      const days = parseInt(val / 60 / 24)
      const hours = parseInt((val / 60) % 24)
      const minutes = parseInt(val % 60)
      if (days > 0) {
        return `${days}天 ${hours}小时 ${minutes}分钟`
      }
      if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`
      }
      return `${minutes}分钟`
    },
  },
  methods: {
    // 前往支付
    async toPay() {
      if (this.btnLoading) return
      this.btnLoading = true
      setTimeout(() => {
        if ( this.btnLoading && !this.isPay ) {
          const toast1 = Toast({
            message: '网络连接失败，请重试',
            duration: 3000,
            onClose: () => {
              this.$router.replace({
                // path: 'parkingFeeSuccess?carno=' + this.parkInfo.carno,
                path: 'home',
              });
            }
          });
          this.btnLoading = false
        }
      }, 10000)
      const { parkingRecord, discountInfo = {}, parkingRule = {}} = this.orderDetail;
      const { coupons, points, memberGrade = [], paperCoupons = [], consume = [] } = discountInfo
      const { hourPrice } = parkingRule
      try {
        const params = {
          // vehicleNo: '', // 车牌号
          // points
          parkingRecord: {
            ...parkingRecord,
            vehicleNo: parkingRecord.vehicleNo,
            enterTime: parkingRecord.enterTime,
            serviceMin: parkingRecord.serviceMin,
            totalFee: parkingRecord.totalFeeInYuan, //应缴
            actualPayFee: this.actualPayFee, //应付金额
          },
          discountInfo: {
            usingTotalDiscount: discountInfo?.usingTotalDiscount || 0, //优惠金额"
            actualUsedDiscount: discountInfo?.usingTotalDiscount || 0, //实际优惠金额
          },
        };
        // 会员等级减免
        if ( memberGrade?.length && memberGrade[0].discountFee > 0 && memberGrade[0].hasOwnProperty('selected')? memberGrade[0]?.selected : memberGrade[0]?.defaultSelected) {
          const selected = memberGrade[0].hasOwnProperty('selected') ? memberGrade[0].selected : memberGrade[0].defaultSelected;
          let discountTime = 0
          let discountFee = 0
          if(selected) {
            discountTime = memberGrade[0].hasOwnProperty('discountTime') ? memberGrade[0].discountTime : memberGrade[0].defaultDiscountTime;
            discountFee = memberGrade[0].hasOwnProperty('discountFee') ? memberGrade[0].discountFee : discountTime * hourPrice;
          }
          params.discountInfo.memberLevel = {
            "discountTime": discountTime * 60, // 小时转成分钟
            "discountFee": discountFee,
            "memberGrade": memberGrade[0].memberGrade
          }
        }
        // 消费减免
        if ( consume?.length && consume[0].discountFee > 0 && consume[0].hasOwnProperty('selected')? consume[0]?.selected : consume[0]?.defaultSelected) {
          const { redeemSalesAmount, defaultDiscountTime} = consume[0]
          const selected = consume[0].hasOwnProperty('selected') ? consume[0].selected : consume[0].defaultSelected;
          let discountTime = 0
          let discountFee = 0
          if(selected) {
            discountFee = consume[0].hasOwnProperty('discountFee') ? consume[0].discountFee : memberGrade[0].defaultDiscountTime * hourPrice;
            discountTime = discountFee / hourPrice * 60;
          }
          params.discountInfo.consume = {
            ...consume[0],
            "defaultSelected": selected,
            "discountTime": discountTime,
            "discountFee": discountFee,
            "redeemSalesAmount": (this.parkMallCode === 4 || this.parkMallCode === 6) ? (redeemSalesAmount / defaultDiscountTime) * ( discountFee / hourPrice) : redeemSalesAmount
          }
        }
        
        // 积分
        if (points?.length && points[0].discountFee > 0) {
          // 15 兑换 5元
          const { pointsPerUnit, unitAmount, discountFee, available } = points[0]
          params.discountInfo.points = {
            "discountTime": discountFee / hourPrice * 60,
            "discountFee": discountFee,
            "discountPoints": discountFee / hourPrice * pointsPerUnit
          }
        }
        // 优惠券
        if (coupons?.length) {
          const selectedCoupons = coupons.filter(elm => {
            const selected = elm.hasOwnProperty('selected') ? elm.selected : elm.defaultSelected;
            return selected
          }).map(elm => {
            elm.discountTime = elm.discountFee / hourPrice * 60
            return elm
          })
          if (selectedCoupons.length) {
            params.discountInfo.coupons = selectedCoupons
          }
        }
        // 纸质优惠券
        if ( paperCoupons?.length ) {
            params.discountInfo.paperCoupons = paperCoupons.filter(elm => {
              if ( !elm.discountFee ) {
                return false
              }
              return {
                ...elm,
                "discountFee": elm.discountFee,
                // discountTime: elm.discountFee / hourPrice * 60
              }
            })
         }
        console.log('下单时的参数', params);
        const res = await ordersAndPrepay(params);
        // console.log('orderDetail', res);
        if (res?.paymentType === 'NO_FEE_PAY') {
          this.btnLoading = false;
          this.isPay = false
          this.$router.replace({
            path: this.getPagePath(),
          });
          // 支付成功
          return
        }
        this.kerryPayment(res.sessionId);
      } catch (err) {
        if(err ==='ERR_NETWORK') {
          setTimeout(() => {
            this.$router.replace({
              // path: 'parkingFeeSuccess?carno=' + this.parkInfo.carno,
              path: 'home',
            });  
          }, 2900)
        } else {
          this.btnLoading = false
          this.isPay = false
        }
        console.log(err);
      }
    },
    kerryPayment(session = '011cad54-735f-4e92-8f1b-f22bdfe073cd', payParams) {
      const platform = getPlatform();
      console.log('platform:::', platform)
      let appId = uni.getStorageSync('appid');
      let openId = uni.getStorageSync('openid') || this.openid;
      if (platform === 'miniprogram') {
        // appId = 'wx92c3e55fbef6b2af';
        // appId = 'wxd830fe4d1e04988e';
        appId = this.appId;
      }
      console.log('支付宝::', isAlipay())
      const params = {
        region: 'cn',
        payChannel: isAlipay() ? 'MINI_PROGRAM' : 'OFFICIAL_ACCOUNT',
        // payChannel: 'MOBILE_WEB',

        payOption: isAlipay() ? 'ALIPAY' : 'WECHATPAY',
        appId: appId,
        // openId: 'oudWQ5SCDElfn-IQH6eBR5JesOz4', // 下的appid： wxd830fe4d1e04988e
        openId,
      };
      // console.log(1854, params);
      this.$md(params);
      // let path = `/profileApi/payment/v1/services/session/${session}/transactions`;
      let path = `${window.profileApi}/payment/v1/services/session/${session}/transactions`;
      this.$request({
        url: path,
        data: params,
        method: 'POST',
        header: JSON.parse(uni.getStorageSync('handleUser')),
      })
        .then(async (res) => {
          // this.Toastloading.clear();
          // console.log(1795, res);
          if (res.data?.code == '000000') {
            const prepayJson = res.data.data.params;
            console.log('prepayJson::', res.data)
            const platform = getPlatform();
            this.isPay = true
            // TODO: h5环境判断
            if (platform === 'micromessenger') {
              const weixinH5PayRes = await this.weixinH5Pay(prepayJson);
              // 微信支付完成，判断结果
              console.log(1784, weixinH5PayRes);
              //  errMsg: 'requestPayment:ok'
              if (weixinH5PayRes?.errMsg === 'requestPayment:ok') {
                this.btnLoading = false
                this.isPay = false
                this.$store.commit('cachedViews/DEL_CACHED_VIEW', {
                  name: 'parkingFeeDetail'
                });
                this.$router.replace({
                  // path: 'parkingFeeSuccess?carno=' + this.parkInfo.carno,
                  path: this.getPagePath(),
                });
              } else {
                this.reCreateParkOrder();
              }
            } else {
              let options = {}
              if (isAlipay()) {
                options = {
                  provider: 'alipay',
                  orderInfo: prepayJson.trade_no,
                }
              } else {
                options = {
                  provider: 'wxpay',
                  timeStamp: prepayJson.timeStamp,
                  nonceStr: prepayJson.nonceStr,
                  package: prepayJson.package,
                  signType: prepayJson.signType,
                  paySign: prepayJson.paySign,
                }
              }
              window.toWXSendMsg({
                type: 'openWxPay',
                options: options,
              });
              window.subscribe('wxPayOver', (options) => {
                // this.Toastloading.clear();
                // console.log('微信支付结束之后的返回参数', options);
                // T-ODO: 在 qa 新发版前，只提示支付成功的信息(已处理成功信息)
                if (options?.wxPayOver === 'fail') {
                  console.log('支付失败');
                  this.reCreateParkOrder();
                } else {
                  this.btnLoading = false;
                  this.isPay = false
                  this.$router.replace({
                    // path: 'parkingFeeSuccess?vehicleNo=' + this.$route.query.vehicleNo,
                    path: this.getPagePath(),
                  });
                }
              });
            }
          } else {
            this.reCreateParkOrder();
          }
        })
        .catch((err) => {
          if(err.code === "ERR_NETWORK") {
            this.btnLoading = true;
            uni.showToast({ title: '网络连接失败，请重试', duration: 3000, icon: 'fail' });
            setTimeout(() => {
              this.$router.replace({
                // path: 'parkingFeeSuccess?carno=' + this.parkInfo.carno,
                path: 'home',
              });
            }, 2900)
            return
          }
          this.reCreateParkOrder();
        });
    },
    // 支付失败后返还优惠券
    failedParkOrder() {
      // this.Toastloading.clear();
      const param = {
        orderno: this.parkInfo.orderno,
      };
      this.$md(param);
      uni
        .request({
          url: this.$baseURL + 'api/1.0/park/failedParkOrder',
          data: param,
          method: 'POST',
          header: JSON.parse(uni.getStorageSync('handleUser')),
        })
        .then((res) => {
          this.reCreateParkOrder();
        })
        .catch((err) => {
          this.reCreateParkOrder();
        });
    },
    // 支付失败弹框 重新创建订单
    reCreateParkOrder() {
      // console.log('支付失败弹框 重新创建订单');
      Dialog.alert({
        title: '提示',
        message: '支付失败',
        confirmButtonColor: '#333',
      }).then(() => {
        this.$refs.countDown.reset(); // 停车场重置费用倒计时3分钟
        this.$store.dispatch('order/orderInit', {
          gateId: this.$route.query?.gateId,
          vehicleNo: this.$route.query?.vehicleNo,
          endlessLoop: this.endlessLoop
        })
        this.btnLoading = false;
        this.isPay = false
        // this.createParkOrder();
      });
      // uni.showModal({
      //   showCancel: false,
      //   title: '提示',
      //   content: '支付失败',
      //   complete: (r) => {
      //     this.createParkOrder();
      //   },
      // });
    },
    // 初始化
    async pageInit() {
      // console.log(247, checkOutResponse);
      // this.msData.detail = checkOutResponse
      // 停车优惠
      // this.discounts(this.msData.detail)
      // 积分减免
      // 优惠券
      // 纸质优惠券
      // 优惠金额
      // 应付金额
      // this.$store.commit('order/SET_ORDER_DETAIL', checkOutResponse);
      try {
        console.log('无牌车扫码出场', this.unlicensedInfo, this.endlessLoop);
        this.btnLoading = false
        this.isPay = false
        // return
        this.$store.dispatch('order/orderInit', {
          vehicleNo: this.$route.query.vehicleNo,
          gateId: this.$route.query?.gateId,
          endlessLoop: this.endlessLoop,
          callback: (res) => {
            setTimeout(() => {
              this.$store.dispatch('clearUnlicensed');
            }, 700);
            // 如果 无牌车扫码出场扫码 无需缴费，直接展示无需缴费页面
            if(/unlicensedOut/.test(res.code) && res?.unlicensed) {
              this.$router.replace({
                path: 'parkingFeeMsg?type=pay',
              });
              return
            }
            // 如果是无需缴费的话,提示用户无需缴费
            if (res?.orderDetail?.parkingRecord?.totalFee <= 0) {
              this.$store.dispatch('order/orderInitRule', res.orderDetail);
                setTimeout(() => {
                  Dialog.alert({
                    message: '当前无需缴费',
                    confirmButtonColor: '#333',
                  }).then(() => {
                    this.$router.back()
                  });
                }, 1000)
              return
            }
            if ( /CAR_NOT_FOUND|INOUT_FAILED/.test(res.code) ) {
              setTimeout(() => {
                this.$router.replace({
                  path: 'parkingFeeMsg',
                  query: {
                    type: 'outFail'
                  }
                })  
              }, 300)
              return;
            }
            if (/NOT_FOUND|PARKING_RECORD_NOT_FOUND/.test(res.code)) {
              // 当前车辆没有查到账单
              this.$router.replace({
                path: 'parkingFeePayment',
                query: {
                  msg: res.langMessage,
                  vehicleNo: this.$route.query.vehicleNo,
                },
              });
              return
            }
            if (/LOCAL_PARK_ERROR|INTERNAL_SERVER_ERROR|VALIDATION_FAILED|PLEASE_SCAN_QRCODE/g.test(res.code)) {
              setTimeout(() => {
                this.$router.back()
              }, 3000)
            }
          }
        });
        setTimeout(() => {
          this.$store.dispatch('clearUnlicensed');
        }, 1200);
      } catch (err) {
        console.log('查询车辆是否在场的报错信息?', err, err.code === "INTERNAL_SERVER_ERROR");
        // 如果网络异常（这里是因为订单页面存在空白场景，才需要单独处理报错交互）
        if (err.code === "INTERNAL_SERVER_ERROR") {
          this.$router.back()
        }
      }
    },
    // 停车优惠
    discounts() {
      // totalFee 为零的时候不做跳转
      if (this.orderDetail.parkingRecord.totalFeeInYuan === 0) return;
      if (!this.enableConsume && !this.memberLevelDiscount && this.orderDetail.parkInfo.parkMallCode !== 2) {
        return Toast({
          message: '暂无可用优惠',
        });
      }
      if( this.discountDesc !== '暂无可用优惠') {
        this.$router.push({
          path: 'parkingFeeDiscounts',
        });
      }
    },
    setColor() {
      window?.toWXSendMsg({
        type: 'uni_func',
        funcName: 'setNavigationBarColor',
        options: {
          frontColor: '#000000',
          backgroundColor: '#2151C5',
        },
      });
      // uni.setNavigationBarColor({
      //   frontColor: '#000000',
      //   backgroundColor: '#FAFBFF',
      // });
    },
    // 是否展示优惠信息
    // isShowDiscounts(params) {
    //   console.log(277, params?.parkingRule?.enableCoupon);
    //   return params?.parkingRule?.enableCoupon
    // },
    //
    // 计算优惠信息
    discountssss(params) {
      // console.log(275, params);
      // console.log(275, params.discountInfo);
      // console.log(275, params.discountInfo.consume);
      return 1;
    },
    coupon() {
      // totalFee 为零的时候不做跳转
      if (this.orderDetail.parkingRecord.totalFeeInYuan === 0) return;
      // 如果没有电子券的话，提示用户
      if (this.coupons.length === 0 && this.source !== 'KIP') {
        uni.showToast({
          title: '暂无可使用的优惠券，请前往积分商城兑换优惠券'
        })
        return
      }
      this.$router.push({
        path: 'parkingFeeCoupon',
      });
    },
    paperCoupon() {
      // totalFee 为零的时候不做跳转
      if (this.orderDetail.parkingRecord.totalFeeInYuan === 0) return;
      this.$router.push({
        path: 'parkingFeePaperCoupon',
        query:{
          vehicleNo: this.$route.query.vehicleNo
        }
      });
    },
    duration() { },
    couponCount() { },
    // 重置倒计时
    resetCountDown() {
      this.$refs?.countDown?.reset();
      this.btnLoading = false;
      this.isPay = false
      this.$store.dispatch('order/orderInit', {
        gateId: this.$route.query?.gateId,
        vehicleNo: this.$route.query?.vehicleNo,
        endlessLoop: this.endlessLoop
      })
      // 重新创建订单
      // this.createParkOrder();
    },
    //缴费说明隐藏显示
    togglePayinstruction() {
      this.isShowDescription = !this.isShowDescription;
    },
    // 积分修改框
    showPointsMathPopup() {
      // totalFee 为零的时候不做跳转
      if (this.orderDetail.parkingRecord.totalFeeInYuan === 0) return;
      if(this.integralDesc === '暂无可用积分'){
        return
      }
      this.popup = true;
    },
    cancelPointsMathPopup() {
      this.$store.dispatch('order/cancelPointsMath', () => {
        this.popup = false;
      });
    },
    savePointsMathPopup() {
      this.$store.dispatch('order/savePointsMath', () => {
        this.popup = false;
      });
    },
    // 获取成功缴费之后前往的页面
    getPagePath() {
      let pagePath = 'parkingFeeSuccess?vehicleNo=' + this.$route.query.vehicleNo
      console.log('临时车流程', this.endlessLoop);
      if (this.$route.query.vehicleNo.indexOf('临') > -1 && this.endlessLoop || this.$route.query.gateId) {
        pagePath = 'parkingFeeMsg?type=pay'
      }
      return pagePath
    },
    pointsMathCallback({type, message}) {
      // console.log(465, type);
      Toast({
        message: message,
        icon: 'none',
      });
    },
    // 
    setDescription() {
      if ( this?.orderDetail?.parkInfo?.description.length > 0 ) {
        let reg = /[;；]/g;
        return this.orderDetail.parkInfo.description.replace(reg, '\r\n').replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>');  
      } 
       return ''
    }
  },
};
