import axios from 'axios'
import { httpRequest } from './http'

export default new (class {
    /** 应用配置信息 */
    private appConfig = axios('./config/appconfig.json');

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

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

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

    /**
     * 尝试自动初始化，若断网或其它原因导致初始化失败，需手动初始化
     */
    private tryInit = this.init();

    /**
     * 初始化服务配置
     */
    private init(): Promise<typeof this.config> {
        this.isPending = true;
        return new Promise((resolve, reject) => {
            this.appConfig.then((res) => {
                const { apiUrl } = res.data;
                // 获取服务接口地址
                httpRequest(apiUrl, 'get', {
                    success: (res) => {
                        console.log('服务配置信息', res.data);
                        this.config = res.data as typeof this.config;
                        this.isReady = true;
                        resolve(this.config);
                    },
                    fail: () => {
                        reject('获取服务配置地址失败');
                    },
                    complete: () => {
                        this.isPending = false;
                    }
                })
            }).catch(() => {
                this.isPending = false;
                reject('获取配置信息失败');
            })
        })
    }

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