/**
 * @Author: 嗨噜客(三亚)<fm453>
 * @Date: 2023-07-19 16:03:07
 * @FilePath: apis/ctms/user.js
 * @Description: 
 * @Email:  393213759@qq.com
 * Copyright (c) 2025 by www.hiluker.cn, All Rights Reserved. 
 */
import request from './_utils/request.js'
import apis from './apis.json'
import constant from './_utils/constant.js'
import _sync from './sync.js'
import config from "@/config/ctms.config.js";
import store from '@/store/index.js';

export default {
    //检查登陆，返回用户信息
    checkLogin: function() {
        var user = store.state.user,
            isCloud = config.isUserUnicloud;
        if (!isCloud) {
            if (user.hasLogin) {
                return user.info;
            }
            return false;
        }

        var userCloud = store.state.userCloud;
        if (isCloud && userCloud.hasLogin) {
            var data = {
                mobile: userCloud.mobile,
                openid: userCloud.openid,
                username: userCloud.mobile
            }
            this.authLogin(data);
            return data;
        }
        return false;
    },

    // 获取用户信息
    getInfo: function() {
        var user = store.state.user,
            isCloud = config.isUserUnicloud;
        if (!isCloud) {
            if (user.hasLogin) {
                return user.info;
            }
            return false;
        }
        var userCloud = store.state.userCloud;
        if (isCloud && userCloud.hasLogin) {
            return {
                mobile: userCloud.mobile,
                openid: userCloud.openid,
                username: userCloud.mobile
            }
        }
        return false;
    },

    //一键授权
    oneKeyAuth: async function() {
        var _that = this;
        var isCloud = config.isUserUnicloud;
        if (!isCloud) {
            uni.showToast({
                icon: 'none',
                title: '应用未开启云服务支持'
            })
        }

        var user = store.state.user,
            userCloud = store.state.userCloud,
            list = [];
        if (!userCloud.hasLogin) {
            return uni.showModal({
                title: '提示',
                content: '请先登陆云平台',
                showCancel: true,
                cancelText: '放弃',
                success() {
                    uni.navigateTo({
                        url: config.uniCloudLoginUrl
                    })
                }
            })
        }
        var _info = userCloud.info,
            openid = userCloud.openid,
            mobile = userCloud.mobile;
        var reg = new RegExp(
            /^(?:(?:\+|00)86)?1(?:(?:3\d)|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8\d)|(?:9[189]))\d{8}$/
        );
        var matches = reg.exec(mobile);

        if (matches['length'] == 1 && matches['0'] == mobile) {
            list.unshift(mobile)
        } else if (openid) {
            list.unshift('同意')
        } else {
            return uni.showToast({
                icon: 'fail',
                title: '无效的平台信息'
            })
        }
        var res = await _sync.Actions.doSync('请确认授权', list);
        if (res) {
            var user = {
                mobile: mobile,
                openid: openid,
                isLong: true
            }
            var user = await _that.authLogin(user);
            // console.log('登陆授权返回', user)
            return user;
        }
        return false;
    },

    // 登陆,成功后执行相应的缓存操作
    login: function(formData) {
        var isLong = formData.isLong || false;
        var data = {
            username: formData.username,
            passwd: formData.passwd,
            isLong: isLong
        };

        var url = apis.UserLogin;
        var header = {
            'content-type': 'application/x-www-form-urlencoded'
        };
        return request({
            'url': url,
            // 'force_url': '', //强制指定URL，忽略上面的url设定
            'method': 'post',
            'data': data,
            "headers": header,
            'params': {}
        }).then((res) => {
            if (res.code == 200) {
                // utils.debug(res.data);
                var user = store.state.user;
                var _info = res.data.user;
                var date = new Date();
                var expireTime = date.getTime() + 3600 * 24 * 1000;
                //过期时间，正常是24小时
                if (isLong) {
                    date.setDate(date.getMonth() + 1);
                    //选择持久登陆时，时长改为1个月
                    expireTime = date.getTime();
                }
                // console.log(expireTime, _info.tokenExpired);
                _info.expireTime = expireTime;
                store.commit('user/login', _info) //触发@store/modules/user.js的login函数，同步执行
                return _info;
            } else {
                uni.showToast({
                    title: '登陆失败',
                    icon: 'none'
                });
            }
        })
    },

    // 通过短信验证码登陆,成功后执行相应的缓存操作
    smsLogin: function(formData) {
        var isLong = formData.isLong || false;
        var data = {
            mobile: formData.mobile,
            vcode: formData.vcode,
            isLong: isLong
        };

        var url = apis.UserLoginSms;
        var header = {
            'content-type': 'application/x-www-form-urlencoded'
        };
        return request({
            'url': url,
            // 'force_url': '', //强制指定URL，忽略上面的url设定
            'method': 'post',
            'data': data,
            "headers": header,
            'params': {}
        }).then((res) => {
            if (res.code == 200) {
                // utils.debug(res.data);
                var user = store.state.user;
                var _info = res.data.user;
                var date = new Date();
                var expireTime = date.getTime() + 3600 * 24 * 1000;
                //过期时间，正常是24小时
                if (isLong) {
                    date.setDate(date.getMonth() + 1);
                    //选择持久登陆时，时长改为1个月
                    expireTime = date.getTime();
                }
                // console.log(expireTime, _info.tokenExpired);
                _info.expireTime = expireTime;
                store.commit('user/login', _info) //触发@store/modules/user.js的login函数，同步执行
                return _info;
            } else {
                uni.showToast({
                    title: '登陆失败',
                    icon: 'none'
                });
            }
        })
    },

    // 注册,成功后执行相应的缓存操作
    reg: function(formData) {
        var isLong = formData.isLong || false;
        var data = {
            username: formData.username,
            passwd: formData.passwd,
            vcode: formData.vcode,
            email: formData.email,
            isLong: isLong
        };

        var url = apis.UserReg;
        var header = {
            'content-type': 'application/x-www-form-urlencoded'
        };
        return request({
            'url': url,
            // 'force_url': '', //强制指定URL，忽略上面的url设定
            'method': 'post',
            'data': data,
            "headers": header,
            'params': {}
        }).then((res) => {
            if (res.code == 200) {
                // utils.debug(res.data);
                var user = store.state.user;
                var _info = res.data.user;
                var date = new Date();
                var expireTime = date.getTime() + 3600 * 24 * 1000;
                //过期时间，正常是24小时
                if (isLong) {
                    date.setDate(date.getMonth() + 1);
                    //选择持久登陆时，时长改为1个月
                    expireTime = date.getTime();
                }
                // console.log(expireTime, _info.tokenExpired);
                _info.expireTime = expireTime;
                store.commit('user/login', _info) //触发@store/modules/user.js的login函数，同步执行
                return _info;
            }
        })
    },

    // 一键授权登陆
    authLogin: async function(user, from) {
        var isLong = user.isLong || false;
        var plat = getApp().globalData.config.openplat;
        var from = from || plat;
        var data = {
            mobile: user.mobile,
            openid: user.openid,
            isLong: isLong,
            from: from
        };
        var url = apis.UserAuth;
        var header = {
            'content-type': 'application/x-www-form-urlencoded'
        };
        return await request({
            'url': url,
            'method': 'post',
            'data': data,
            "headers": header,
            'params': {}
        }).then((res) => {
            if (res.code == 200) {
                // utils.debug(res.data);
                var user = store.state.user;
                var _info = res.data.user;
                var date = new Date();
                var expireTime = date.getTime() + 3600 * 24 * 1000;
                //过期时间，正常是24小时
                if (isLong) {
                    date.setDate(date.getMonth() + 1);
                    //选择持久登陆时，时长改为1个月
                    expireTime = date.getTime();
                }
                // console.log(expireTime, _info.tokenExpired);
                _info.expireTime = expireTime;
                store.commit('user/login', _info) //触发@store/modules/user.js的login函数，同步执行
                return _info;
            }
        })
    },

    logout: async function() {
        var isCloud = config.isUserUnicloud;
        var res = await _sync.Confirm.doSync('提示', '您正在注销，请确认继续', false);
        if (res) {
            store.commit('user/logout') //触发@store/modules/user.js的logout函数，同步执行
            if (isCloud) store.commit('userCloud/logout')
            uni.showToast({
                title: '您已注销，现在重新打开APP',
                icon: 'none'
            });
            return true;
        }
        return false;
    },

    loginDraft(formData = {}, isGet = false) {
        var ls = constant.userLoginForm;
        var data = uni.getStorageSync(ls);
        if (isGet) return data;
        var data = {
            ...data,
            ...formData
        };
        uni.setStorageSync(ls, data);
    },

    regDraft(formData = {}, isGet = false) {
        var ls = constant.userRegForm;
        var data = uni.getStorageSync(ls);
        if (isGet) return data;
        var data = {
            ...data,
            ...formData
        };
        uni.setStorageSync(ls, data);
    }
}