import Taro from '@tarojs/taro';
import store from "@/store";
import { dispatchCitySelected } from '@/actions/city'
import { USER_INFO } from '@/constants/user'
import { parseQueryString, setRecommender } from '@/utils/tools'
import { wxLogin } from '@/services/login'
import { queryUserInfo } from '@/services/user'
import { getCodeScene } from '@/services/common'

function loginRemote (params) {
  return new Promise((resolve, reject) => {
    // 远程登录获取人员
    wxLogin({...params }).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)
        }
      }

      // 如果有推荐人信息
      if (params.recommender && params.recommender !== person.personId) {
        setRecommender(params.recommender)
      }

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

function getCodeAndLogin (params) {
  return new Promise((resolve, reject) => {
    Taro.login({
      success: ({ code }) => {
        params.code = code
  
        // login
        loginRemote(params).then((res) => {
          const { person } = res
          resolve(person)
        })
      },
      fail: (err) => {
        console.error(err)
        reject(err)
      }
    })
  })
}

export default (params) => {
  return new Promise((resolve, reject) => {
    // 二维码ID
    const qrCodeId = params.scene
    if (qrCodeId) {
      // 读二维码内容
      getCodeScene(qrCodeId).then((res) => {
        const queryStr = JSON.parse(res).scene
        const qrCodeParams = parseQueryString(queryStr) || {}
        
        getCodeAndLogin({
          ...params,
          ...qrCodeParams,
        }).then(resolve).catch(reject)
      })
    } else {
      getCodeAndLogin(params).then(resolve).catch(reject)
    }
  })
}
