import "./reset.css";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import {
  getKeyList,
  isAllEmpty,
  deviceDetection
} from "@pureadmin/utils";
import {
  getUserList,
  addUser,
  deleteUser,
  modifyUser
} from "@/api/system";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";

import { ROLES } from '@/global/constDefine'

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧部门树的id
    deptId: "",
    username: "",
    phone: "",
    status: ""
  });
  const editMap = ref({});
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "用户名称",
      prop: "username",
      minWidth: 130,
      cellRenderer: ({ row, index }) => (
        <>
          {editMap.value[index]?.editable ? (
            <el-input v-model={row.username} />
          ) : (
            <p>{row.username}</p>
          )}
        </>
      )
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 130,
      cellRenderer: ({ row, index }) => (
        <>
          {editMap.value[index]?.editable ? (
            <el-input v-model={row.nickname} />
          ) : (
            <p>{row.nickname}</p>
          )}
        </>
      )
    },
    {
      label: "角色",
      prop: "roles",
      minWidth: 130,
      cellRenderer: ({ row, index }) => (
        <div>
          {
            row.roles.map((curname) => {
              // const matchedObj = ROLES.find(obj => { obj.name == curname });
              // console.log('matchedObj', matchedObj);
              return <el-tag > {
                ROLES.find(obj => { if (obj.name == curname) return obj })?.title
              } </el-tag>;
            })
          }
        </div>
      )
    },
    // {
    //   label: "密码",
    //   prop: "password",
    //   minWidth: 130,
    //   cellRenderer: ({ row, index }) => (
    //     <>
    //       {editMap.value[index]?.editable ? (
    //         <el-input v-model={row.id} />
    //       ) : (
    //         <p>{row.id}</p>
    //       )}
    //     </>
    //   )
    // },
    // {
    //   label: "确认密码",
    //   prop: "password2",
    //   minWidth: 130,
    //   cellRenderer: ({ row, index }) => (
    //     <>
    //       {editMap.value[index]?.editable ? (
    //         <el-input v-model={row.id} />
    //       ) : (
    //         <p>{row.id}</p>
    //       )}
    //     </>
    //   )
    // },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      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();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        modifyUser({ user: row }).then((resp) => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );

          if (resp.success) {
            message("已成功修改用户状态", {
              type: "success"
            });
            onSearch();
          } else {
            message("修改用户状态失败", {
              type: "info"
            });
          }
        });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    deleteUser({ username: row.username }).then((resp) => {
      if (resp.success) {
        message(`您删除了用户名为${row.username}的这条数据`, { type: "success" });
        onSearch();
      } else {
        message(`删除用户名为${row.username}的这条数据失败`, { type: "info" });
      }
    });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

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

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

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    console.log('getUserList');
    const { items } = await getUserList(toRaw(form));
    dataList.value = items;
    pagination.total = items.length;
    // pagination.pageSize = data.pageSize;
    // pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.deptId = "";
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.deptId = selected ? id : "";
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          title,
          nickname: row?.nickname ?? "",
          username: row?.username ?? "",
          password: row?.password ?? "",
          roles: row?.roles ?? [],
          status: row?.status ?? 0,
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为${curData.username}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              if (curData.username == 'admin'
                || curData.username == 'root'
                || curData.username == 'eng') {
                message(`不能使用该用户名`, { type: "info" });
                return
              }

              addUser({ user: curData }).then((resp) => {
                if (resp.success) {
                  chores();
                } else {
                  message(`${title}用户名称为${curData.username}失败`, { type: "info" });
                }
              });
              
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              modifyUser({ user: curData}).then((resp) => {
                if (resp.success) {
                  chores();
                } else {
                  message(`${title}用户名称为${curData.username}失败`, { type: "info" });
                }
              });
            }
          }
        });
      }
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <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="my-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>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            const user = row;
            user.password = pwdForm.newPwd;
            modifyUser({ user: user}).then((resp) => {
              if (resp.success) {
                message(`已成功重置 ${row.username} 用户的密码`, {
                  type: "success"
                });
                console.log(pwdForm.newPwd);
                // 根据实际业务使用pwdForm.newPwd和row里的某些字段去调用重置用户密码接口即可
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              } else {
                message(`重置 ${row.username} 用户的密码失败`, { type: "info" });
              }
            });
          }
        });
      }
    });
  }

  onMounted(async () => {
    onSearch();

    // 角色列表
    roleOptions.value = [];
    for (let i = 1; i < ROLES.length; i++) {
      roleOptions.value.push(ROLES[i]);
    }
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleReset,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
