import axios from 'axios'
import plus from '@/utils/h5plus'

export default new (class {
    /** 服务配置信息 */
    config = {
        commSearchUrl: '',
        goCommonSearchUrl: '',
        hsbyBankSignZone: '',
        hsbyRegister: '',
        hsbyPayUrlWeb: '',
        hsbySignUp: '',
        mobileAuthUrl: '',
        mobileOpenUrl: '',
        newsUrl: '',
        openApiUrl: '',
        quoteHost: '',
        quotePort: '',
        quoteUrl: '',
        tradeHost: '',
        tradePort: '',
        tradeUrl: '',
        uploadUrl: '',
        oem: '',
        iOS: '',
        android: '',
        androidUpdateUrl: '',
        pcNewsUrl: '',
        pcMangerUrl: '',
        shareUrl: '',
    }

    /** 服务初始化完成状态 */
    isReady = false

    /** 等待服务初始化 */
    private isPending = false

    /**
     * 自动初始化，若断网或其它原因导致初始化失败，需手动初始化
     * IOS上架审核可能会遇到网络权限的情况，应用可能会在未授权网络权限的情况下发起请求，导致请求等待时间过长，最终审核被拒
     */
    //private onload = this.init()

    /**
     * 手动初始化
     */
    private onload = Promise.resolve(this.config)

    /**
     * 重试次数
     */
    private retryCount = 0

    /**
     * 失败时重新尝试初始化，直到成功为止
     */
    private tryinit = () => {
        return new Promise<typeof this.config>((resolve, reject) => {
            if (this.retryCount >= 5) {
                this.retryCount = 0
                this.isPending = false
                reject('服务加载失败，请稍后再试')
            } else {
                this.retryCount++
                // 自动计算每次重试的延时，重试次数越多，延时越大
                // const delay = this.retryCount * 3000
                setTimeout(() => {
                    resolve(this.init())
                }, 3000)
            }
        })
    }

    /**
     * 初始化服务配置
     * https://uniapp.dcloud.net.cn/tutorial/app-ios-uiwebview.html
     */
    private init(): Promise<typeof this.config> {
        this.isPending = true
        return new Promise((resolve, reject) => {
            const filePath = './config/appconfig.json'
            const getAppConfig = async () => {
                if (plus.hasPlus()) {
                    const res = await plus.getLocalFileContent(filePath)
                    return JSON.parse(res)
                } else {
                    const res = await axios(filePath)
                    return res.data
                }
            }
            getAppConfig().then((res) => {
                // 获取服务接口地址
                axios(res.apiUrl).then((res) => {
                    this.config = res.data.data
                    this.isReady = true
                    resolve(this.config)
                }).catch(() => {
                    const result = this.tryinit()
                    resolve(result)
                })
            }).catch(() => {
                reject('配置文件加载失败，请稍后再试')
            })
        })
    }

    /**
     * 服务初始化完成时触发
     */
    onReady() {
        if (!this.isReady && !this.isPending) {
            this.onload = this.init()
        }
        // 确保当前只有一个初始化实例
        return this.onload
    }
})