import sdk from '../../../dist/index'
import axios from 'axios'
import qs from 'qs'
import moment from 'moment'

document.getElementById('submit').addEventListener('click', async () => {
  const amount = document.getElementById('amount').value
  if (amount === '') {
    alert('请输入支付金额')
    return
  }

  const returnUrl = document.getElementById('returnUrl').value
  if (returnUrl === '') {
    alert('请输入returnUrl')
    return
  }

  // 订单数据
  const data = {
    appId: '999',
    signType: 'RSA2',
    charset: 'UTF-8',
    version: '1.0',
    timestamp: moment.utc().format('YYYYMMDDHHmmss'),
    format: 'JSON',
    msgId: '{{$guid}}',
    method: '/api/v1/payment_orders/create',
    bizContent: `{
        "merchantId": "999202008041414438sSViH",
        "merchantOrderId": "${Math.floor(Math.random() * 100000000)}",
        "merchantOrderTime": "${moment.utc().format('YYYYMMDDHHmmss')}",
        "chId": "AsiaBill",
        "payMethod": "Card",
        "amount": ${amount},
        "currency": "HKD",
        "userType": "yyuid",
        "userId": "123456",
        "prodId": "测试",
        "prodName": "测试",
        "notifyUrl": "http://requestbin.net/r/x1dse5x1",
        "attach": "",
        "orderData":{
          "shopperFirstName": "Eva",
          "shopperLastName": "Tan",
          "shopperCountryCode": "US",
          "shopperState": "OH",
          "shopperCity": "Collierville",
          "shopperAddress1": "110 North Tree Drive",
          "shopperZip": "38017",
          "shopperEmail": "est@Asiabill.com",
          "shopperPhone": "075525846758"
        },
        "riskData": {}
      }`,
    sign: '1',
  }
  console.log(data)

  // 创建订单
  const res = await axios.post('/create', qs.stringify(data), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
  const orderData = res.data.resp

  console.log(orderData)

  // 提交到第三方支付 AsiaBill
  const fieldData = {
    merNo: orderData.payData.merNo,
    gatewayNo: orderData.payData.gatewayNo,
    orderNo: orderData.orderId,
    orderCurrency: 'HKD',
    orderAmount: amount,
    signInfo: orderData.payData.signKey,
    returnUrl: returnUrl,
    firstName: 'Eva',
    lastName: 'Tan',
    email: 'est@Asiabill.com',
    phone: '075525846758',
    paymentMethod: 'Credit Card',
    country: 'US',
    state: 'Tennessee',
    city: 'Collierville',
    address: '110 North Tree Drive',
    zip: '38017',
  }

  const initialData = {
    env: 'dev',
    sdkName: 'asiaBill',
    fieldData: fieldData,
    reportSDKLoading: reportSDKLoadingParams => {
      console.log('sdk加载时间', reportSDKLoadingParams)
    },
  }
  const pay = new sdk('', initialData)
  console.log(pay)
  const token = await pay.getToken()
  if (!token.state) {
    alert(token.msg)
  }
})
