<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isAdd ? '添加' : '编辑'"
    :width="864"
    center
    align-center
    :close-on-click-modal="false"
    @closed="closed"
  >
    <el-form :model="formData" ref="formRef" label-width="90px" :rules="formRules">
      <el-row class="mt20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="formData.nickName" placeholder="请输入姓名" :maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="false">
          <el-form-item label="归属部门" prop="deptId">
            <el-cascader
              v-model="formData.deptId"
              :options="deptTree"
              :show-all-levels="false"
              :props="{ value: 'id', emitPath: false }"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="formData.userName"
              placeholder="请输入用户名"
              :maxlength="20"
              @input="val => (formData.userName = val.replace(/[\W]/g, ''))"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select v-model="formData.roleIds" style="width: 100%" multiple>
              <el-option v-for="item in roleList" :label="item.roleName" :value="item.roleId" :key="item.roleId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isAdd" :span="12">
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" :maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位" prop="postIds">
            <el-select v-model="formData.postIds" style="width: 100%" multiple>
              <el-option v-for="item in postList" :label="item.postName" :value="item.postId" :key="item.postId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="formData.phonenumber"
              placeholder="请输入手机号码"
              :maxlength="11"
              @input="val => (formData.phonenumber = val.replace(/\D/g, ''))"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch v-model="formData.status" active-value="0" inactive-value="1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否为临时账号" prop="temporary" label-width="110px">
            <el-switch v-model="formData.temporary" active-value="0" inactive-value="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" class="ml30" v-throttle="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="editTeamMember">
import { reactive, ref, defineExpose, inject, computed } from "vue";
import { FormInstance, FormRules, ElMessage } from "element-plus";
import { editUser, addUser, getUserInfoById } from "@/api/modules/system/user";
import { User } from "@/api/interface";

//* 接收注入
const dialogVisible = ref(false);
//* data
//* ref
const formRef = ref<FormInstance>();
const openPromise = ref<any>({});
interface FormData extends Partial<User.ResUserList> {
  [key: string]: any;
}
const deptTree = ref([]);
const getDeptTree: () => [] = inject("getDeptTree", () => []);
const dropDownData = reactive<any>({
  posts: [],
  roles: []
});
const isAdd = ref(false);
const formData = reactive<FormData>({
  userId: undefined,
  userName: "",
  password: "",
  nickName: "",
  deptId: undefined,
  phonenumber: "",
  status: "0",
  roleIds: [],
  postIds: []
});
//* 方法

// 校验规则
let formRules = reactive<FormRules>({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
  phonenumber: [{ pattern: /^1[3-9]\d{9}$/, message: "手机号不正确", trigger: ["blur", "change"] }],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }
  ]
});

// 角色列表
const roleList = computed(() => {
  return dropDownData.roles.filter((item: any) => item.status === "0" || formData.roleIds?.includes(item.roleId));
});

const postList = computed(() => {
  return dropDownData.posts.filter((item: any) => item.status === "0" || formData.postIds?.includes(item.postId));
});

// 加载下拉框
async function loadDropDownData() {
  const { data } = await getUserInfoById();
  dropDownData.roles = data.roles || [];
  dropDownData.posts = data.posts || [];
}
loadDropDownData();
// 加载详情
function loadDetail(userId: number) {
  getUserInfoById(userId).then((res: any) => {
    const detail: { [key: string]: any } = {
      ...res.data,
      postIds: res.postIds || [],
      roleIds: res.roleIds || []
    };
    if (res.data.userId) {
      for (const key of Object.keys(formData)) {
        if (key === "password") continue;
        formData[key] = detail[key];
      }
    }
  });
}
function closed() {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  formData.userId = undefined;
}
// 取消
function handleCancel() {
  dialogVisible.value = false;
}
//提交
function handleSubmit() {
  formRef.value?.validate(async valid => {
    if (!valid) return;
    const params = {
      ...formData
    };
    if (isAdd.value) {
      await addUser(params);
      ElMessage.success("新增成功");
    } else {
      await editUser(params);
      ElMessage.success("编辑成功");
    }
    openPromise.value.resolve();
    dialogVisible.value = false;
  });
}

function open(userId?: number) {
  deptTree.value = getDeptTree();
  isAdd.value = !userId;
  if (userId) {
    loadDetail(userId);
  }
  dialogVisible.value = true;
  return new Promise(resolve => {
    openPromise.value.resolve = resolve;
  });
}
defineExpose({
  open
});
</script>

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