import router from '../../router'
import { UserActionsType } from '../../store/modules/user/actions'
import { dispatchAction, getStoreGetter, setStoreState } from '../../store/utils'
import message from '../../utils/message'
import { reactive, ref } from 'vue'
import { isEmail } from '../../utils/validate'
import { useI18n } from 'vue-i18n'
interface LoginParams {
  username: string
  password: string
  remeber: boolean
}

const userUserLoginModule = () => {
  const userModel: LoginParams = reactive({
    username: '',
    password: '',
    remeber: false
  })
  const {t} = useI18n()
  const userValidateRule = reactive({
    // usernameRule: [(val:any, rules:any) => rules.email(val) || t("login.ruleTipsAccount")],
    usernameRule: [(val:any, rules:any) => !!val || t("login.ruleTipsAccount")],
    userpasswordRule: [(val: any) => !!val || t("login.ruleTipsPwd")]
  })
  const stateManager = reactive({
    subLogin: ref(false)
  })
  const usernameRef = ref(null)
  const passwordRef = ref(null)

  const loginSubmit = async () => {
    if (!stateManager.subLogin) {
      stateManager.subLogin = true
      const ur = usernameRef as any //断言任意类型
      const pr = passwordRef as any
      ur.value.validate()
      pr.value.validate()
      
      if (ur.value.hasError || pr.value.hasError) {
        message.warnMsg(t("login.formTips"))
        stateManager.subLogin = false
      } else {
        const param = {
          account: userModel.username,
          password: userModel.password,
          platform: 0
        }
        let r = await dispatchAction<UserActionsType>('user', 'userLogin', param) as [boolean,string]
        if(!r[0]){
          message.errorMsg(r[1])
          stateManager.subLogin=false
        }else{
          location.href='/index'
        }
      }
    }
  }

  

  return { userModel, usernameRef, passwordRef, userValidateRule, loginSubmit, stateManager }
}

export default userUserLoginModule
