import { Toast } from 'vant';
import fetch from '@/utils/fetch';
import { getBaseUrl, getWxType } from '@/utils/index'
import { setCookie, getCookie, delCookie } from '@/utils/index';
import { envConfig } from '@/utils/env-config';

let wxInfo = sessionStorage.getItem('wxInfo');
wxInfo = wxInfo ? JSON.parse(wxInfo) : {};

const user = {
  state: {
    token: localStorage.getItem('couponToken') || getCookie('couponToken') || '',
    info: {}, // 用户信息
    wxInfo, // 微信信息，openid等
    wxCode: '', // 微信code
  },
  mutations: {
    SET_TOKEN: (state, payload) => {
      state.token = payload;
      console.log('state.token ' + state.token);
    },
    SET_USER_INFO_2: (state, payload) => {
      state.info = payload;
    },
    SET_WX_INFO: (state, payload) => {
      state.wxInfo = payload;
    },
    SET_WX_CODE: (state, payload) => {
      state.wxCode = payload;
    },
  },
  actions: {
    // 外部登陆返回设置token
    setToken({ commit, dispatch }, params) {
      console.log('setToken 1', params);
      if( typeof(params) == 'object') {
        params = params.join("");
      }
      console.log('setToken 2', params);
      commit('SET_TOKEN', params);
      localStorage.setItem('couponToken', params);
      setCookie('couponToken', params)
      dispatch('getUserInfo');
    },
    // 获取用户信息
    async getUserInfo({ state, commit, dispatch }) {
      try {
        const errCallBack = () => {
          dispatch('logout');
          // Toast('登录失效，请重新登录~')
        }
        const res = await fetch({
          url: getBaseUrl('account/login/web'),
          method: 'get',
          headers: { token: state.token }
        }).catch(() => {
          errCallBack()
        });
        if (res && res.code === '000000') {
          const { certifyDoc, isExist } = res.data;
          const picapDoctor = res.data.picapDoctor || {};
          if (picapDoctor.id) {
            // let avatar = picapDoctor.avatar_image_url || '';
            let avatarUrl = '';
            // const img1 = await preLoadImg(`https://test-file.yunqueyi.com${avatar}`).catch(err => console.log(err));
            // const img2 = await preLoadImg(`https://file.yunqueyi.com${avatar}`).catch(err => console.log(err));
            // if (img1) {
            //   avatarUrl = img1.src;
            // }
            // if (img2) {
            //   avatarUrl = img2.src;
            // }
            picapDoctor.avatar = avatarUrl || 'https://file.yunqueyi.com/File/doctor_default.png';
            commit('SET_USER_INFO_2', { ...picapDoctor, isExist, certifyDoc });
          }
        } else {
          errCallBack()
        }
      } catch (err) {
        console.error(err);
      }
    },

    // 通过登陆
    goLogin() {
      window.location.href = envConfig[process.env.BUILD_ENV]['webPageUrl'] + "/pica_login?target_url=" + encodeURIComponent(location.href);
    },

    getWxUserInfo({ state, commit }, code) {
      commit('SET_WX_CODE', code);
      const type = getWxType();
      // let url = getBaseUrl(`wechats/users/info/${type}/${code}`);
      let url = `https://sc.yunqueyi.com/wechats/users/info/${type}/${code}`; // 测试支付，暂时使用线上
      fetch({
        url,
        method: 'get',
        headers: { token: state.token }
      }).then(res => {
        sessionStorage.setItem('wxInfo', JSON.stringify(res.data));
        commit('SET_WX_INFO', res.data)
      });
    },

    // 登出
    logout({ state, commit }) {
      commit('SET_TOKEN', '');
      commit('SET_USER_INFO_2', {});
      localStorage.removeItem('couponToken');
      delCookie('couponToken');
    },
  },
}

export default user;
