<template>
    <!-- 基础信息弹出框 -->
  <el-dialog v-model='dialogVisible' :title="dialogTitle" v-bind="dialogSmall" @close="close">
    <div>
        <el-form :model="formContent"
                  ref='dialogFormRef'
                  :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" v-if="IsPasswordShow">
          <el-input type="password" v-model="formContent.password" show-password placeholder="请输入密码" autocomplete="off" />
        </el-form-item>
        <el-form-item label='角色' :label-width='100' prop='roles'>
            <el-select v-model="formContent.roleIds"  multiple   placeholder="请选择角色">
              <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          </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>
      </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/user';
  import { useDictStore } from '@/stores/modules/dict'
  import { type Role } from '@/api/user/interface/role';
  const dictStore = useDictStore()
  // 定义弹出组件元信息
  const dialogFormRef = ref()
  const IsPasswordShow = ref(false)
  const roleList = ref<Role.RoleBO[]>([])
  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: '', //用户密码错误锁定时间
      state: 1, //
    })
    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: '', //用户密码错误锁定时间
      state: 1, //
    }
  }
  
  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' },
       // 指定正则，此处是数字正则
       { pattern: /^[A-Za-z\u4e00-\u9fa5]{1,16}$/, message: '名称需1~16位的英文或汉字', trigger: 'blur' }],
      loginName: [{ required: true, message: '登录名必填！', trigger: 'blur' },
      { pattern: /^[a-zA-Z_.]{1}[a-zA-Z0-9_.]{2,15}$/, message: '登录名需2-15位的字母数字符号', trigger: 'blur' }],
      password: [{ required: true, message: '密码必填！', trigger: 'blur' },
      { pattern: /^(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,16}$/, message: '密码长度为8-16，需包含特殊字符', trigger: 'blur' }],
  })
 
  
 // 关闭弹窗
 const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          if (formContent.value.id) {
                await updateUser(formContent.value);
            } else {
                await addUser(formContent.value);
          }
          ElMessage.success({ message: `${dialogTitle.value}成功！` })
          close()
          // 刷新表格
          await props.refreshTable!()
        }
      })
    } catch (err) {
      console.error('验证过程中出现错误', err)
    }
  }
  
  // 打开弹窗，可能是新增，也可能是编辑
  const open = async (sign: string, data: User.ResUser,roleParams: Role.RoleBO[]) => {
    // 获取角色列表
    roleList.value = roleParams
    titleType.value = sign
    dialogVisible.value = true
    if (data.id) {
      IsPasswordShow.value = false
      formContent.value = { ...data }
    } else {
      IsPasswordShow.value = true
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  

  </script>