import Taro from '@tarojs/taro';
import store from "@/store";
import { dispatchCitySelected } from '@/actions/city'
import { USER_INFO, ASSIGN_UNREADNUM, ROLE_CODE } from '@/constants/user'
import { ifNull } from '@/utils/tools'
import { wxLogin } from '@/services/login'
import { queryUserInfo } from '@/services/user'
import { API_QUERY_USERINFO_BYID } from '@/constants/api'
import { fetch } from '@/utils/request'

export default (params) => {
  return new Promise((resolve, reject) => {  
    // 转换 undefined 为 ''
    const loginParams = Object.keys(params).reduce((acc, k) => ({ ...acc, [`${k}`]: ifNull(params[k], '') }), {})

    // 远程登录获取人员
    wxLogin(loginParams, false).then(data => {

      const { extraInfo, miniApp, person, city } = data
      const { token, sessionKey } = miniApp
      const { dispatch, getState } = store

      Taro.setStorageSync('token', token)
      Taro.setStorageSync('sessionKey', sessionKey)

      dispatch({ type: USER_INFO, payload: { extraInfo, person, miniApp } })
      const { city: { curCity } } = getState()

      if (!curCity || Object.keys(curCity).length == 0) {
        if (city) {
          dispatchCitySelected(city)(dispatch)
        }
      }

      // 获取人员详细信息
      // eslint-disable-next-line no-unused-vars
      queryUserInfo().then(info => {
        resolve(data)
      }).catch(reject)

      // 如果有推荐人信息
      if (loginParams.recommender && loginParams.recommender !== person.personId) {
        fetch({ url: `${API_QUERY_USERINFO_BYID}/${loginParams.recommender}` }).then((res) => {
          dispatch({ type: 'SYNC_RECOMMENDER', payload: res });
          if (res.personType === ROLE_CODE.CONSULTANT) {
            dispatch({ type: 'SYNC_CONSULTANT', payload: res });
          }
        })
      }
    }).catch(reject)
  
  })
}
