import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import {
  getAdminList,
  addAdmin,
  updateAdmin,
  deleteAdmin,
  resetPassword
} from "@/api/admin";
import { getAllRoles } from "@/api/role";
import {
  type Ref,
  h,
  ref,
  toRaw,
  reactive,
  onMounted
} from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadioButton,
  ElMessageBox
} from "element-plus";
import type { AdminFormItem, AdminSearchForm, RoleOption } from "./types";

export function useAdmin(tableRef: Ref) {
  const form = reactive<AdminSearchForm>({
    username: "",
    phone: "",
    roleIds: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const selectedNum = ref(0);
  const roleOptions = ref<RoleOption[]>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "管理员ID",
      prop: "id",
      width: 90
    },
    {
      label: "用户名",
      prop: "username",
      minWidth: 120
    },
    {
      label: "真实姓名",
      prop: "realName",
      minWidth: 120
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 120
    },
    {
      label: "角色",
      prop: "roleName",
      minWidth: 120
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      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={2}
          active-text="启用"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  // 状态切换
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${row.status === 2 ? "停用" : "启用"}</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
        });
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign({}, switchLoadMap.value[index], {
            loading: false
          });
          message(`已${row.status === 2 ? "停用" : "启用"}管理员 ${row.username}`, {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status = row.status === 2 ? 1 : 2;
      });
  }

  // 删除
  async function handleDelete(row: AdminFormItem) {
    try {
      const res = await deleteAdmin(row.id);
      if (res.code === 200 || res.code === 0) {
        message(`已成功删除管理员 ${row.username}`, { type: "success" });
        onSearch();
      } else {
        message(res.message || "删除失败", { type: "error" });
      }
    } catch (error) {
      message("删除失败", { type: "error" });
    }
  }

  // 分页
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

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

  // 选择变化
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 取消选择
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 批量删除
  async function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const ids = curSelected.map(item => item.id);
    message(`已删除管理员ID为 ${ids.join(",")} 的数据`, { type: "success" });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      // 只添加非空的搜索条件
      if (form.username) searchParams.username = form.username;
      if (form.phone) searchParams.phone = form.phone;
      if (form.roleIds) searchParams.roleIds = form.roleIds;
      if (form.status) searchParams.status = form.status;
      
      const { data } = await getAdminList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } catch (error) {
      console.error("获取管理员列表失败:", error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  // 重置表单
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    onSearch();
  };

  // 打开弹窗
  function openDialog(title = "新增", row?: AdminFormItem) {
    const dialogForm = reactive<AdminFormItem>({
      id: row?.id,
      username: row?.username ?? "",
      password: "",
      realName: row?.realName ?? "",
      phone: row?.phone ?? "",
      email: row?.email ?? "",
      roleIds: row?.roleIds ?? "",
      status: row?.status ?? 1,
      remark: row?.remark ?? ""
    });

    addDialog({
      title: `${title}管理员`,
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={dialogForm} label-width="100px">
          <ElFormItem
            label="用户名"
            prop="username"
            rules={[{ required: true, message: "请输入用户名", trigger: "blur" }]}
          >
            <ElInput
              v-model={dialogForm.username}
              placeholder="请输入用户名"
              clearable
              disabled={title === "修改"}
            />
          </ElFormItem>
          {title === "新增" && (
            <ElFormItem
              label="密码"
              prop="password"
              rules={[{ required: true, message: "请输入密码", trigger: "blur" }]}
            >
              <ElInput
                v-model={dialogForm.password}
                type="password"
                placeholder="请输入密码"
                show-password
                clearable
              />
            </ElFormItem>
          )}
          <ElFormItem
            label="真实姓名"
            prop="realName"
            rules={[{ required: true, message: "请输入真实姓名", trigger: "blur" }]}
          >
            <ElInput v-model={dialogForm.realName} placeholder="请输入真实姓名" clearable />
          </ElFormItem>
          <ElFormItem
            label="手机号"
            prop="phone"
            rules={[
              { required: true, message: "请输入手机号", trigger: "blur" },
              { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
            ]}
          >
            <ElInput v-model={dialogForm.phone} placeholder="请输入手机号" clearable />
          </ElFormItem>
          <ElFormItem label="邮箱" prop="email">
            <ElInput v-model={dialogForm.email} placeholder="请输入邮箱" clearable />
          </ElFormItem>
          <ElFormItem
            label="角色"
            prop="roleIds"
            rules={[{ required: true, message: "请选择角色", trigger: "change" }]}
          >
            <ElSelect v-model={dialogForm.roleIds} placeholder="请选择角色" class="w-full">
              {roleOptions.value.map(item => (
                <ElOption key={item.id} label={item.name} value={item.id} />
              ))}
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="状态" prop="status">
            <ElRadioGroup v-model={dialogForm.status}>
              <ElRadioButton value={1}>启用</ElRadioButton>
              <ElRadioButton value={2}>停用</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="备注" prop="remark">
            <ElInput
              v-model={dialogForm.remark}
              type="textarea"
              placeholder="请输入备注"
              rows={3}
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) return;

        try {
          const submitData = {
            ...toRaw(dialogForm),
            password: title === "新增" ? dialogForm.password : undefined
          };

          if (title === "新增") {
            const res = await addAdmin(submitData);
            if (res.code === 200 || res.code === 0) {
              message(`新增管理员 ${dialogForm.username} 成功`, { type: "success" });
              done();
              onSearch();
            } else {
              message(res.message || "新增失败", { type: "error" });
            }
          } else {
            const res = await updateAdmin({ ...submitData, id: row.id });
            if (res.code === 200 || res.code === 0) {
              message(`修改管理员 ${dialogForm.username} 成功`, { type: "success" });
              done();
              onSearch();
            } else {
              message(res.message || "修改失败", { type: "error" });
            }
          }
        } catch (error) {
          message("操作失败", { type: "error" });
        }
      }
    });
  }

  // 重置密码
  const pwdForm = reactive({
    newPwd: ""
  });

  function handleReset(row: AdminFormItem) {
    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>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: async (done) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) return;

        try {
          const res = await resetPassword({ id: row.id, newPassword: pwdForm.newPwd });
          if (res.code === 200 || res.code === 0) {
            message(`已成功重置 ${row.username} 的密码`, { type: "success" });
            done();
          } else {
            message(res.message || "重置密码失败", { type: "error" });
          }
        } catch (error) {
          message("重置密码失败", { type: "error" });
        }
      }
    });
  }

  // 获取角色列表
  async function fetchRoleOptions() {
    try {
      const { data } = await getAllRoles();
      roleOptions.value = data || [];
    } catch (error) {
      console.error("获取角色列表失败:", error);
    }
  }

  onMounted(async () => {
    await fetchRoleOptions();
    onSearch();
  });

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