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

const publicKey = {
  key: '250405304072',
  // key: 'AVLRNG',
}
const initialData = {
  domId: 'payment',
  sdkName: '2checkout',
  // btnText: '提交',
  createToken: token => {
    console.log(token)
  },
  reportSDKLoading: time => {
    console.log(time)
  },
  label: {
    userNameLabel: '持卡人姓名',
  },
  errorTips: { userNameErrorTips: '請輸入有效的持卡人姓名' },
  styleOption: {
    commonStyle: {},
    componentStyle: {},
  },
  language: 'zy',
}

const pay = new sdk(publicKey, initialData)
console.log(pay)

document.getElementById('sumbit').addEventListener('click', async () => {
  // 订单数据
  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": "TwoCheckout",
      "payMethod": "Card",
      "amount": "0.1",
      "currency": "HKD",
      "userType": "yyuid",
      "userId": "123456",
      "prodId": "测试",
      "prodName": "测试",
      "notifyUrl": "http://requestbin.net/r/x1dse5x1",
      "attach": "",
      "orderData":{
        "shopperFirstName": "John",
        "shopperLastName": "Doe",
        "shopperCountryCode": "US",
        "shopperState": "OH",
        "shopperCity": "Columbus",
        "shopperAddress1": "123 test st",
        "shopperZip": "43123",
        "shopperEmail": "testingtesdsfdster22@2co.com",
        "shopperPhone": "5555555555"
      },
      "riskData": {}
    }`,
    sign: '1',
  }
  console.log(data)
  // 获取 第三方支付 token
  const token = await pay.getToken()

  if (token.error) {
    alert(token.error)
    return
  }

  // 创建订单
  const res =
    token.token &&
    (await axios.post('/create', qs.stringify(data), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    }))
  console.log(res.data)
  // 提交 token 到第三方支付渠道
  const channelPayUrl = res.data.resp.payData.channelPayUrl
  console.log(channelPayUrl)
  console.log(token.token)
  const channel = token.token && (await axios.post(channelPayUrl, { token: token.token }))
  console.log(channel.data)
  channel.data.code === 'SUCCESS' && alert('支付成功')
})
