<template>
    <!-- 基础信息弹出框 -->
  <el-dialog v-model='dialogVisible' :title="dialogTitle" v-bind="dialogSmall" @close="close">
    <div>
        <el-form :model="formContent"
                  ref='formRuleRef'
                  :rules='rules'
                  >
        <el-form-item label="用户名" prop='name' :label-width="100">
          <el-input v-model="formContent.name" placeholder="请输入用户名" autocomplete="off" />
        </el-form-item>
        <el-form-item label="登录名" prop='loginName'  :label-width="100">
          <el-input v-model="formContent.loginName" placeholder="请输入登录名" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop='password' :label-width="100">
          <el-input type="password" v-model="formContent.password" placeholder="请输入密码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号码" prop='phone' :label-width="100">
          <el-input v-model="formContent.phone" placeholder="请输入手机号码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱地址" prop='email' :label-width="100">
          <el-input v-model="formContent.email" placeholder="请输入邮箱地址" autocomplete="off" />
        </el-form-item>
        <el-form-item label="最后一次登录时间" prop='loginTime' :label-width="100">
          <el-input v-model="formContent.loginTime" placeholder="请输入最后一次登录时间" autocomplete="off" />
        </el-form-item>
        <el-form-item label="登录错误次数" prop='loginErrorTimes' :label-width="100">
          <el-input v-model="formContent.loginErrorTimes" placeholder="请输入登录错误次数" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户密码错误锁定时间" prop='lockTime' :label-width="100">
          <el-input v-model="formContent.lockTime" placeholder="请输入用户密码错误锁定时间" autocomplete="off" />
        </el-form-item>
      </el-form>
      </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="save()">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  </template>
  
  <script lang="ts" setup>
  import { ref,computed, type Ref  } from 'vue'
  import {dialogSmall} from '@/utils/elementBind'
  import { ElMessage, type FormInstance,type FormItemRule } from 'element-plus'
  import {
    addUser,
    updateUser
  } from '@/api/user/user'
  // 使用 dayjs 库格式化
  import dayjs from 'dayjs';
  import { type User } from '@/api/user/interface';
  // 定义弹出组件元信息
  const dialogFormRef = ref()

  function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<User.ResUser>({
      id: '',       //用户ID，作为唯一标识
      name: '',     //用户名(别名)
      loginName: '',//登录名
      password: '',//密码
      phone: '',    //手机号
      email: '',   //邮箱
      loginTime: '',//最后一次登录时间
      loginErrorTimes: 0,//登录错误次数
      lockTime: '', //用户密码错误锁定时间
    })
    return { dialogVisible, titleType, formContent }
  }
  
  const { dialogVisible, titleType, formContent } = useMetaInfo()
  // 清空formContent
  const resetFormContent = () => {
    formContent.value = {
      id: '',       //用户ID，作为唯一标识
      name: '',     //用户名(别名)
      loginName: '',//登录名
      password: '',//密码
      phone: '',    //手机号
      email: '',   //邮箱
      loginTime: '',//最后一次登录时间
      loginErrorTimes: 0,//登录错误次数
      lockTime: '', //用户密码错误锁定时间
    }
  }
  
  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增用户' : '编辑用户'
  })


    //定义规则
    const formRuleRef = ref<FormInstance>()
  //定义校验规则
  const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: '名称必填！', trigger: 'blur' }],
    loginName: [{ required: true, message: '登录名必填！', trigger: 'blur' }],
    password: [{ required: true, message: '密码必填！', trigger: 'blur' }],
    loginErrorTimes: [{ required: true, message: '登录错误次数必填！', trigger: 'blur' }],
  })
 
  
 // 关闭弹窗
 const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          formContent.value.lockTime = dayjs(formContent.value.lockTime).format('YYYY-MM-DD');
          if (formContent.value.id) {
                const result = await updateUser(formContent.value);
                if(result.code != 'A0000'){
                  ElMessage.error({ message: result.message})
                }else{
                  ElMessage.success({ message: `${dialogTitle.value}成功！` })
                }
            } else {
                const result = await addUser(formContent.value);
               if(result.code != 'A0000'){
                  ElMessage.error({ message: result.message})
                }else{
                  ElMessage.success({ message: `${dialogTitle.value}成功！` })
                }
          }
          close()
          // 刷新表格
          await props.refreshTable!()
        }
      })
    } catch (err) {
      console.error('验证过程中出现错误', err)
    }
  }
  
  // 打开弹窗，可能是新增，也可能是编辑
  const open = (sign: string, data: User.ResUser) => {
    titleType.value = sign
    dialogVisible.value = true
    if (data.id) {
      formContent.value = { ...data }
    } else {
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  

  </script>