import React from 'react';
import Taro from '@tarojs/taro';
import md5 from 'md5';
import { login, signin, currentUser, authPhone, authUser } from '@/services/wxma';
import { changePassword } from '@/services/sysuser';
import { ROLE_CITIZEN } from '@/utils/user';

export default function useUser() {
  const [person, setPerson] = React.useState();
  const [user, setUser] = React.useState();
  const [duty, setDuty] = React.useState();

  const maLogin = (code) => {
    login(code).then(res => {
      setPerson(res.person);
      Taro.setStorage({ key: 'personId', data: res.person.personId })
      Taro.setStorage({ key: 'sessionKey', data: res.sessionKey })
    });
  }

  const updateDuty = (d = ROLE_CITIZEN) => {
    setDuty(d);
    Taro.setStorageSync('duty', d);
  }

  const initDuty = (u) => {
    const d = Taro.getStorageSync('duty');
    const dutyList = u?.dutyList || [];
    if (d) {
      if (dutyList.indexOf(d) < 0) {
        updateDuty(dutyList[0]);
      } else {
        updateDuty(d);
      }
    } else {
      updateDuty(dutyList[0]);
    }
  }

  const maSignIn = (params) => {
    const data = {
      ...params,
      password: md5(params.password)
    };

    return signin(data).then(res => {
      setUser(res.user);
      initDuty(res.user);
    })
  }

  const current = () => {
    currentUser().then(res => {
      setUser(res.user);
      initDuty(res.user);
    })
  }

  const signinByPhone = (code) => {
    return authPhone(code).then(res => {
      setUser(res.user);
      initDuty(res.user);
      setPerson(res.person);
    })
  }

  const authProfile = (data) => {
    const sessionKey = Taro.getStorageSync('sessionKey');
    authUser({ ...data, sessionKey }).then(res => {
      setPerson(res);
    })
  }

  const signOut = () => {
    setUser(null);
    initDuty([]);
  }

  const changePwd = (params) => {
    const data = {
      originPassword: md5(params.originPassword),
      newPassword: md5(params.newPassword),
    }

    changePassword(data);
  }

  return {
    user,
    person,
    current,
    duty,
    signin: maSignIn,
    login: maLogin,
    updateDuty,
    signinByPhone,
    authProfile,
    signOut,
    changePwd,
  }
}
