import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import useUserInfo from './useUserInfo'
import useLoginRequest from './useLoginRequest'
import { BindingCompanyApi, GetAdminUserInfoApi, GetPhoneNumberApi, GetWxUserInfoApi } from '@/api/user'
import { SHARE_SCENE } from '@/common/enum'
import { GetShortCodeApi } from '@/api/share'
import { alert } from '@/common/common'
import { LoginApi } from '@/api/login'
import { IMG_CND_Prefix } from '@/common/constant'

export default () => {
  const { setUserInfo, setAdminUserInfo, setSortCode, userInfo } = useUserInfo()
  // 获取分享码(右上角分享码)
  const { SharePage } = SHARE_SCENE
  const { fetchData: fetchDataShortCode } = GetShortCodeApi()
  const getShortCode = async(user_id) => {
    const { data: resPage } = await fetchDataShortCode({ share_user_id: user_id, type: SharePage.value })
    setSortCode({ ...userInfo.sort_code, shareShortPage: { title: '打造面料爆品 专注客户服务', code: resPage.md5_key, img: `${IMG_CND_Prefix}/mall/share_img_01.png` } })
  }

  // 获取用户信息
  const { fetchData: FetchData } = GetAdminUserInfoApi()
  const getAdminUserInfo = async() => {
    const res = await FetchData()
    setAdminUserInfo({ ...res.data })
    getShortCode(res.data.user_id)
  }
  // 登录请求
  const { login } = useLoginRequest()
  // const {fetchData:login} = LoginApi()
  const wxLogin = async() => {
    try {
      await login()
      getAdminUserInfo()
    }
    catch (e) {
      console.log('登录失败::', e)
    }
  }

  // 登录加checkLogin检查
  const checkLogin = () => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async(resolve) => {
      if (!userInfo.token) {
        await wxLogin()
        resolve(true)
      }
      else {
        // 这个东西不要打开，checkSession有调用频率问题
        // Taro.checkSession({
        //     success: async () => {
        //         resolve(true)
        //         if(!userInfo.adminUserInfo)  getAdminUserInfo()
        //     },
        //     fail: async () =>  {
        //         await wxLogin()
        //         resolve(true)
        //     }
        // })
      }
    })
  }

  // 获取用户头像等信息数据
  const { fetchData: fetchDataUserInfo } = GetWxUserInfoApi()
  const getSelfUserInfo = async() => {
    return new Promise((resolve, reject) => {
      if (userInfo.adminUserInfo?.is_authorize_name) {
        resolve(true)
        return true
      }
      Taro.getUserProfile({
        desc: '用于完善会员资料',
        success: async(res) => {
          if (!userInfo.session_key) {
            await wxLogin()
          }
          const user_res = await fetchDataUserInfo({
            session_key: userInfo.session_key,
            raw_data: res.rawData,
            signature: res.signature,
            encrypted_data: res.encryptedData,
            iv: res.iv,
          })
          if (user_res.success) {
            setUserInfo({ ...user_res.data })
            getAdminUserInfo()
            resolve(true)
          }
          else {
            reject(user_res.msg)
          }
        },
        fail: (e) => {
          console.log('授权失败：：', e)
          reject(e.errMsg)
        },
      })
    })
  }

  // 获取手机号码
  const { fetchData: fetchDataUserPhone } = GetPhoneNumberApi()
  const { fetchData: fetchBindingCompany } = BindingCompanyApi()
  const getPhoneNumber = (code) => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async(resolve, reject) => {
      if (userInfo.adminUserInfo?.is_authorize_phone) {
        resolve(true)
        return true
      }
      const res = await fetchDataUserPhone({ code })
      if (res.success) {
        setUserInfo({ ...userInfo.userInfo, phone: res.data.phone_number })
        await fetchBindingCompany()
        getAdminUserInfo()
        resolve(res.data)
      }
      else {
        reject(res.msg)
      }
    })
  }
  useDidShow(() => {
    checkLogin()
  })
  return {
    checkLogin,
    wxLogin,
    getSelfUserInfo,
    getPhoneNumber,
    userInfo,
    getAdminUserInfo,
  }
}
