import store from '../store/index'

// export var requestPath = 'http://192.168.192.201:8992/qa-regulatory-gwj/'; // 后台请求地址
export var requestPath = 'https://skqhdg.porthebei.com:9005/regulatory_gwj_2.0/'; // 后台请求地址
// export var requestPath = 'http://192.168.151.75:8092/';

let videoApiPath = 'https://arqsp.qhdsafety.com:10010'; // 视频平台后台请求地址
import dayjs from "dayjs";
import { setRefreshToken } from "@/api";
import {decryptAes} from "@/utils/aes_secret";
// export var requestPath = 'https://skqhdg.porthebei.com:9005/qa-regulatory-gwj/'; // 后台请求地址

export var requestPath = 'http://192.168.192.201:8992/regulatory_gwj_2.0/';

let videoApiPath = 'https://arqsp.qhdsafety.com:10010'; // 视频平台后台请求地址

function logOut(reject,data) {
    uni.showToast({
        title: '登录失效，请重新登录',
        icon: 'none',
        duration: 2000
    });
    reject(data)
    setTimeout(()=>{
        let userInfo = {}
        for (const userInfoKey in store.state.userInfo) {
            if (store.state.userInfo.hasOwnProperty(userInfoKey)) {
                userInfo[userInfoKey] = ''
            }
        }
        store.dispatch('setUserInfo', userInfo)
        uni.reLaunch({
            url: '/pages/login/login'
        })
    },1000)
}

function post(url, data) {
    return new Promise((resolve, reject) => {
        if (data && data.loading !== false) {
            uni.showLoading({
                title: '加载中'
            });
        }
        uni.request({
            url: requestPath + url,
            data: {
                USER_ID: store.state.userInfo.USER_ID || '',
                CORPINFO_ID: store.state.userInfo.CORPINFO_ID || '',
                ...data
            },
            method: 'POST',
            header: {
                'Content-type': data?.postMethod || 'application/json',
                'token': uni.getStorageSync('token') || ''
            },
            success: (res) => {
                res.data = decryptAes(res.data);
                if (data && data.loading !== false) {
                    uni.hideLoading();
                }
                if (res.data.result === 'success') {
                    resolve(res.data)
                } else {
                    if(url =='/admin/check'){
                        uni.showToast({
                            title: res.data.msg || '系统开小差了',
                            icon: 'none',
                            duration: 2000
                        });
                        reject(res.data)
                    }else{
                        if(res.data.code === 401){
                            logOut(reject,res.data)
                            return
                        }
                        uni.showToast({
                            title: res.data.msg || '系统开小差了',
                            icon: 'none',
                            duration: 2000
                        });
                        reject(res.data)
                    }

                }
            },
            fail: (err) => {
                if (data && data.loading !== false) {
                    uni.hideLoading();
                }
                uni.showToast({
                    title: '网络错误请重试',
                    icon: 'error',
                    duration: 2000
                });
                reject(err)
            }
        });
    })
}

function upload(url, data) {
    return new Promise((resolve, reject) => {
        if (data && data.loading !== false) {
            uni.showLoading({
                title: '加载中'
            });
        }
        uni.uploadFile({
            url: requestPath + url,
            filePath: data.filePath,
            name: data.name || 'file',
            formData: data.formData || {},
            header: {
                'token': uni.getStorageSync('token') || ''
            },
            success: (res) => {
                res.data = decryptAes(res.data);
                uni.hideLoading();
                const data = JSON.parse(res.data)
                if (data.result === 'success') {
                    resolve(data)
                } else {
                    if(data.code === 401){
                        logOut(reject,data)
                        return
                    }
                    uni.showToast({
                        title: data.msg || '系统开小差了',
                        icon: 'none',
                        duration: 2000
                    });
                    reject(data)
                }
            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: '网络错误请重试',
                    icon: 'error',
                    duration: 2000
                });
                reject(err)
            }
        });
    })
}

function uploads(url, data) {
    return new Promise((resolve, reject) => {
        if (data && data.loading !== false) {
            uni.showLoading({
                title: '加载中'
            });
        }
        uni.uploadFile({
            url: requestPath + url,
            files: data.files,
            formData: data.formData || {},
            header: {
                'token': uni.getStorageSync('token') || ''
            },
            success: (res) => {
                res.data = decryptAes(res.data);
                uni.hideLoading();
                const data = JSON.parse(res.data)
                if (data.result === 'success') {
                    resolve(data)
                } else {
                    if(data.code === 401){
                        logOut(reject,data)
                        return
                    }
                    uni.showToast({
                        title: data.msg || '系统开小差了',
                        icon: 'none',
                        duration: 2000
                    });
                    reject(data)
                }
            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: '网络错误请重试',
                    icon: 'error',
                    duration: 2000
                });
                reject(err)
            }
        });
    })
}
function setBasePath(url, data) {
    requestPath = url
}

function videoApiGet(url, data) {
    return new Promise((resolve, reject) => {
        if (data && data.loading !== false) {
            uni.showLoading({
                title: '加载中'
            });
        }
        uni.request({
            url: videoApiPath + url + (data.token?`?token=${data.token}`:''),
            data: {
                ...data
            },
            method: 'GET',
            header: {
                'Content-type': 'application/json'
            },
            success: (res) => {
                uni.hideLoading();
                resolve(res.data)
            },
            fail: (err) => {
                if (data && data.loading !== false) {
                    uni.hideLoading();
                }
                uni.showToast({
                    title: '网络错误请重试',
                    icon: 'none',
                    duration: 2000
                });
                reject(err)
            }
        });
    })
}

function loginRequest(url, data = {}) {
    return new Promise((resolve, reject) => {
        if (data && data.loading !== false) {
            uni.showLoading({
                title: "加载中",
                mask: true,
            });
        }
        uni.request({
            url: requestPath + url,
            data: {
                ...data,
            },
            header: {
                "Content-type": data?.postMethod || "application/json",
            },
            method: "POST",
            success: (res) => {
                res.data = decryptAes(res.data);
                if (data && data.loading !== false) {
                    uni.hideLoading();
                }
                if (res.data.result === "success") {
                    resolve(res.data);
                } else {
                    uni.showToast({
                        title: res.data || "系统开小差了",
                        icon: "none",
                    });
                    reject(res.data);
                }
            },
            fail: (err) => {
                if (data && data.loading !== false) {
                    uni.hideLoading();
                }
                uni.showToast({
                    title: "网络错误请重试",
                    icon: "none",
                });
                reject(err);
            },
        });
    });
}

setInterval(async () => {
    if (uni.getStorageSync('tokenTime') == null) return;
    if (dayjs().diff(dayjs(uni.getStorageSync('tokenTime')), "minute") >= 5) {
        uni.setStorageSync('tokenTime', dayjs().format("YYYY-MM-DD HH:mm:ss"))
        await setRefreshToken();
    }
}, 1000 * 60);

export {post, upload, uploads,setBasePath,videoApiGet,loginRequest}
