import axios from 'axios'
import i18n, { defaultLang } from "@/lang/index.js"
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus/es'
import router from '@/router'

let loadingInstance = null

export const apiUrl = window.global?.botURL; // botapi的地址

const service = axios.create({
    baseURL: window.global?.baseURL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': localStorage.getItem('token'),
    }
})

service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        const localLang = localStorage.getItem('locale')

        if (token) {
            config.headers.Authorization = token
        }

        config.headers.Lang = localLang || defaultLang

        if (!config.hideLoading) {
            loadingInstance = ElLoading.service({
                lock: true,
                text: i18n.global.t('加载中') + '...',
                background: 'rgba(0, 0, 0, 0.7)'
            })
        }

        return config
    },
    error => {
        if (loadingInstance) {
            loadingInstance.close()
        }
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        if (loadingInstance) {
            loadingInstance.close()
        }

        const res = response.data

        if (res.code === 1) {
            if (response.config.showSuccessTip !== false && res.msg) {
                ElMessage.success(res.msg)
            }
            return res
        } else if (res.code === 0) {
            if (response.config.showFailTip !== false && res.msg) {
                ElMessage.error(res.msg)
            }
            return Promise.reject(res)
        } else if (res.code === 401) {
            ElMessage.error(res.msg || i18n.global.t('登录已过期，请重新登录'))
            localStorage.removeItem('token')
            localStorage.removeItem("youke_token");
            localStorage.removeItem('user_info')
            setTimeout(() => {
                window.location.href = '/login'
            }, 1500)
            return Promise.reject(new Error('登录已过期'))
        } else if (res.code === 10011) {
            // 资金密码未设置
            setTimeout(() => {
                ElMessageBox.confirm(
                    i18n.global.t('您还未设置资金密码，是否前往设置？'),
                    i18n.global.t('提示'),
                    {
                        confirmButtonText: i18n.global.t('确定'),
                        cancelButtonText: i18n.global.t('取消'),
                        type: 'warning',
                    }
                ).then(() => {
                    router.push({ name: 'Safety', query: { active: 'fund_pwd' }})
                }).catch(() => {})
            }, 300)
            return Promise.reject(new Error(res.msg || '未设置资金密码'))
        } else if (res.code === 10012) {
            // 系统通知维护弹窗
            const maintainTime = res.data?.time || ''; 

           const htmlContent = `
                <div style="line-height: 1.8; font-size: 14px; padding: 10px 5px;">
                    <div style="font-size: 12px; color: #909399; margin-bottom: 30px; text-align: center; border-bottom: 1px solid #333; padding-bottom: 15px;">
                        ${i18n.global.t('温馨提示：平台不会主动加好友上分，请谨防被骗，以咨询客服人员为准')}
                    </div>
                    
                    <div style="text-align: left; margin-bottom: 15px; color: #e5e7eb; font-size: 15px; font-weight: 500;">
                        ${i18n.global.t('尊敬的用户')}：
                    </div>
                    
                    <div style="text-align: left; margin-bottom: 12px; color: #c0c4cc; text-indent: 2em;">
                        ${i18n.global.t('每日')}（<span style="color: #f56c6c; font-weight: bold; padding: 0 4px;">${maintainTime}</span>）${i18n.global.t('为系统维护时间段')}。
                    </div>
                    
                    <div style="text-align: left; color: #a3a6ad; font-size: 13px; text-indent: 2em;">
                        ${i18n.global.t('维护期间将暂停此交易服务，请您合理安排操作时间，敬请谅解！')}
                    </div>
                </div>
            `;

            ElMessageBox.alert(htmlContent, i18n.global.t('系统通知'), {
                dangerouslyUseHTMLString: true,
                confirmButtonText: i18n.global.t('确认'),
                center: true,
                showClose: false,
                confirmButtonClass: 'notice-confirm-btn',
                customClass: 'dark-notice-modal' // 添加此 class 方便在全局设定深色背景
            }).catch(() => {});

            return Promise.reject(new Error(res.msg || '系统重要通知'))
        } else {
            if (response.config.showFailTip !== false) {
                ElMessage.error(res.msg || i18n.global.t('请求失败，请稍后重试'))
            }
            return Promise.reject(new Error(res.msg || '请求失败'))
        }
    },
    error => {
        if (loadingInstance) {
            loadingInstance.close()
        }

        ElMessage.error(error.message || i18n.global.t('网络异常，请检查网络后重试'))
        return Promise.reject(error)
    }
)

service.get = (url, config = {}) => {
    return service({
        url,
        method: 'GET',
        params: config.params,
        hideLoading: config.hideLoading,
        showSuccessTip: config.showSuccessTip,
        showFailTip: config.showFailTip
    })
}

service.post = (url, data = {}, config = {}) => {
    return service({
        url,
        method: 'POST',
        data,
        hideLoading: config.hideLoading,
        showSuccessTip: config.showSuccessTip,
        showFailTip: config.showFailTip
    })
}

export default service