const noop = () => { }

const warn = (msg, duration, callback = noop) => {
    wx.showToast({
        icon: "none",
        title: msg,
        duration,
        success: callback
    })
}

const request = ({
    url,
    method = "GET",
    complete = noop,
    header = {},
    ...rest
}) => {
    let token = wx.getStorageSync("token")
    wx.request({
        url: url,
        method: method,
        header: {
            ...header,
            Authorization: token
        },
        ...rest,
        complete: function (res) {
            if (res.statusCode === 401) {
                wx.removeStorageSync("token")
                let pages = getCurrentPages();
                let loginPage = "/pages/login/login"
                if(pages[pages.length - 1].route !== loginPage){
                    if(!wx.getStorageSync('login_navigated')){
                        wx.navigateTo({url: loginPage})
                        wx.setStorageSync('login_navigated', 1)
                    }
                }    
            } else {
                wx.removeStorageSync('login_navigated');
                if (res.statusCode === 500) {
                    warn("请求失败！");
                }
            }
            complete(res);
        }
    })
}


const pad = n => n >= 10 ? n.toString() : `0${n}`

const format = (datetime, short) => {
    let dt = new Date(datetime);
    let y = dt.getFullYear(),
        m = dt.getMonth() + 1,
        d = dt.getDate(),
        h = dt.getHours(),
        min = dt.getMinutes(),
        s = dt.getSeconds();
    if (short) return `${pad(m)}/${pad(d)} ${pad(h)}:${pad(min)}`
    return `${pad(y)}-${pad(m)}-${pad(d)} ${pad(h)}:${pad(min)}`
}

const uuid = () => {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

const secureCheck = (host, filename) => {
    return new Promise((resolve, reject) => {
        wx.serviceMarket.invokeService({
            service: 'wxee446d7507c68b11',
            api: 'imgSecCheck',
            data: {
                "Action": "ImageModeration",
                "Scenes": ["PORN", "POLITICS", "TERRORISM", "TEXT"],
                "ImageUrl": host + filename,
                "ImageBase64": "",
                "Config": "",
                "Extra": ""
            },
        }).then(res => {
            console.log(res.data)
            let { data: { Response: { Suggestion } } } = res;
            if (Suggestion === 'PASS') {
                resolve()
            } else {
                let msg = '您上传的图片可能包含广告、色情、暴力等违规信息或敏感政治词！'
                warn(msg, 2000, reject)
            }
        })
    })
}
const trim = (str) => {
    if(!str) return str;
    return str.replace(/^\s+/, '').replace(/\s+$/, '')
}

const ExerciseTypes = {
    ImageIdentify: 0,
    SightSing: 1
}

module.exports = {
    warn,
    request,
    pad,
    uuid,
    format,
    secureCheck,
    trim,
    ExerciseTypes
}
