<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { useSettingStore } from '@/stores/settingStore'
import { syncSendCmd } from 'apis/system'
import SoftKeyboard from 'components/common/SoftKeyboard/index.vue'
import { FtMessage } from 'libs/message'
import { ref, watchEffect } from 'vue'

const emits = defineEmits(['refresh'])
const settingStore = useSettingStore()
const visible = ref(settingStore.addUserVisible)
const modalType = ref(settingStore.userModalState)
const inputValue = ref<string>('')
const keyboardVisible = ref(false)
const keyboardType = ref<'text' | 'number'>('text')
const softKeyboardRef = ref()
const userFormRef = ref()
const focusedInput = ref<string | null>(null)
const modalTitle = ref('新增用户')
const userForm = ref<Record<string, any>>({
  name: '',
  passwd: '',
  confirmPasswd: '',
  roleType: '',
})

watchEffect(() => {
  modalType.value = settingStore.userModalState
  if (settingStore.userModalState === 'edit') {
    modalTitle.value = '修改密码'
    if (settingStore.currentEditUser) {
      userForm.value = settingStore.currentEditUser
    }
  }
  else {
    modalTitle.value = '新增用户'
  }
  visible.value = settingStore.addUserVisible
  if (focusedInput.value) {
    userForm.value[focusedInput.value] = inputValue.value
  }
})

const onSave = (formRef: FormInstance | undefined) => {
  if (!formRef) {
    return
  }
  formRef.validate((valid) => {
    if (valid) {
      if (userForm.value.id) {
        doEdit()
      }
      else {
        doSave()
      }
    }
    else {
      console.log('error submit!')
    }
  })
}
const openKeyboard = (e: any) => {
  setTimeout(() => {
    keyboardVisible.value = true
    const labelName = e.target.name
    const formValue = userForm.value[labelName]
    inputValue.value = formValue ? formValue.toString() : ''
    focusedInput.value = e.target.name
  }, 100)
}
const doEdit = () => {
}
const doSave = () => {
  const name = userForm.value.name
  const passwd = userForm.value.passwd
  const confirmPasswd = userForm.value.confirmPasswd
  const roleType = userForm.value.roleType
  if (passwd !== confirmPasswd) {
    FtMessage.error('输入的密码不一致')
    return
  }
  const saveParams = {
    className: 'UserMgrService',
    fnName: 'addUser',
    params: {
      name,
      passwd,
      roleType: roleType ? 'admin' : 'maintainer',
    },
  }

  syncSendCmd(saveParams).then((res) => {
    if (res.ackcode === 0) {
      FtMessage.success('成功')
      emits('refresh')
      onClose()
    }
  })
}
const onClose = () => {
  const defaultForm = {
    id: 0,
    name: '',
    passwd: '',
    confirmPasswd: '',
    roleType: '',
  }
  userForm.value = defaultForm
  settingStore.updateCurrentEditUser(defaultForm)
  focusedInput.value = null
  settingStore.updateVisible(false)
}
const handleConfirm = (value: string) => {
  console.log('确认输入:', value)
}
</script>

<template>
  <FtDialog v-if="visible" v-model="visible" :title="modalTitle" :ok-handle="() => { onSave(userFormRef) }" @cancel="onClose">
    <div>
      <el-form ref="userFormRef" :model="userForm" label-width="auto" style="max-width: 400px">
        <el-form-item
          v-if="!userForm.id"
          label="登录名："
          prop="name"
          :rules="[{
            required: true,
            message: '输入登录名',
            trigger: ['blur', 'change'],
          }]"
        >
          <el-input v-model="userForm.name" v-prevent-keyboard name="name" @focus="openKeyboard" placeholder="登录名" />
        </el-form-item>
        <div>
          <el-form-item
            label="密码："
            prop="passwd"
            :rules="{
              required: true,
              message: '输入密码',
              trigger: ['blur', 'change'],
            }"
          >
            <el-input v-model="userForm.passwd" v-prevent-keyboard name="passwd" @focus="openKeyboard" type="password" placeholder="密码" />
          </el-form-item>
          <el-form-item
            label="确认密码："
            prop="confirmPasswd"
            :rules="{
              required: true,
              message: '输入密码',
              trigger: ['blur', 'change'],
            }"
          >
            <el-input v-model="userForm.confirmPasswd" v-prevent-keyboard name="confirmPasswd" @focus="openKeyboard" placeholder="确认密码" />
          </el-form-item>
        </div>
        <el-form-item
          label="是否管理员："
        >
          <el-checkbox v-model="userForm.roleType" size="small" />
        </el-form-item>
      </el-form>
      <Teleport to="body">
        <SoftKeyboard
          ref="softKeyboardRef"
          v-model="inputValue"
          :is-visible="keyboardVisible"
          :keyboard-type="keyboardType"
          @update-keyboard-visible="(visible) => keyboardVisible = visible"
          @confirm="handleConfirm"
          @close="keyboardVisible = false"
        />
      </Teleport>
    </div>
  </FtDialog>
</template>

<style lang="scss" scoped>
</style>
