import { corePost } from '@/api/http'
import config from '@/store/module/config'
import jwtDecode from 'jwt-decode'

export default {
    /**
     * 註冊帳號
     * @param {String} applyType - 寄信類型(email, phone)
     * @param {String} name - 姓名
     * @param {String} account - 驗證帳號
     * @param {String} pw - 密碼
     * @param {String} country - 手機區碼，無須+號(有phone為必填)
     * @param {String} pinCode - 驗證碼
     */
    crtAccount: function (item) {
        return new Promise((resolve) => {
            let srvAdr = localStorage.getItem('srvAdr')
            let url = config.state[srvAdr].coreAPIUrl
            let nonceStr = 'habook'  // 檢查項目
            let data = {
                "grant_type": "create",
                'client_id': config.state[srvAdr].clientID,
                'nonce': nonceStr,
                "name": item.name,
                "password": item.pw,
                "pin_code": item.pinCode.toString()
            }

            if (item.applyType == 'phone') {
                data.account = '+' + item.country + '-' + item.account
            } else {
                data.account = item.account
            }

            corePost(url + '/oauth2/login', data).then(res => {
                if (res.error) {
                    resolve(res)
                } else {
                    let t_data = jwtDecode(res.id_token)
                    if (nonceStr === t_data.nonce) {
                        resolve(res)
                    } else {
                        resolve({ error: 'nonce' })
                    }
                }
            }, err => {
                console.log(err)
            })
        })
    },
    //通过IP判断地区（大陆、香港、台湾）
    checkIp: function () {
        return new Promise((r, j) => {
            let srvAdr = localStorage.getItem('srvAdr')
            let url = config.state[srvAdr].coreAPIUrl
            corePost(url + '/area/lang').then(
                res => {
                    if (res.error) {
                        j('error')
                    } else {
                        r(res)
                    }
                },
                err => {
                    j(err)
                }
            )
        })
    }
}


