import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import editForm from "../form/index.vue";
import { getPermissionList } from "@/api/system";
import { type Ref, h, ref, computed, reactive, onMounted } from "vue";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";

export function usePermission(tableRef: Ref) {
  const form = reactive({
    permissionName: "",
    permissionCode: "",
    status: undefined as number | undefined
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const switchLoadMap = ref({});

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "权限编号",
      prop: "id",
      width: 90
    },
    {
      label: "权限名称",
      prop: "permissionName",
      minWidth: 150,
      align: "left",
      cellRenderer: ({ row }) => (
        <span style={{ paddingLeft: `${(row.level || 0) * 20}px` }}>
          {row.permissionName}
        </span>
      )
    },
    {
      label: "权限编码",
      prop: "permissionCode",
      minWidth: 150
    },
    {
      label: "权限类型",
      prop: "permissionType",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const typeMap = {
          1: { text: "菜单", type: "primary" },
          2: { text: "按钮", type: "warning" },
          3: { text: "接口", type: "success" }
        };
        const typeInfo = typeMap[row.permissionType] || {
          text: "未知",
          type: "info"
        };
        return (
          <el-tag type={typeInfo.type} effect="plain">
            {typeInfo.text}
          </el-tag>
        );
      }
    },
    {
      label: "路径",
      prop: "path",
      minWidth: 150
    },
    {
      label: "排序",
      prop: "sortOrder",
      width: 80
    },
    {
      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
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 120,
      prop: "createTime",
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "h-5!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  function onChange({ row, index }) {
    const action = row.status === 0 ? "停用" : "启用";
    ElMessageBox.confirm(
      `确认要<strong>${action}</strong><strong style='color:var(--el-color-primary)'>${row.permissionName}</strong>权限吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = { loading: true };
        setTimeout(() => {
          switchLoadMap.value[index] = { loading: false };
          message(`已成功${action}权限`, { type: "success" });
        }, 300);
      })
      .catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
  }

  function handleDelete(row) {
    message(`您删除了权限编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  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();
  }

  function onbatchDel() {
    const curSelected = tableRef.value?.getTableRef().getSelectionRows();
    message(`已删除权限编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value?.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const { code, data } = await getPermissionList({
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
        keyword: form.permissionName || form.permissionCode || undefined
      });
      if (code === 200) {
        dataList.value = data?.records || [];
        pagination.total = Number(data?.total) || 0;
        pagination.pageSize = Number(data?.size) || 10;
        pagination.currentPage = Number(data?.current) || 1;
      }
    } catch (error) {
      console.error(error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 500);
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}权限`,
      props: {
        formInline: {
          title,
          id: row?.id ?? "",
          parentId: row?.parentId ?? 0,
          permissionName: row?.permissionName ?? "",
          permissionCode: row?.permissionCode ?? "",
          permissionType: row?.permissionType ?? 1,
          path: row?.path ?? "",
          component: row?.component ?? "",
          icon: row?.icon ?? "",
          apiUrl: row?.apiUrl ?? "",
          apiMethod: row?.apiMethod ?? "",
          sortOrder: row?.sortOrder ?? 0,
          visible: row?.visible ?? 1,
          status: row?.status ?? 1
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value?.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了权限名称为${curData.permissionName}的这条数据`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef?.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            if (title === "新增") {
              chores();
            } else {
              chores();
            }
          }
        });
      }
    });
  }

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

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

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