<template>
  <div class="e-dialog">
    <el-dialog v-model="dialog.visible" :title="dialog.title" :draggable="draggable" width="35%" align-center>
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="auto" class="mt-3">
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="formData.userId == undefined" label="用户名" prop="userName">
              <el-input v-model="formData.userName" placeholder="请输入用户名/登录账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="formData.userId == undefined" label="登录密码" prop="loginPwd">
              <el-input v-model="formData.loginPwd" placeholder="请输入登录密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学/工号" prop="userNumb">
              <el-input v-model="formData.userNumb" placeholder="请输入学/工号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="realName">
              <el-input v-model="formData.realName" placeholder="请输入用户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="formData.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择归属部门"
                check-strictly
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在岗位" prop="postId">
              <el-select v-model="formData.postId" placeholder="请选择">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == '1'"
                  filterable
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="category">
              <el-select v-model="formData.category" placeholder="请选择用户身份">
                <el-option v-for="dict in CATEGORY" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="formData.idNumber" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择性别">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入用户邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="formData.roleIds" filterable multiple placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="formData.userId == undefined && createAccount == '1'" label="卡片类型" prop="cardType">
              <el-select v-model="formData.cardType" placeholder="请选择">
                <el-option v-for="item in cardTypeOptions" :key="item.typeId" :label="item.typeName" :value="item.typeId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="formData.userId == undefined && createAccount == '1'" label="有效期" prop="lifespan">
              <el-date-picker v-model="formData.lifespan" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择账户有效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="UserDetailForm" lang="ts">
/**  模块导入 */
import { UserForm } from '@/api/system/right/user/types';
import api from '@/api/system/right/user';
import { useI18n } from 'vue-i18n';
import { DeptVO } from '@/api/system/dept/types';
import { PostVO } from '@/api/system/params/post/types';
import { RoleVO } from '@/api/system/role/types';
import { treeselect } from '@/api/system/dept';
import { listUsePtCardType } from '@/api/basics/basicParameter/ptCardtype';
import { PtCardTypeVO } from '@/api/basics/basicParameter/ptCardtype/types';
import { getPtParamByCode } from '@/api/basics/basicParameter/ptParameter';

/** 当前组件属性 */
defineOptions({ name: 'RecompenseForm' });
// 国际化
const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 当前页面引用的数据字典
const { sys_yes_no, sys_user_sex, CATEGORY } = toRefs<any>(proxy?.useDict('sys_yes_no', 'sys_user_sex', 'CATEGORY'));
// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 操作类型
const command = ref('');
// 输入项是否禁用
const disabled = ref(true);
// 是否自动创建账户
const createAccount = ref('1');
// 部门下拉数据
const deptOptions = ref<DeptVO[]>([]);
// 默认初始密码
const initPassword = ref<string>('');
// 岗位下拉数据
const postOptions = ref<PostVO[]>([]);
// 角色下拉数据
const roleOptions = ref<RoleVO[]>([]);
// 卡类下拉数据
const cardTypeOptions = ref<PtCardTypeVO[]>([]);
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<UserForm>({
  userId: undefined,
  deptId: undefined,
  postId: undefined,
  userName: '',
  nickName: undefined,
  realName: undefined,
  idNumber: '',
  userNumb: '',
  loginPwd: '',
  category: undefined,
  phone: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  cardType: undefined,
  lifespan: undefined,
  remark: '',
  roleIds: []
});
// 表单提交校验规则
const formRules = reactive({
  userName: [{ required: true, message: '登录账号不能为空', trigger: 'blur' }],
  loginPwd: [{ required: true, message: '登录密码不能为空', trigger: 'blur' }],
  userNumb: [{ required: true, message: '学/工号不能为空', trigger: 'blur' }],
  realName: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '归属部门不能为空', trigger: 'blur' }],
  postId: [{ required: true, message: '工作岗位不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '用户身份不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '电话号码不能为空', trigger: 'blur' }],
  roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
  cardType: [{ required: true, message: '账户卡类不能为空', trigger: 'blur' }],
  lifespan: [{ required: true, message: '账户有效期不能为空', trigger: 'blur' }]
});
/** 当前组件方法 */
const open = async (cmd: string, id?: string | number) => {
  dialog.visible = true;
  dialog.title = t('action.' + cmd);
  formType.value = cmd;
  command.value = cmd;
  resetForm();
  await initTreeData();
  // 修改时，设置数据
  formLoading.value = true;
  try {
    let res;
    if (id) {
      disabled.value = false;
      res = await api.getUser(id);
      Object.assign(formData.value, res.data.user);
      formData.value.postIds = res.data.postIds;
      formData.value.roleIds = res.data.roleIds;
      formData.value.loginPwd = '';
    } else {
      disabled.value = true;
      res = await api.getUser();
      formData.value.loginPwd = initPassword.value.toString();
    }
    postOptions.value = res.data.posts;
    roleOptions.value = res.data.roles;
  } finally {
    formLoading.value = false;
  }
};
// 查询部门下拉树结构
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};
// 初始化部门数据
const initTreeData = async () => {
  // 判断部门的数据是否存在，存在不获取，不存在则获取
  if (deptOptions.value === undefined) {
    const { data } = await treeselect();
    deptOptions.value = data;
  }
};
// 初始化卡类数据
const getCardTypeOption = async () => {
  const response = await listUsePtCardType();
  cardTypeOptions.value = response.data;
};
// 重置表单
const resetForm = () => {
  formData.value = {
    userId: undefined,
    deptId: undefined,
    postId: undefined,
    userName: '',
    nickName: undefined,
    realName: undefined,
    userNumb: '',
    loginPwd: '',
    idNumber: '',
    category: undefined,
    phone: undefined,
    email: undefined,
    sex: undefined,
    status: '0',
    cardType: undefined,
    lifespan: undefined,
    remark: '',
    postIds: [],
    roleIds: []
  };
  formRef.value?.resetFields();
};
// 传回给父组件的属性与方法
defineExpose({ open });

// 触发父组件的事件
const emit = defineEmits(['success']);
// 提交按钮
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as UserForm;
    data.userId ? await api.updateUser(data) : await api.addUser(data);
    proxy?.$modal.msgSuccess('操作成功');
  } finally {
    formLoading.value = false;
  }
  dialog.visible = false;
  // 发送操作成功的事件
  emit('success');
};
// 初始化
onMounted(() => {
  // 初始化部门数据
  getTreeSelect();
  // 初始化默认密码
  proxy?.getConfigKey('sys.user.initPassword').then((response) => {
    initPassword.value = response.data;
  });
  getPtParamByCode('AUTO_CREATE_BAG').then((response) => {
    createAccount.value = response.data;
  });
  // 初始化卡类数据
  getCardTypeOption();
});
</script>

<style scoped lang="scss">
.e-dialog {
  .slide-fade-enter-active {
    transition: all 0.3s ease;
  }

  .slide-fade-leave-active {
    transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
  }

  .slide-fade-enter,
  .slide-fade-leave-to {
    opacity: 0;
  }
}

.card-header {
  color: #1c84c6;
  font-size: medium;
}

.consume-select-header {
  color: #1c84c6;
  font-size: medium;
}

:deep() .el-dialog {
  border-radius: 10px;
}

:deep() .el-dialog__body {
  padding: 1px 1px !important;
  max-height: 90vh !important;
}

:deep() .el-dialog__header {
  background: #1d78d5;
  border-radius: 6px 6px 5px 5px;
}

:deep() .el-dialog__title {
  color: white;
  margin-top: 1px;
}

:deep() .el-dialog__headerbtn .el-dialog__close {
  color: white !important;
  top: 15px;
  right: 10px;
}

:deep() .el-overlay .el-overlay-dialog .el-dialog .el-dialog__body {
  padding: 1px !important;
}
</style>
