import dayjs from "dayjs";
import editForm from "../components/form.vue";
import roleForm from "../components/role.vue";
import permissionForm from "../components/permission.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import croppingUpload from "../components/upload.vue";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { hideTextAtIndex, getKeyList, isAllEmpty } from "@pureadmin/utils";
import Avatar from "@/assets/user.png";
import {
  getDepartmentListAPI,
  getUserListAPI,
  postAddUserAPI,
  putUpdateUserAPI,
  deleteUserAPI,
  putUpdateUserPasswordAPI,
  putUpdateUserRolesAPI,
  getUserRolesAPI,
  deleteUserListAPI,
  getUserGetDepartmentRolesAPI
} from "@/api/system";
import { postUploadAvatarAPI } from "@/api/user";
import { ElForm, ElInput, ElFormItem, ElProgress } from "element-plus";
import { type Ref, h, ref, watch, computed, reactive, onMounted } from "vue";
import type { DepartmentInfo, UserInfo } from "types/system";

import { handleTree } from "@/utils/tree";

export const useUser = (tableRef: Ref, treeRef: Ref) => {
  /**查询表单 */
  const form = reactive({
    id: "",
    department_id: "",
    username: "",
    nickname: "",
    phone: "",
    email: "",
    gender: "",
    status: ""
  });
  const formRef = ref(null);
  const ruleFormRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<UserInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref<boolean>(true);

  // 上传头像信息
  const avatarInfo = ref();
  /**
   * 标签样式
   */
  const { tagStyle } = usePublicHooks();
  /**
   * 部门树形列表
   */
  const higherOptions = ref();
  /**
   * 部门树形列表
   */
  const treeData = ref<DepartmentInfo[]>([]);
  /**
   * 部门树形列表加载状态
   */
  const treeLoading = ref(true);
  /**
   * 已选用户数量
   */
  const selectedNum = ref(0);
  /**
   * 分页配置
   */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 30, 40, 50]
  });
  /**
   * 表格列配置
   */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户账号",
      prop: "username"
    },
    {
      label: "用户头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar || Avatar}
          preview-src-list={Array.of(row.avatar || Avatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      )
    },
    {
      label: "用户姓名",
      prop: "nickname"
    },
    {
      label: "性别",
      prop: "gender",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.gender === 0 ? "danger" : null}
          effect="plain"
        >
          {row.gender === 0 ? "女" : "男"}
        </el-tag>
      )
    },
    {
      label: "手机号码",
      prop: "phone",
      formatter: ({ phone }) => hideTextAtIndex(phone, { start: 3, end: 6 })
    },
    {
      label: "状态",
      prop: "status",
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  /**
   * 按钮类型
   */
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  /**
   * 密码强度
   */
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref<number>(0);
  const roleOptions = ref([]);

  /**
   * 删除用户
   * @param row
   */
  const handleDelete = async (row: UserInfo) => {
    const res = await deleteUserAPI(row.id);
    if (res.code === 200) {
      message(`您删除了用户账号为${row.username}的这条数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message("删除失败！", { type: "error" });
    }
  };
  /**
   * 处理每页数量变化
   * @param val
   */
  const handleSizeChange = async (val: number) => {
    const res = await getUserListAPI({
      page: pagination.currentPage,
      pageSize: val,
      department_id: form.department_id,
      username: form.username,
      nickname: form.nickname,
      gender: form.gender,
      email: form.email,
      status: form.status,
      phone: form.phone
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
    }
  };
  // 处理页码变化
  const handleCurrentChange = async (val: number) => {
    const res = await getUserListAPI({
      page: val,
      pageSize: pagination.pageSize,
      department_id: form.department_id,
      username: form.username,
      nickname: form.nickname,
      gender: form.gender,
      email: form.email,
      status: form.status,
      phone: form.phone
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
    }
  };

  /** 当CheckBox选择项发生变化时会触发该事件 */
  const handleSelectionChange = (val: any) => {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  };

  /** 取消选择 */
  const onSelectionCancel = () => {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  };

  /** 批量删除 */
  const onbatchDel = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await deleteUserListAPI({
      userIds: getKeyList(curSelected, "id")
    });
    if (res.code === 200) {
      message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, { type: "error", duration: 5000 });
    }
  };
  /**
   * 查询
   */
  const onSearch = async () => {
    loading.value = true;
    const { data } = await getUserListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      department_id: form.department_id,
      username: form.username,
      nickname: form.nickname,
      gender: form.gender,
      email: form.email,
      status: form.status,
      phone: form.phone
    });
    dataList.value = data.result;
    pagination.total = data.total;
    pagination.currentPage = data.page;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  };
  /**
   * 重置表单
   * @param formEl
   * @returns
   */
  const resetForm = async (formEl: any) => {
    if (!formEl) return;
    form.department_id = "";
    treeRef.value.onTreeReset();
    formEl.resetFields();
    await onSearch();
  };

  /**树形选择器选中 */
  const onTreeSelect = async ({ id, selected }) => {
    form.department_id = selected ? id : "";
    await onSearch();
  };

  const formatHigherOptions = (treeList: any) => {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  };
  /**
   * 打开弹窗
   * @param way
   * @param row
   */
  const openDialog = (way = "新增", row?: UserInfo) => {
    addDialog({
      title: `${way}用户`,
      props: {
        formInline: {
          way: way,
          id: row?.id ?? "",
          higherOptions: formatHigherOptions(higherOptions.value),
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          password: "",
          phone: row?.phone ?? "",
          email: row?.email ?? "",
          gender: row?.gender ?? "",
          department_id: row?.department_id ?? "",
          status: row?.status ?? 1
        }
      },
      width: "46%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          ref: formRef,
          formInline: {
            way: way,
            id: row?.id ?? "",
            higherOptions: formatHigherOptions(higherOptions.value),
            username: row?.username ?? "",
            nickname: row?.nickname ?? "",
            password: "",
            phone: row?.phone ?? "",
            email: row?.email ?? "",
            gender: row?.gender ?? "",
            department_id: row?.department_id ?? "",
            status: row?.status ?? 1
          }
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as UserInfo;
        function chores() {
          message(`您${way}了用户账号为${curData.username}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            if (way === "新增") {
              let addForm = {
                username: "string",
                password: "string",
                gender: 1,
                avatar: "",
                email: "",
                nickname: "普通用户",
                phone: "",
                department_id: "",
                status: 1
              };
              for (let key in addForm) {
                // 检查第二个字典是否包含相同的键
                if (key in curData) {
                  // 将第二个字典中对应键的值赋给第一个字典
                  addForm[key] = curData[key];
                }
              }
              const res = await postAddUserAPI(addForm);
              if (res.code === 200) {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              } else {
                message("添加失败", { type: "error" });
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              let updateForm = {
                username: "string",
                gender: 1,
                avatar: "",
                email: "",
                nickname: "普通用户",
                phone: "",
                department_id: "",
                status: 1
              };
              for (let key in updateForm) {
                // 检查第二个字典是否包含相同的键
                if (key in curData) {
                  // 将第二个字典中对应键的值赋给第一个字典
                  updateForm[key] = curData[key];
                }
              }
              const res = await putUpdateUserAPI(curData.id, updateForm);
              if (res.code === 200) {
                chores();
              } else {
                message(`更新失败！`, { type: "error" });
              }
            }
          }
        });
      }
    });
  };

  const cropRef = ref();
  /** 上传头像 */
  const handleUpload = (row: UserInfo) => {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(croppingUpload, {
          ref: cropRef,
          imgSrc: row.avatar || Avatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: async done => {
        const res = await postUploadAvatarAPI(row.id, {
          file: avatarInfo.value.blob
        });
        if (res.code === 200) {
          // 根据实际业务使用avatarInfo.value和row里的某些字段去调用上传头像接口即可
          message(`更新成功！`, { type: "success" });
          onSearch(); // 刷新表格数据
        } else {
          message(`更新失败！`, { type: "error" });
        }
        done(); // 关闭弹框
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  };
  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  const handleReset = (row: UserInfo) => {
    addDialog({
      title: `重置 ${row.username} 的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <div>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码~",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码~"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </div>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            const res = await putUpdateUserPasswordAPI(row.id, {
              password: pwdForm.newPwd
            });
            if (res.code === 200) {
              console.log(pwdForm.newPwd);
              done();
              message(`已成功重置 ${row.username} 的密码`, {
                type: "success"
              });
              onSearch(); // 刷新表格数据
            } else {
              message(`重置 ${row.username} 用户的密码失败！`, {
                type: "error"
              });
              done();
            }
          }
        });
      }
    });
  };

  /** 分配角色 */
  const handleRole = async (row: UserInfo) => {
    // 选中的角色列表
    const idRes = await getUserRolesAPI(row.id);
    const ids = getKeyList(idRes.data.result, "role_id") ?? [];
    const res = await getUserGetDepartmentRolesAPI(row.department_id);
    if (res.success) {
      roleOptions.value = res.data.result;
    } else {
      roleOptions.value = [];
    }
    addDialog({
      title: `分配 ${row.username}--${row.nickname} 用户的角色`,
      props: {
        formInline: {
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          ids
        }
      },
      width: "400px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: async (done, { options }) => {
        const curData = options.props.formInline;
        console.log("curIds", curData.ids);
        const res = await putUpdateUserRolesAPI({
          user_id: row.id,
          role_ids: curData.ids as string[]
        });
        if (res.code === 200) {
          message(`${row.username}--${row.nickname}的角色信息更新成功！`, {
            type: "success",
            duration: 5000
          });
          done(); // 关闭弹框
        } else {
          message(`${row.username}--${row.nickname}的角色信息更新失败！`, {
            type: "error",
            duration: 5000
          });
        }
      }
    });
  };

  /**分配权限 */
  const openPerDialog = async (row: UserInfo) => {
    addDialog({
      title: `权限详情--(${row.username}-${row.nickname})`,
      props: {
        id: row?.id ?? ""
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(permissionForm, { ref: formRef, id: row?.id ?? "" }),
      beforeSure: async done => {
        done();
      }
    });
  };
  onMounted(async () => {
    treeLoading.value = true;
    onSearch();
    // 归属部门
    const res = await getDepartmentListAPI({
      page: 1,
      pageSize: 9999
    });
    if (res.success) {
      const data = res.data.result.sort((a, b) => a.sort - b.sort);
      higherOptions.value = handleTree(data, "id", "parent_id");
      treeData.value = handleTree(data, "id", "parent_id");
      treeLoading.value = false;
    }
  });
  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    openPerDialog,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleDelete,
    handleUpload,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
};
