import { createPayOrder, queryOrderState } from '../api/wx-jsapi'
import store from '../store'

export function wxPay(param) {
  return new Promise((resolve, reject) => {
    createPayOrder(param).then((res) => {
      if (res.yjReqNo) {
        store.commit('SET_YJREQNO', null)
      }
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: res.appId,
          timeStamp: res.timeStamp,
          nonceStr: res.serialNo,
          package: 'prepay_id=' + res.prepayId,
          signType: res.signType,
          paySign: res.paySign,
          totalFee: res.totalFee,
        },
        function () {
          queryOrderState(res.tradeNo).then((response) => {
            if (response instanceof Object && response.tradeNo) {
              resolve(response)
            } else {
              reject(response)
            }
          })
        }
      )
    })
  })
}
