user.js 2.84 KB
import urlAlias from '../url';
import request from '../request';

const {
  login,
  getUserInfo,
} = urlAlias;

const state = {
  fromInfo: {
		loginQueryInfo: {},
    fromuid: 0,
    fromsid: 0,
    frompid: 0,
    scene: 1001,
  },
  userInfo: {
    uid: 1,
    openid: '',
    nickName: '',
    headerphoto: '',
  }
};

const mutations = {
  FROM: (state, data) => {
    state.formInfo = data;
  },
  UPDATE: (state, data) => {
    state.userInfo = data;
  }
};

const actions = {
  // 登陆
  login({ commit }, param) {
    const {
      frompid = undefined,
      fromsid = undefined,
      fromuid = undefined,
      scene = 1001 ,
    } = param || {};
    uni.login({
      provider: 'weixin',
      success: function (loginRes) {
        console.log('login',loginRes);
        request({
          url: login,
          data: {
            app_uid: 2020,
            code: loginRes.code,
            frompid,
            fromsid,
            fromuid,

          },
          success: (res) => {
            const { data: { session_key, openid} } = res;
            console.log('res', res)
            // 写入缓存
            uni.setStorageSync('session_key', session_key);
            uni.setStorageSync('openid', openid);
            request({
              url: getUserInfo,
              data: {
                app_uid: 2020,
                frompid,
                fromsid,
                fromuid,
                openid,
                scene,
              },
              success: (res) => {
                console.log('userInfo=====', res);
                const { data: { data: { uid, username: nickName, openid, headerphoto } } } = res;
                uni.setStorageSync('uid', uid);
                const userInfo = {
                  uid,
                  openid,
                  nickName,
                  headerphoto,
                }
                commit("UPDATE", userInfo)
              }
            })
          }
        })
      }
    });
  },
  setFrom({ commit }, param) {
    commit("FROM", param);
  },
  getUserInfo( { commit }, param) {
    const {
      frompid = undefined,
      fromsid = undefined,
      fromuid = undefined,
      scene = 1001 ,
    } = param || {};
    // 写入缓存
    const openid = uni.getStorageSync('openid', openid);
    request({
      url: getUserInfo,
      data: {
        app_uid: 2020,
        frompid,
        fromsid,
        fromuid,
        openid,
        scene,
      },
      success: (res) => {
        console.log('userInfo=====', res);
        const { data: { data: { uid, username: nickName, openid, headerphoto } } } = res;
        uni.setStorageSync('uid', uid);
        const userInfo = {
          uid,
          openid,
          nickName,
          headerphoto,
        }
        commit("UPDATE", userInfo)
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}