import $store from "@/store/index"
import Vue from "vue"
let prototype = Vue.prototype;

export default {
    /**
     * 登录平台
     */
    platformLogin() {
        return new Promise((resolve, reject) => {
            // #ifdef MP-WEIXIN
            uni.login({
                provider: "weixin",
                success(result) {
                    prototype.$request({
                        api: 'user.openId',
                        data: {
                            code: result.code
                        }
                    }).then((response) => {
                        prototype.$storage.set("open_id", response.data.openid);
                        return resolve(response.data);
                    }).catch(e => { });
                }
            });
            // #endif
            // #ifdef H5
            return resolve({
                openid: "mobile_000000000000000000"
            });
            // #endif
        });
    },
    /**
     * 初始化用户
     */
    async initUser() {
        // openid
        let openId = prototype.$storage.get("open_id");
        if (!openId) {
            await this.platformLogin().then((response) => {
                openId = response.openid;
            });
        }
        $store.commit("user/openId", openId);
        // token
        let token = prototype.$storage.get("user_access_token");
        $store.commit('user/token', token);
    },
    /**
     * 发送验证码
     */
    sendVerificationCode(mobile) {
        return new Promise((resolve, reject) => {
            if (!prototype.$test.mobile(mobile)) {
                return reject('请输入正确的手机号码');
            }
            prototype.$request({
                api: 'user.sendCode',
                data: {
                    username: mobile,
                },
            }).then((res) => {
                if (res.code == 1) {
                    return resolve();
                } else {
                    return reject(response.msg);
                }
            }).catch(e => { });
        });
    },
    /**
     * 获取信息
     */
    info(refresh) {
        return new Promise((resolve, reject) => {
            if (refresh === true) {
                prototype.$storage.remove('userinfo');
            }
            let cacheUser = prototype.$storage.get('userinfo');
            if (cacheUser) {
                return resolve(cacheUser);
            }
            prototype.$request({
                api: 'user.info',
            }).then(response => {
                if (response.code == 1) {
                    let user = {
                        id: response.data.id,
                        avatar: response.data.avatar,
                        nickname: response.data.user_nickname,
                        openid: response.data.openid,
                        mobile: response.data.mobile,
                        create_time: response.data.create_time,
                    };
                    prototype.$storage.set('userinfo', user);
                    return resolve(user);
                } else {
                    return reject(response.msg);
                }
            }).catch(e => { });
        });
    },
    /**
     * 保存用户信息
     */
    save(data) {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "user.save",
                data: data
            }).then(response => {
                if (response.code == 1) {
                    return resolve(response.msg);
                }
                return reject(response.msg);
            }).catch(e => { });
        });
    },
    /**
     * 获取注册类型
     */
    getRegisterType() {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "user.registerType",
            }).then(response => {
                if (response.code == 1) {
                    let list = [];
                    response.data.forEach(item => {
                        list.push({
                            id: item.id,
                            name: item.name,
                        });
                    });
                    return resolve(list);
                }
                return reject(response.msg);
            }).catch(e => { });
        });
    },
    /**
     * 用户注册
     */
    register(user, verificationCode) {
        return new Promise((resolve, reject) => {
            if (!prototype.$test.mobile(user.mobile)) {
                return reject('请输入正确的手机号码');
            }
            if (user.password.length < 6 || user.password.length > 16) {
                return reject('密码在6至16位字符之间');
            }
            if (!user.openId) {
                return reject('缺少OpenId，请重启应用');
            }
            prototype.$request({
                api: 'user.register',
                data: {
                    username: user.mobile,
                    password: user.password,
                    openid: user.openId,
                    verification_code: verificationCode,
                    register_type: user.registerType,
                    types: 1,
                }
            }).then((response) => {
                if (response.code == 1) {
                    return resolve(response);
                } else {
                    return reject(response.msg);
                }
            }).catch(e => { });
        });
    },
    /**
     * 登录用户
     */
    login(user) {
        return new Promise((resolve, reject) => {
            if (!prototype.$test.mobile(user.mobile)) {
                return reject('请输入正确的手机号码');
            }
            if (user.password.length < 6 || user.password.length > 16) {
                return reject('密码在6至16位字符之间');
            }
            prototype.$request({
                api: 'user.login',
                data: {
                    username: user.mobile,
                    password: user.password,
                }
            }).then(async response => {
                if (response.code == 1) {
                    prototype.$storage.set('user_access_token', response.data.token);
                    // 提交token到store
                    await this.initUser();
                    return resolve(response);
                } else {
                    return reject(response.msg);
                }
            }).catch(e => { });
        });
    },
    /**
     * 找回密码
     */
    resetPassword(data, verificationCode) {
        return new Promise((resolve, reject) => {
            prototype.$request({
                api: "user.resetPassword",
                data: {
                    username: data.username,
                    password: data.password,
                    verification_code: verificationCode,
                    types: 1,
                },
            }).then(response => {
                if (response.code == 1) {
                    return resolve(response.msg);
                }
                return reject(response.msg);
            }).catch(e => { });
        });
    },
    /**
     * 注销登录
     */
    logout() {
        return new Promise((resolve, reject) => {
            prototype.$storage.set('user_access_token', null);
            prototype.$storage.set('userinfo', null);
            $store.commit('user/token', "");
            $store.commit('cart/cart', {
                loaded: false,
                list: [],
            });
            return resolve();
        });
    }
}
