import editForm from "../components/form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";

import {
  deletePermissionAPI,
  getPermissionListAPI,
  postAddPermissionAPI,
  putUpdatePermissionAPI
} from "@/api/system";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import type { PermissionInfo } from "types/system";
export const usePermission = () => {
  /**
   * 表单
   */
  const form = reactive({
    title: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref();
  /**
   * 数据列表
   */
  const dataList = ref<PermissionInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref(true);
  /**
   * 获取菜单类型
   * @param type 菜单类型
   * @param text 文本
   * @returns
   */
  const getMenuType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "菜单" : "primary";
      case 1:
        return text ? "iframe" : "warning";
      case 2:
        return text ? "外链" : "danger";
      case 3:
        return text ? "按钮" : "info";
    }
  };
  /**
   * 表格数据
   */
  const columns: TableColumnList = [
    {
      label: "权限名称",
      prop: "title",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row.icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{transformI18n(row.title)}</span>
        </>
      )
    },
    {
      label: "权限类型",
      prop: "menu_type",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={getMenuType(row.menu_type)}
          effect="plain"
        >
          {getMenuType(row.menu_type, true)}
        </el-tag>
      )
    },
    {
      label: "路由路径",
      prop: "path"
    },
    {
      label: "组件路径",
      prop: "component",
      formatter: ({ path, component }) =>
        isAllEmpty(component) ? path : component
    },
    {
      label: "权限标识",
      prop: "auths"
    },
    {
      label: "排序",
      prop: "rank",
      width: 100
    },
    {
      label: "隐藏",
      prop: "show_link",
      formatter: ({ show_link }) => (show_link ? "否" : "是"),
      width: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 230,
      slot: "operation"
    }
  ];
  /**
   * 搜索
   */
  const onSearch = async () => {
    loading.value = true; // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    const res = await getPermissionListAPI({
      page: 1,
      pageSize: 9999,
      ...form
    });
    if (res.success) {
      let newData = res.data.result;
      dataList.value = handleTree(newData, "id", "parent_id"); // 处理成树结构
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  };
  /**
   * 重置表单
   * @param formEl
   * @returns
   */
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  const formatHigherOptions = treeList => {
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].title = transformI18n(treeList[i].title);
      formatHigherOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  };
  const openDialog = (title = "新增", row?: PermissionInfo) => {
    addDialog({
      title: `${title}权限`,
      props: {
        formInline: {
          id: row?.id ?? "",
          higherOptions: formatHigherOptions(cloneDeep(dataList.value)),
          parent_id: row?.parent_id ?? "",
          title: row?.title ?? "",
          menu_type: row?.menu_type ?? 0,
          name: row?.name ?? "",
          path: row?.path ?? "",
          component: row?.component ?? "",
          rank: row?.rank ?? 99,
          redirect: row?.redirect ?? "",
          icon: row?.icon ?? "",
          extra_icon: row?.extra_icon ?? "",
          enter_transition: row?.enter_transition ?? "",
          leave_transition: row?.leave_transition ?? "",
          active_path: row?.active_path ?? "",
          auths: row?.auths ?? "",
          frame_src: row?.frame_src ?? "",
          frame_loading: row?.frame_loading ?? true,
          keep_alive: row?.keep_alive ?? false,
          hidden_tag: row?.hidden_tag ?? false,
          fixed_tag: row?.fixed_tag ?? false,
          show_link: row?.show_link ?? true,
          show_parent: row?.show_parent ?? false
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          ref: formRef,
          formInline: {
            id: row?.id ?? "",
            higherOptions: formatHigherOptions(cloneDeep(dataList.value)),
            parent_id: row?.parent_id ?? "",
            title: row?.title ?? "",
            menu_type: row?.menu_type ?? 0,
            name: row?.name ?? "",
            path: row?.path ?? "",
            component: row?.component ?? "",
            rank: row?.rank ?? 99,
            redirect: row?.redirect ?? "",
            icon: row?.icon ?? "",
            extra_icon: row?.extra_icon ?? "",
            enter_transition: row?.enter_transition ?? "",
            leave_transition: row?.leave_transition ?? "",
            active_path: row?.active_path ?? "",
            frame_src: row?.frame_src ?? "",
            auths: row?.auths ?? "",
            frame_loading: row?.frame_loading ?? true,
            keep_alive: row?.keep_alive ?? false,
            hidden_tag: row?.hidden_tag ?? false,
            fixed_tag: row?.fixed_tag ?? false,
            show_link: row?.show_link ?? true,
            show_parent: row?.show_parent ?? false
          }
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as PermissionInfo;
        console.log(curData);
        function chores() {
          message(
            `您${title}了权限名称为${transformI18n(curData.title)}的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              let addForm = {
                menu_type: 0,
                parent_id: "",
                title: "",
                name: "",
                path: "",
                component: "",
                rank: 99,
                redirect: "",
                icon: "",
                extra_icon: "",
                enter_transition: "",
                leave_transition: "",
                active_path: "",
                auths: "",
                frame_src: "",
                frame_loading: true,
                keep_alive: false,
                hidden_tag: false,
                fixed_tag: false,
                show_link: true,
                show_parent: false
              };
              for (let key in addForm) {
                // 检查第二个字典是否包含相同的键
                if (key in curData) {
                  // 将第二个字典中对应键的值赋给第一个字典
                  addForm[key] = curData[key];
                }
              }
              const res = await postAddPermissionAPI(addForm);
              if (res.code === 200) {
                // 实际开发先调用新增接口，再进行下面操作
                chores();
              } else {
                message(`添加失败！`, { type: "success" });
              }
            } else {
              let updateForm = {
                menu_type: 0,
                parent_id: "",
                title: "",
                name: "",
                path: "",
                component: "",
                rank: 99,
                redirect: "",
                icon: "",
                extra_icon: "",
                enter_transition: "",
                leave_transition: "",
                active_path: "",
                auths: "",
                frame_src: "",
                frame_loading: true,
                keep_alive: false,
                hidden_tag: false,
                fixed_tag: false,
                show_link: true,
                show_parent: false
              };
              for (let key in updateForm) {
                // 检查第二个字典是否包含相同的键
                if (key in curData) {
                  // 将第二个字典中对应键的值赋给第一个字典
                  updateForm[key] = curData[key];
                }
              }
              const res = await putUpdatePermissionAPI(curData.id, updateForm);
              if (res.code === 200) {
                chores();
              } else {
                message(`更新失败！`, { type: "error" });
              }
            }
          }
        });
      }
    });
  };
  const handleDelete = async (row: PermissionInfo) => {
    const res = await deletePermissionAPI(row.id);
    if (res.code === 200) {
      message(`您删除了权限名称为${transformI18n(row.title)}的这条数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message("权限删除失败！", { type: "error" });
    }
  };
  onMounted(() => {
    onSearch();
  });
  return {
    form,
    formRef,
    dataList,
    loading,
    columns,
    onSearch,
    resetForm,
    openDialog,
    handleDelete
  };
};
