/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

import Wechat from './wechat.js'
import util from '@/utils/util.js'
import * as Constant from '@/utils/constant'

const paySettlementType = uni.getStorageSync('cloudPaySettlementType')

export default {
  /**
   * 订单支付
   * @param {Number} payType 支付类型;见util/constant.js
   * @param {String} orderIds 订单编号
   * @param {Boolean} isPurePoints 是否纯积分订单(积分+钱订单与普通订单一致)
   * @param {Boolean} dvyType // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
   * @param {Number/String} orderType 订单类型 1团购 2秒杀
   * @param {Number} payEntry 支付入口 0商城订单 1余额充值 2购买vip
   * @param {Boolean} isFinalPayment 是否是尾款
   */
  // eslint-disable-next-line max-lines-per-function
  toOrderPay ({ payType, orderIds, isPurePoints, dvyType, orderType, payEntry, isFinalPayment = false }) {
    // 使用promise获取通联的订单号（非通联不调用resolve回调）
    // eslint-disable-next-line max-lines-per-function
    return new Promise((resolve) => {
      const paymemtObj = { payType, orderIds, isPurePoints, dvyType, orderType, payEntry }
      payType = Number(payType)
      isPurePoints = Number(isPurePoints)
      let redirectUrl = payEntry === Constant.PayEntry.RECHARGE ? '/package-activities/pages/my-balance/my-balance' : payEntry === Constant.PayEntry.VIP ? '/package-activities/pages/member-center/member-center' : '/package-user/pages/order/order?orderStatus=0'
      // #ifdef H5
      const { protocol, host, pathname } = window.location
      const pathnameArr = pathname.split('/')
      const base = pathnameArr[1] === 'package-activities' || pathnameArr[1] === 'pages' ? '' : '/' + pathnameArr[1]
      if (payEntry === Constant.PayEntry.RECHARGE) {
        redirectUrl = `${protocol}//${host}${base}` + '/package-activities/pages/my-balance/my-balance'
      } else if (payEntry === Constant.PayEntry.VIP) {
        redirectUrl = `${protocol}//${host}${base}` + '/package-activities/pages/member-center/member-center'
      } else {
        redirectUrl = `${protocol}//${host}${base}` + '/package-user/pages/order/order?orderStatus=0'
      }
      // #endif
      // #ifdef APP-PLUS
      if (paySettlementType === 1 && payEntry === Constant.PayEntry.VIP) {
        redirectUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-activities/pages/member-center/member-center'
      }
      // #endif

      // 跟进支付入口生成请求参数和请求url
      const reqData = {
        payType,
        returnUrl: redirectUrl,
        systemType: paySettlementType === 1 ? 1 : undefined,
        systemModel: uni.getStorageSync('cloudSystemType')
      }
      let url = ''
      if (payEntry === Constant.PayEntry.ORDER) {
        reqData.orderIds = orderIds.split(',')
        url = isFinalPayment ? '/tmerclub_payment/pay/pay_balance' : '/tmerclub_payment/pay/order'
      }
      if (payEntry === Constant.PayEntry.RECHARGE) {
        reqData.balanceLogId = orderIds
        url = '/tmerclub_payment/pay/recharge'
      }
      if (payEntry === Constant.PayEntry.VIP) {
        reqData.userLevelLogId = orderIds
        url = '/tmerclub_payment/pay/vip'
      }
      if (paySettlementType === 1) {
        if (Constant.PayType.BALANCEPAY === payType || Constant.PayType.WECHATPAY_H5 === payType) {
          // 通联支付余额支付时，不需要传returnUrl（在确定支付接口传返回页面）
          reqData.returnUrl = undefined
        }
        if (Constant.PayType.WECHATPAY_MP === payType) {
          reqData.returnUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-activities/pages/result/result'
        }

        // #ifdef MP-WEIXIN
        // 微信小程序支付不用验证 vaildateType传0
        if (paySettlementType === 1) {
          reqData.validateType = 0
        }
        // #endif
      }
      http.request({
        url,
        method: 'POST',
        data: reqData,
        withoutPrompting: true
      }).then(res => {
        const _this = this
        // 保存支付信息，用于检测是否支付成功
        uni.setStorageSync('cloudPayOrderInfo', {
          payEntry,
          orderIds
        })
        // 积分订单: 纯积分 isPurePoints=1 或者 纯积分支付
        if (isPurePoints === 1 || payType === 0) {
          uni.redirectTo({
            url: '/pages/payment-result/payment-result?sts=1&orderIds=' + orderIds + '&orderType=' + orderType
          })
        } else {
          // 微信h5支付
          if (Constant.PayType.WECHATPAY_H5 === payType) {
            if (paySettlementType === 1) {
              _this.allinpayWechatPay(res, resolve)
              return
            }
            const url = encodeURIComponent(redirectUrl)
            window.location.href = res + '&redirect_url=' + url
          } else if (Constant.PayType.WECHATPAY_MP === payType) {
            if (paySettlementType === 1) {
              // 通联支付的微信公众号支付需要修改参数
              resolve(res.bizOrderNo)
              res = JSON.parse(res.payInfo)
              res.packageValue = res.package
            }
            // 微信公众号支付
            Wechat.callWexinPay(res, () => {
              // 支付成功
              _this.routeToAfterPay(true, paymemtObj)
            }, () => {
              // 支付失败
              _this.routeToAfterPay(false, paymemtObj)
            })
          } else if (Constant.PayType.ALIPAY_H5 === payType) {
            if (paySettlementType === 1) {
              // 通联支付的余额充值和购买vip
              http.request({
                url: '/tmerclub_payment/allinpay/order/pay_confirm_by_front_sms',
                method: 'POST',
                data: {
                  bizOrderNo: res.bizOrderNo
                }
              }).then(confirmRes => {
                resolve(res)
                // #ifdef APP-PLUS
                confirmRes = encodeURIComponent(confirmRes)
                // eslint-disable-next-line no-undef
                plus.runtime.openURL('alipays://platformapi/startapp?appId=20000067&url=' + confirmRes)
                // #endif
                // #ifdef H5
                confirmRes = encodeURIComponent(confirmRes)
                window.location.href = 'alipays://platformapi/startapp?appId=20000067&url=' + confirmRes
                // #endif
              })
              return
            }
            // 支付宝支付
            const div = document.createElement('div')
            div.innerHTML = res
            document.body.appendChild(div)
            document.forms[0].submit()
            div.remove()
          } else if (Constant.PayType.BALANCEPAY === payType) {
            // 余额支付
            this.balancePaySuccess(res, paymemtObj)
            resolve(res)
          } else if (Constant.PayType.PAYPAL === payType) {
            // PayPal支付
            window.location.href = res
          } else {
            // #ifdef APP-PLUS
            let wxAppPayInfo = {}
            if (payType === Constant.PayType.WECHATPAY_APP) {
              wxAppPayInfo = {
                sign: res.sign,
                prepayid: res.prepayId,
                partnerid: res.partnerId,
                appid: res.appId || res.appid,
                timestamp: res.timeStamp || res.timestamp,
                noncestr: res.nonceStr || res.noncestr,
                package: res.packageValue
              }
            }
            uni.getProvider({
              service: 'payment',
              success: () => {
                uni.requestPayment({
                  provider: payType === Constant.PayType.WECHATPAY_APP ? 'wxpay' : 'alipay',
                  orderInfo: payType === Constant.PayType.WECHATPAY_APP ? wxAppPayInfo : res,
                  success: () => {
                    _this.routeToAfterPay(true, paymemtObj)
                  },
                  fail: () => {
                    _this.routeToAfterPay(false, paymemtObj)
                  }
                })
              }
            })
            // #endif
            // #ifdef MP-WEIXIN
            if (paySettlementType === 1) {
              resolve(res.bizOrderNo)
              const payInfo = JSON.parse(res.payInfo)
              wx.requestPayment({
                timeStamp: payInfo.timeStamp,
                nonceStr: payInfo.nonceStr,
                package: payInfo.package,
                signType: payInfo.signType,
                paySign: payInfo.paySign,
                success: () => {
                  _this.routeToAfterPay(true, paymemtObj)
                },
                fail: () => {
                  _this.routeToAfterPay(false, paymemtObj)
                }
              })
              return
            }
            wx.requestPayment({
              timeStamp: res.timeStamp,
              nonceStr: res.nonceStr,
              package: res.packageValue,
              signType: res.signType,
              paySign: res.paySign,
              success: () => {
                _this.routeToAfterPay(true, paymemtObj)
              },
              fail: () => {
                _this.routeToAfterPay(false, paymemtObj)
              }
            })
            // #endif
          }
        }
      }).catch(err => {
        uni.showModal({
          title: '提示',
          content: err.data || err.msg,
          showCancel: false,
          success: errModSucc => {
            if (errModSucc.confirm) {
              uni.navigateTo({
                url: '/package-user/pages/order/order?orderStatus=0'
              })
            }
          }
        })
      })
    })
  },

  /**
   * 支付成功或失败后的统一跳转
   * @param {Boolean} isSuccess 是否支付成功
   * @param {Number} dvyType 配送类型
   * @param {String} orderIds 订单编号
   * @param {Number} payType 支付类型
   * @param {Number} payEntry 支付入口类型
   */
  routeToAfterPay (isSuccess, { dvyType, orderIds, payType, payEntry }) {
    dvyType = dvyType ? Number(dvyType) : ''
    let url = ''
    // 购买vip 成功与否都跳转同一个链接
    if (payEntry === Constant.PayEntry.VIP) {
      const pages = getCurrentPages()
      let backDelata = 0

      pages.forEach((page, index) => {
        if (page.$page.fullPath === '/package-activities/pages/member-center/member-center') {
          backDelata = pages.length - index - 1
        }
      })
      if (backDelata > 0) {
        setTimeout(function () {
          uni.setStorageSync('cloudLoadMemberCenter', true)
          uni.navigateBack({
            delta: backDelata
          })
        }, 1000)
      } else {
        // 避免购买会员未同步延迟1秒执行
        setTimeout(function () {
          uni.redirectTo({
            url: '/package-activities/pages/member-center/member-center'
          })
        }, 1000)
      }
      return
    }
    if (isSuccess) {
      // 支付成功后的跳转
      url = payEntry === Constant.PayEntry.RECHARGE ? '/package-activities/pages/my-balance/my-balance' : dvyType === 2 ? '/pages/paySuccess/paySuccess?sts=1&orderIds=' + orderIds + '&dvyType=' + dvyType : '/pages/payment-result/payment-result?sts=1&orderIds=' + orderIds + '&payType=' + payType
    } else {
      // 支付失败的跳转
      url = payEntry === Constant.PayEntry.RECHARGE ? '/package-activities/pages/recharge/recharge' : '/pages/payment-result/payment-result?sts=0&orderIds=' + orderIds + '&payType=' + payType
    }
    setTimeout(() => {
      uni.redirectTo({
        url
      }, 1000)
    })
  },

  /**
   * 唤起支付
   * @param payType
   * @param redirectPage
   * @param {Object} paydata 支付需要的参数
   * @param {Object} cb 成功回调
   * @param {Object} errorCb 失败回调
   */
  toPay ({ payType, redirectPage, paydata, cb, errorCb }) {
    payType = Number(payType)
    if (Constant.PayType.WECHATPAY_H5 === payType) {
      let redirectUrl = ''
      if (!redirectPage) {
        redirectUrl = window.location.href
      } else {
        const {
          protocol,
          host
        } = window.location
        redirectUrl = `${protocol}//${host}` + redirectPage
      }
      const url = encodeURIComponent(redirectUrl)
      window.location.href = paydata + '&redirect_url=' + url
    } else if (Constant.PayType.WECHATPAY_MP === payType) {
      // 微信公众号支付
      Wechat.callWexinPay(paydata, cb, errorCb)
    }
  },

  /**
   * 通联支付下微信支付
   * @param {*} res 申请接口的返回值
   * @param {*} resolve promise的成功回调
   */
  allinpayWechatPay (res, resolve) {
    // 通联支付的微信支付
    http.request({
      url: '/tmerclub_payment/allinpay/order/pay_confirm_by_front_sms',
      method: 'POST',
      data: {
        bizOrderNo: res.bizOrderNo
      }
    }).then(confirmRes => {
      resolve(res)
      confirmRes = encodeURIComponent(confirmRes)
      // #ifdef H5
      window.location.href = confirmRes
      // #endif
      // #ifdef MP-WEIXIN
      util.toAllinPay({
        targetUrl: res
      })
      // #endif
      // #ifdef APP-PLUS
      // eslint-disable-next-line no-undef
      plus.runtime.openURL(res)
      // #endif
    })
  },

  /**
   * 余额支付回调
   * @param {Number | Object} payId 余额支付id 若为空则支付失败；通联支付时为支付订单详情（对象）
   * @param {Number} dvyType 配送类型
   * @param {String} orderIds 订单编号
   * @param {Number} payType 支付类型
   * @param {Number} payEntry 支付入口类型
   */
  balancePaySuccess (payId, { dvyType, orderIds, payType, payEntry }) {
    const paymentObj = { dvyType, orderIds, payType, payEntry }
    if (paySettlementType === 1) {
      // 通联支付使用不同接口进行余额支付
      const data = {
        bizOrderNo: payId.bizOrderNo,
        jumpUrl: import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-activities/pages/member-center/member-center',
        errorJumpUrl: import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-activities/pages/member-center/member-center',
        jumpPageType: 1
      }
      if (payEntry === Constant.PayEntry.ORDER) {
        data.jumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/order/order?orderStatus=0'
        data.errorJumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/order/order?orderStatus=0'
      }
      // #ifdef APP-PLUS
      // 如果是app打开，则需要在url后面拼接isBuyVip=1(购买会员)，用于判断是否是设置或修改支付密码成功后返回的页面
      data.jumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isBuyVip=1'
      data.errorJumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isBuyVip=0'
      if (payEntry === Constant.PayEntry.ORDER) {
        // 如果是订单打开，则需要在url后面拼接isOrderEntry=1(订单)
        data.jumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isOrderEntry=1'
        data.errorJumpUrl = import.meta.env.VITE_APP_DOMAIN_ADDRESS + '/package-user/pages/redirect/redirect?isOrderEntry=0'
      }
      // #endif
      // #ifdef MP-WEIXIN
      data.jumpPageType = 2
      if (payEntry === Constant.PayEntry.ORDER) {
        data.jumpUrl = undefined
        data.errorJumpUrl = undefined
      }
      // #endif
      http.request({
        url: '/tmerclub_payment/allinpay/order/pay_confirm_by_front_pwd',
        method: 'POST',
        data
      }).then(res => {
        uni.hideLoading()
        // #ifdef H5
        window.location.href = res
        // #endif
        // #ifdef MP-WEIXIN
        util.toAllinPay({
          targetUrl: res
        })
        // #endif
        // #ifdef APP-PLUS
        // eslint-disable-next-line no-undef
        plus.runtime.openURL(res)
        // #endif
      }).catch(() => {
        uni.hideLoading()
      })
      return
    }
    http.request({
      url: '/tmerclub_user/user_balance/balance_pay',
      method: 'POST',
      data: String(payId)
    }).then(() => {
      if (payEntry === Constant.PayEntry.VIP) {
        uni.showToast({
          title: '支付成功！',
          duration: 1200
        })
      }
      this.routeToAfterPay(true, paymentObj)
    }).catch((err) => {
      uni.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  }
}
