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 {
  getRoleList,
  addRole,
  updateRole,
  deleteRole
} from "@/api/role";
import { getRoleMenu, getRoleMenuIds, saveRoleMenus } from "@/api/system";
import { handleTree } from "@/utils/tree";
import {
  ref,
  toRaw,
  reactive,
  onMounted
} from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElRadioGroup,
  ElRadioButton,
  ElMessageBox
} from "element-plus";
import type { FormItemProps, SearchFormProps } from "./types";

export function useRole() {
  const form = reactive<SearchFormProps>({
    name: "",
    code: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const isDataLoaded = ref(false);
  const { switchStyle } = usePublicHooks();
  const menuTree = ref([]);
  const checkedMenuIds = ref<string[]>([]);
  const roleMenuTreeRef = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "id",
      width: 90
    },
    {
      label: "角色名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "角色标识",
      prop: "code",
      minWidth: 120
    },
    {
      label: "状态",
      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={0}
          active-text="启用"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 160,
      showOverflowTooltip: true
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  // 状态切换
  function onChange({ row, index }) {
    if (!isDataLoaded.value) {
      return;
    }
    ElMessageBox.confirm(
      `确认要<strong>${row.status === 0 ? "停用" : "启用"}</strong>角色<strong style='color:var(--el-color-primary)'>${row.name}</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign({}, switchLoadMap.value[index], {
          loading: true
        });
        try {
          const res = await updateRole({ id: row.id, status: row.status });
          if (res.code === 200) {
            message(`已${row.status === 0 ? "停用" : "启用"}角色 ${row.name}`, {
              type: "success"
            });
          } else {
            row.status = row.status === 0 ? 1 : 0;
            message(res.message || "操作失败", { type: "error" });
          }
        } catch (error) {
          row.status = row.status === 0 ? 1 : 0;
          message("操作失败", { type: "error" });
        } finally {
          switchLoadMap.value[index] = Object.assign({}, switchLoadMap.value[index], {
            loading: false
          });
        }
      })
      .catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
  }

  // 删除
  async function handleDelete(row: FormItemProps) {
    try {
      const res = await deleteRole(row.id);
      if (res.code === 200) {
        message(`已成功删除角色 ${row.name}`, { 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) {
    console.log("handleSelectionChange", val);
  }

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

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

  // 加载角色菜单数据
  async function loadRoleMenus(roleId: number) {
    try {
      const menuRes = await getRoleMenu();
      menuTree.value = handleTree(menuRes.data || []);
    } catch {
      menuTree.value = [];
    }
    try {
      const idsRes = await getRoleMenuIds({ id: roleId });
      checkedMenuIds.value = (idsRes.data || []).map(String);
    } catch {
      checkedMenuIds.value = [];
    }
  }

  // 打开弹窗
  async function openDialog(title = "新增", row?: FormItemProps) {
    // 将数据复制到表单对象
    if (row) {
      form.name = row.name ?? "";
      form.code = row.code ?? "";
      form.status = row.status ?? 1;
      form.remark = row.remark ?? "";
      await loadRoleMenus(row.id);
    } else {
      form.name = "";
      form.code = "";
      form.status = 1;
      form.remark = "";
      menuTree.value = [];
      checkedMenuIds.value = [];
    }

    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.id,
          name: row?.name ?? "",
          code: row?.code ?? "",
          status: row?.status ?? 1,
          remark: row?.remark ?? ""
        }
      },
      width: "50%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={form} label-width="80px">
          <ElFormItem
            label="角色名称"
            prop="name"
            rules={[{ required: true, message: "请输入角色名称", trigger: "blur" }]}
          >
            <ElInput v-model={form.name} placeholder="请输入角色名称" clearable />
          </ElFormItem>
          <ElFormItem
            label="角色标识"
            prop="code"
            rules={[{ required: true, message: "请输入角色标识", trigger: "blur" }]}
          >
            <ElInput
              v-model={form.code}
              placeholder="请输入角色标识"
              clearable
              disabled={title === "修改"}
            />
          </ElFormItem>
          <ElFormItem label="状态" prop="status">
            <ElRadioGroup v-model={form.status}>
              <ElRadioButton value={1}>启用</ElRadioButton>
              <ElRadioButton value={0}>停用</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem label="备注" prop="remark">
            <ElInput
              v-model={form.remark}
              type="textarea"
              placeholder="请输入备注"
              rows={3}
            />
          </ElFormItem>
          <ElFormItem label="菜单权限">
            <div style={{
              maxHeight: "300px",
              overflow: "auto",
              width: "100%",
              border: "1px solid var(--el-border-color)",
              borderRadius: "4px",
              padding: "8px"
            }}>
              {menuTree.value.length > 0 ? (
                <el-tree
                  ref={roleMenuTreeRef}
                  data={menuTree.value}
                  props={{ children: "children", label: "title" }}
                  node-key="id"
                  show-checkbox
                  default-expand-all
                  default-checked-keys={checkedMenuIds.value}
                />
              ) : (
                <div style={{ textAlign: "center", padding: "16px", color: "var(--el-text-color-placeholder)" }}>
                  {row ? "暂无菜单数据" : "新增角色请先保存，再编辑分配菜单"}
                </div>
              )}
            </div>
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) return;

        try {
          let roleId = row?.id;

          if (title === "新增") {
            const res = await addRole(toRaw(form));
            if (res.code === 200) {
              roleId = res.data?.id;
              message(`新增角色 ${form.name} 成功`, { type: "success" });
            } else {
              message(res.message || "新增失败", { type: "error" });
              return;
            }
          } else {
            const res = await updateRole({ ...toRaw(form), id: row.id });
            if (res.code === 200) {
              message(`修改角色 ${form.name} 成功`, { type: "success" });
            } else {
              message(res.message || "修改失败", { type: "error" });
              return;
            }
          }

          // 保存角色菜单关联
          if (roleId && roleMenuTreeRef.value) {
            const checkedKeys = roleMenuTreeRef.value.getCheckedKeys(false);
            const halfCheckedKeys = roleMenuTreeRef.value.getHalfCheckedKeys();
            const allMenuIds = [...checkedKeys, ...halfCheckedKeys].map(Number);
            await saveRoleMenus({ roleId, menuIds: allMenuIds });
          }

          done();
          onSearch();
        } catch (error) {
          message("操作失败", { type: "error" });
        }
      }
    });
  }

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
