import {
    isURL,
    validatenull
} from '@/untils/validate.js'
import website from '@/config/website'
import {
    loginByUsername,
    getUserInfo,
    logout,
    refreshToken,
    mobileIsCms,
    noticeIsEnable,
    setNoticeIsEnable
} from '@/api/user'
import md5 from 'js-md5'
import {
    getStore,
    setStore
} from '@/untils/store.js'
import {
    calcDate
} from '@/untils/date.js'
import {
    myResume,
} from '@/api/resume.js';

let refreshTimer = null;

function startRefreshToken(dispatch) {
    refreshTimer = setInterval(() => {
        const token =
            getStore({
                name: "token",
                debug: true
            }) || {};
        const date = calcDate(token.datetime, new Date().getTime());
        if (validatenull(date)) return;
        if (date.seconds >= website.tokenTime) {
            dispatch("refreshToken")
                .then(() => {})
                .catch(() => {});
        }
    }, 10000);
}

function stopRefreshToken() {
    clearInterval(refreshTimer)
}

const user = {
    state: {
        tenantId: getStore({
            name: 'tenantId'
        }) || '',
        userInfo: getStore({
            name: 'userInfo'
        }) || [],
        token: getStore({
            name: 'token'
        }) || '',
        refreshToken: getStore({
            name: 'refreshToken'
        }) || '',
        userChecked: getStore({
            name: 'setUserCheckValue'
        }) || false,
        sendTimes: getStore({ //用户发送短信次数
            name: 'setUserSendTimes'
        }) || 0,
        seeEnterprise: getStore({ //用户发送短信次数
            name: 'enterprise'
        }) || 0, // 0 个体招工 ； 企业招工
        userLocation: null,
        userIsCms: false,
        resumeInfo: {},
        isEnbleNotice: false,
    },
    actions: {
        getNoticeState({
            commit,
            dispatch
        }) {
            noticeIsEnable().then(res => {
                if (res.data.code === 200) {
                    const data = res.data.data ? true : false
                    commit('upDateNoticeState', data)
                }
            })
        },
        setNoticeOpen({
            commit,
            dispatch
        }) {
            setNoticeIsEnable(1).then(res => {
                if (res.code === 200) {
                    const data = res.data
                    commit('upDateNoticeState', true)
                }
            })
        },
        setNoticeClose({
            commit,
            dispatch
        }) {
            setNoticeIsEnable(0).then(res => {
                if (res.code === 200) {
                    const data = res.data
                    commit('upDateNoticeState', false)
                }
            })
        },
        getResumeInfo({
            commit,
            dispatch
        }) {
            myResume().then(res => {
                const data = res.data.data
                commit('upDataResumeInfo', data)
            })
        },
        getMobileIsCms({
            commit,
            dispatch
        }) {
            mobileIsCms().then((res) => {
                commit('setIsCms', {
                    val: res.data.data
                })
            })
        },
        getUserLocation({
            commit,
            dispatch
        }) {
            // commit('setLocation', {
            //     latitude: 31.133980,
            //     longitude: 104.404419,
            // })
            uni.getLocation({
                type: 'wgs84',
                success: function(res) {
                    console.warn('用户位置获取成功')
                    const {
                        longitude,
                        latitude
                    } = res
                    commit('setLocation', {
                        longitude,
                        latitude
                    })
                },
                fail: function(err) {
                    console.warn('用户位置获取失败')
                    commit('setLocation', null)
                },
                complete: function(e) {
                    console.warn('getUserLocation' + JSON.stringify(e))
                }
            })
        },
        //用户点击radio按钮
        UserCheckedBtn({
            commit
        }, val) {
            commit('SET_USER_CHECKED', val);
        },
        //根据用户名登录
        LoginByUsername({
            commit,
            dispatch
        }, userInfo) {
            return new Promise((resolve, reject) => {
                loginByUsername(userInfo.tenantId, userInfo.username, md5(userInfo.password), userInfo.type,
                    userInfo.key,
                    userInfo.code, userInfo.token).then(res => {

                    const data = res.data;
                    if (data.error_description) {
                        uni.showToast({
                            icon: "none",
                            title: data.error_description,
                        })
                    } else {
                        commit('SET_TOKEN', data.access_token);
                        commit('SET_REFRESH_TOKEN', data.refresh_token);
                        commit('SET_TENANT_ID', data.tenant_id);
                        commit('SET_USER_INFO', data);
                        dispatch('refreshAuthState')
                        dispatch('startRefreshNewsTimer')
                        startRefreshToken();
                    }
                    resolve(res);
                }).catch(error => {
                    reject(error);
                })
            })
        },
        //根据手机号登录
        LoginByPhone({
            commit
        }, userInfo) {
            return new Promise((resolve) => {
                loginByUsername(userInfo.phone, userInfo.code).then(res => {
                    const data = res.data.data;
                    commit('SET_TOKEN', data);
                    resolve();
                })
            })
        },
        GetUserInfo({
            commit
        }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then((res) => {
                    const data = res.data.data;
                    resolve(data);
                }).catch(err => {
                    reject(err);
                })
            })
        },
        //刷新token
        refreshToken({
            state,
            commit,
            dispatch
        }) {
            return new Promise((resolve, reject) => {
                refreshToken(state.refreshToken, state.tenantId).then(res => {
                    const data = res.data;
                    dispatch('refreshAuthState')
                    commit('SET_TOKEN', data.access_token);
                    commit('SET_REFRESH_TOKEN', data.refresh_token);
                    resolve();
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登出
        LogOut({
            dispatch,
            commit
        }) {
            return new Promise((resolve, reject) => {
                logout();
                stopRefreshToken();
                commit('SET_TOKEN', '');
                commit('SET_VIPCODE', '0');
                resolve();
            })
        },
        //注销session
        FedLogOut({
            commit
        }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '');
                resolve();
            })
        },
        startRefreshTokenTimer({
            state,
            commit,
            dispatch
        }) {
            if (state.token) {
                dispatch('refreshToken').then(() => {
                    startRefreshToken(dispatch);
                })
            }
        },
        //更新用户接收短信次数
        UpdateUserSendTimes({
            commit
        }, data) {
            commit('SET_USER_SENDTIMES', data);
        }
    },
    mutations: {
        upDateNoticeState(state, payload) {
            state.isEnbleNotice = payload
        },
        upDataResumeInfo(state, payload) {
            state.resumeInfo = payload
        },
        setIsCms(state, payload) {
            state.userIsCms = payload.val
        },
        setLocation(state, val) {
            state.userLocation = val
        },
        setEnterprise(state, val) { // 0 个体招工 ； 企业招工
            state.seeEnterprise = val;
            setStore({
                name: 'enterprise',
                content: val,
            })
        },
        SET_TOKEN: (state, token) => {
            state.token = token;
            setStore({
                name: 'token',
                content: state.token,
                type: 'session'
            })
        },
        SET_REFRESH_TOKEN: (state, refreshToken) => {
            state.refreshToken = refreshToken;
            setStore({
                name: 'refreshToken',
                content: state.refreshToken,
                type: 'session'
            })
        },
        SET_TENANT_ID: (state, tenantId) => {
            state.tenantId = tenantId;
            setStore({
                name: 'tenantId',
                content: state.tenantId,
                type: 'session'
            })
        },
        SET_USER_INFO: (state, userInfo) => {
            state.userInfo = userInfo;
            setStore({
                name: 'userInfo',
                content: state.userInfo
            })
        },
        SET_USER_CHECKED: (state, val) => {
            state.userChecked = val;
            setStore({
                name: 'setUserCheckValue',
                content: state.userChecked
            })
        },
        SET_USER_SENDTIMES: (state, val) => {
            state.sendTimes = val;
            setStore({
                name: 'setUserSendTimes',
                content: state.sendTimes
            })
        },

    }
}
export default user