<template>
  <div class="p-2 editInfo">
    <el-form label-position="top" ref="userFormRef" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="10">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="2"></el-col>
        <el-col :span="10">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="form.deptId"
              :data="enabledDeptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属部门"
              check-strictly
              @change="handleDeptChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item> </el-col
        ><el-col :span="2"></el-col>
        <el-col :span="10">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
          </el-form-item> </el-col
        ><el-col :span="2"></el-col>
        <el-col :span="10">
          <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="用户性别">
            <el-select v-model="form.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="2"></el-col>
        <el-col :span="10">
          <el-form-item label="岗位">
            <el-select v-model="form.postIds" multiple placeholder="请选择">
              <el-option
                v-for="item in postOptions"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
                :disabled="item.status == '1'"
              ></el-option>
            </el-select>
          </el-form-item> </el-col
        ><el-col :span="2"></el-col>
        <el-col :span="10">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="box_submit">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel()">取 消</el-button>
    </div>
  </div>
</template>

<script setup name="Profile" lang="ts">
import api from '@/api/system/user';
import { listProject } from '@/api/project/project';
import { getProjectByDeptId, getRoleList, optionselect } from '@/api/system/post';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_user_sex'));
const enabledDeptOptions = ref([]);
const deptOptions = ref([]);
const projectOptions = ref<any[]>([]);
const postOptions = ref([]);
const roleOptions = ref([]);
const userFormRef = ref<ElFormInstance>();
const initFormData = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  projectRoles: [
    {
      projectId: [],
      roleIds: []
    }
  ],
  status: '0',
  remark: '',
  postIds: [],
  filePath: undefined
};

const initData = {
  form: { ...initFormData },
  rules: {
    userName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '用户名称长度必须介于 2 和 20 之间',
        trigger: 'blur'
      }
    ],
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      {
        min: 5,
        max: 20,
        message: '用户密码长度必须介于 5 和 20 之间',
        trigger: 'blur'
      },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\ |', trigger: 'blur' }
    ],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    phonenumber: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ]
  }
};
const data = reactive(initData);
const { form, rules } = toRefs(data);
/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  const res = await api.deptTreeSelect({ isShow: '1' });
  deptOptions.value = res.data;
  enabledDeptOptions.value = filterDisabledDept(res.data);
  const projectList = await listProject();
  projectOptions.value = projectList.rows;
};
/** 过滤禁用的部门 */
const filterDisabledDept = (deptList) => {
  return deptList.filter((dept) => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};
async function handleDeptChange(value: number | string) {
  const response = await optionselect(value);
  const roleList = await getRoleList(value);
  roleOptions.value = roleList.data;
  postOptions.value = response.data;
  form.value.postIds = [];
  form.value.projectRoles = [
    {
      projectId: [],
      roleIds: []
    }
  ];
}

const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.userId ? await api.updateUser(form.value) : await api.addUser(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      proxy?.$emit('submit', false);
    }
  });
};

const cancel = () => {
  proxy?.$emit('close', false);
};
/** 重置操作表单 */
const reset = () => {
  form.value = { ...initFormData };
  form.value.projectRoles = [
    {
      projectId: [],
      roleIds: []
    }
  ];

  userFormRef.value?.resetFields();
};
// 打开弹框调用参数
const open = async (row?: any) => {
  reset();
  if (row) {
    // 编辑
    const { data } = await api.getUser(row.userId);
    Object.assign(form.value, data.user);
    postOptions.value = data.posts;
    roleOptions.value = data.roles;
    form.value.postIds = data.postIds;
    form.value.projectRoles = data.projectRoles;
    form.value.password = '';
    const roleList = await getRoleList(form.value.deptId);
    roleOptions.value = roleList.data;
  } else {
    // 新增
    const { data } = await api.getUser();
    postOptions.value = data.posts;
  }
};
onMounted(() => {
  getDeptTree();
});
defineExpose({ open });
</script>
<style lang="scss" scoped>
.editInfo {
  position: relative;
  height: 100%;
  .box_submit {
    position: absolute;
    right: 10px;
    bottom: 10px;
  }
}
</style>
