import { useState } from "react"
import Taro from '@tarojs/taro'
import { signIn, authPhone, authAvatar,toggleRoul } from '@/services/person'

export default () => {
  const [person, setPerson] = useState()
  const [peronRoles, setPersonRoles] = useState([])

  const login = (params) => {
    signIn(params).then((res) => {
      const { person: taPerson, personRoleList, sessionKey, qrcode, token } = res;
      setPerson(taPerson);
      setPersonRoles(personRoleList);

      Taro.setStorage({ key: 'sessionKey', data: sessionKey })
      Taro.setStorage({ key: 'token', data: token })
      Taro.setStorage({ key: 'personId', data: taPerson.personId })
      Taro.setStorage({ key: 'openid', data: taPerson.openid })

      if (qrcode) {
        Taro.setStorage({ key: 'qrcode', data: qrcode })
      }
    })
  }

  const getPhone = (data) => {
    return authPhone(data).then((res) => {
      setPerson(res);
    })
  }


  const getAvatar = (data) => {
    return authAvatar(data).then((res) => {
      setPerson(res);
    })
  }

  const getRoul = (data) => {
    return toggleRoul(data).then((res) => {
      setPerson(res);
    })
  }

  return {
    person,
    peronRoles,
    setPerson,
    login,
    getPhone,
    getAvatar,
    getRoul
  }
}
