import {
  deleteUserList,
  editUserList,
  getAllRoleList,
  getUserList,
  AddUserList,
  lockUserList,
  getAllDeptList,
  getAllPostList
} from "@/api/system";
import { type PaginationProps } from "@pureadmin/table";
import { log } from "console";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, computed, onMounted } from "vue";

export function useUser() {
  const form = reactive({
    username: "",
    phone: "",
    deptId: ""
  });
  const UpdateForm: any = ref({
    username: "", //用户名
    password: "", //密码
    phone: "", //电话号码
    nickname: "", //昵称
    name: "", //姓名
    email: "", //邮箱地址
    role: "", //角色id集合
    post: "", //岗位集合
    deptId: "", //所属部门ID
    avatar: "" //头像
  });
  const dialogType = ref(1);
  const dataList = ref([]);
  const optionList = ref([]);
  const optionDeptList = ref([]);
  const optionPostList = ref([]);
  const loading = ref(false);
  const dialogUpdateVisible = ref(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "用户名",
      prop: "username",
      minWidth: 130
    },
    {
      label: "电话号码",
      prop: "phone",
      minWidth: 130
    },
    {
      label: "角色",
      prop: "roleList",
      minWidth: 130,
      formatter: ({ roleList }) => {
        let RoleName = "";
        roleList.forEach(item => {
          RoleName = RoleName + "\n" + item.roleName;
        });
        return RoleName;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  async function UpdateFormSubmit() {
    if (dialogType.value == 1) {
      console.log(UpdateForm.value);
      const { status, msg } = await AddUserList(UpdateForm.value);
      if (status == 1) {
        ElMessage({
          message: "新增账号成功",
          type: "success"
        });
        dialogUpdateVisible.value = false;
        UpdateForm.value = {
          account: "",
          username: "",
          password: "",
          roleIds: [],
          phone: "",
          adminType: "1"
        };
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    } else {
      console.log(UpdateForm.value);
      const { status, msg } = await editUserList(UpdateForm.value);
      if (status == 1) {
        ElMessage({
          message: "修改账号成功",
          type: "success"
        });
        dialogUpdateVisible.value = false;
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    }
  }
  // 获取角色列表
  async function RoleList() {
    const { data } = await getAllRoleList({});
    const option = data.map(item => {
      return {
        label: item.roleName,
        Id: item.roleId
      };
    });
    optionList.value = option;
  }
  RoleList();
  // 获取部门列表
  async function DeptList() {
    const { data } = await getAllDeptList({});
    const option = data.map(item => {
      return {
        label: item.name,
        Id: item.deptId
      };
    });
    optionDeptList.value = option;
  }
  DeptList();
  // 获取部门列表
  async function PostList() {
    const { data } = await getAllPostList({});
    const option = data.map(item => {
      return {
        label: item.postName,
        Id: item.postId
      };
    });
    optionPostList.value = option;
  }
  PostList();
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否删除该用户?  用户名称为:${row.username}`,
      "提示",
      {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      const { status, msg } = await deleteUserList(row.userId);
      if (status == 1) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    });
  }
  function AddUser() {
    UpdateForm.value = {
      username: "", //用户名
      password: "", //密码
      phone: "", //电话号码
      nickname: "", //昵称
      name: "", //姓名
      email: "", //邮箱地址
      role: "", //角色id集合
      deptId: "", //所属部门ID
      avatar: "" //头像
    };
    dialogUpdateVisible.value = true;
    dialogType.value = 1;
  }
  function handleUpdate(row) {
    dialogType.value = 2;
    dialogUpdateVisible.value = true;
    UpdateForm.value = {
      userId: row.userId ? row.userId : "", //用户ID
      username: row.username ? row.username : "", //用户名
      phone: row.phone ? row.phone : "", //电话号码
      avatar: row.avatar ? row.avatar : "", //头像
      nickname: row.nickname ? row.nickname : "", //昵称
      name: row.name ? row.name : "", //姓名
      email: row.email ? row.email : "", //邮箱地址
      deptId: row.deptId ? row.deptId : "", //所属部门ID
      role: row.roleList
        ? row.roleList.map(item => {
          return item.roleId;
        })
        : [], //角色id集合
      post: row.postList
        ? row.postList.map(item => {
          return item.postId;
        })
        : [] //岗位id集合
    };
  }

  function handleSizeChange(val: number) {
    if (typeof val === "number") {
      pagination.pageSize = val;
      onSearch();
    }
  }

  function handleCurrentChange(val: number) {
    if (typeof val === "number") {
      pagination.currentPage = val;
      onSearch();
    }
  }

  function handleSelectionChange(val) { }

  // 搜索函数（请求表格数据列表）
  function submit(e: { keyCode: number }) {
    if (e.keyCode == 229) {
      return;
    } else {
      onSearch("search");
    }
  }
  async function onSearch(type = "") {
    if (type == "search" && !Object.values(form).some(item => !!item)) {
      return ElMessage({
        message: "请输入查询条件",
        type: "error"
      });
    }
    if (type == "all") {
      (form.username = ""), (form.phone = ""), (form.deptId = "");
    }
    loading.value = true;
    const { data } = await getUserList({
      ...form,
      pageSize: pagination.pageSize,
      pageNum: pagination.currentPage
    });
    dataList.value = data.records;
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  // 锁定用户
  const handleLock = row => {
    ElMessageBox.confirm(
      `是否锁定该用户?  用户名称为:${row.username}`,
      "提示",
      {
        confirmButtonText: "锁定",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      console.log("[  ] >", {
        userId: row.userId,
        username: row.username
      });
      const { status, msg } = await lockUserList({
        userId: row.userId,
        username: row.username
      });
      if (status == 1) {
        ElMessage({
          message: "锁定用户成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    });
  };
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    dialogUpdateVisible,
    UpdateFormSubmit,
    submit,
    UpdateForm,
    optionList,
    optionDeptList,
    optionPostList,
    dialogType,
    AddUser,
    onSearch,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleLock
  };
}
