import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
// import { getRoleList } from "@/api/system";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { type FormItemProps, MunuData } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import type { ElTreeV2 } from "element-plus";
// import { any } from "vue-types";

export function useRole() {
  const form = reactive({
    name: "",
    code: "",
    status: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "id",
      minWidth: 100
    },
    {
      label: "角色名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "角色标识",
      prop: "code",
      minWidth: 150
    },
    {
      label: "状态",
      minWidth: 130,
      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: 150
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  // const buttonClass = computed(() => {
  //   return [
  //     "!h-[20px]",
  //     "reset-margin",
  //     "!text-gray-500",
  //     "dark:!text-white",
  //     "dark:hover:!text-primary"
  //   ];
  // });

  function onChange({ row, index }) {
    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(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message(`已${row.status === 0 ? "停用" : "启用"}${row.name}`, {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleDelete(row) {
    message(`您删除了角色名称为${row.name}的这条数据`, { type: "success" });
    const updatedListData = roleList.value.list.filter(
      item => item.id !== row.id
    );
    roleList.value.list = updatedListData;
    onSearch();
  }

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

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

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }
  const roleList = ref({
    list: [
      {
        createTime: 1605456000000, // 时间戳（毫秒ms）
        updateTime: 1684512000000,
        creator: "admin",
        id: 1,
        name: "超级管理员",
        code: "admin",
        status: 1, // 状态 1 启用 0 停用
        remark: "超级管理员拥有最高权限"
      },
      {
        createTime: 1605456000000,
        updateTime: 1684512000000,
        creator: "admin",
        id: 2,
        name: "普通角色",
        code: "common",
        status: 1,
        remark: "普通角色拥有部分权限"
      }
    ],
    total: 2, // 总条目数
    pageSize: 10, // 每页显示条目个数
    currentPage: 1 // 当前页数
  });
  function getRoleList() {
    // http.request("post", "/login")
    return roleList;
  }

  async function onSearch() {
    loading.value = true;
    // const { data } = await getRoleList(toRaw(form));
    const data = getRoleList();
    dataList.value = data.value.list;
    pagination.total = data.value.total;
    pagination.pageSize = data.value.pageSize;
    pagination.currentPage = data.value.currentPage;

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

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

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          name: row?.name ?? "",
          code: row?.code ?? "",
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      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.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const addItem = {
                createTime: 1605456000000, // 时间戳（毫秒ms）
                updateTime: 1684512000000,
                creator: curData.name,
                id: 3,
                name: "员工",
                code: curData.code,
                status: 1, // 状态 1 启用 0 停用
                remark: curData.remark
              };
              roleList.value.list.push(addItem);
              chores();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  /** 菜单权限 */
  function handleMenu() {
    // message("等菜单管理页面开发后完善");
    drawerShow.value = true;
    Object.assign(menuArr, result);
    selectArr.value = filterSelectArr(menuArr, []);
    console.log(selectArr, "selectArr");
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}
  const drawerShow = ref(false);
  //准备一个数组:数组用于存储勾选的节点的ID(四级的)
  const selectArr = ref<number[]>([]);
  //定义数组存储用户权限的数据
  const menuArr = reactive<MunuData[]>([]);
  //获取tree组件实例
  const treeRef = ref<InstanceType<typeof ElTreeV2>>();
  //树形控件的测试数据
  const defaultProps = {
    children: "children",
    label: "name"
  };
  const filterSelectArr = (allData: any, initArr: any) => {
    allData.forEach((item: any) => {
      if (item.select && item.level == 4) {
        initArr.push(item.id);
      }
      if (item.children && item.children.length > 0) {
        filterSelectArr(item.children, initArr);
      }
    });

    return initArr;
  };
  const result = reactive([
    {
      code: null,
      createTime: "2019-11-15 17:13:06",
      id: 1,
      level: 1,
      name: "全部数据",
      pid: 0,
      select: false,
      status: null,
      toCode: null,
      type: 1,
      updateTime: "2020-09-25 13:47:54",
      children: [
        {
          id: 7,
          createTime: "2020-11-30 16:40:08",
          updateTime: "2021-12-04 19:39:41",
          pid: 1,
          name: "权限管理",
          code: "Acl",
          toCode: "",
          type: 1,
          status: null,
          select: true,
          level: 2,
          children: [
            {
              id: 8,
              createTime: "2020-11-30 16:40:38",
              updateTime: "2021-12-04 19:40:01",
              pid: 7,
              name: "用户管理",
              code: "User",
              toCode: "",
              type: 1,
              status: null,
              select: true,
              level: 3,
              children: [
                {
                  children: [],
                  code: "btn.User.add",
                  createTime: "2020-11-30 16:43:16",
                  id: 11,
                  level: 4,
                  name: "添加用户",
                  pid: 8,
                  select: true,
                  status: null,
                  toCode: "",
                  type: 2,
                  updateTime: "2021-12-04 19:42:37"
                }
              ]
            },
            {
              id: 9,
              createTime: "2020-11-30 16:40:55",
              updateTime: "2021-12-04 19:40:02",
              pid: 7,
              name: "角色管理",
              code: "Role",
              toCode: "",
              type: 1,
              status: null,
              select: true,
              level: 3,
              children: [
                {
                  children: [],
                  code: "btn.Role.assgin",
                  createTime: "2020-11-30 16:50:13",
                  id: 15,
                  level: 4,
                  name: "分配权限",
                  pid: 9,
                  select: false,
                  status: null,
                  toCode: "RoleAuth",
                  type: 2,
                  updateTime: "2021-12-04 19:42:45"
                }
              ]
            },
            {
              id: 10,
              createTime: "2020-11-30 16:41:21",
              updateTime: "2021-12-04 19:40:06",
              pid: 7,
              name: "菜单管理",
              code: "Permission",
              toCode: "",
              type: 1,
              status: null,
              select: true,
              level: 3,
              children: []
            }
          ]
        }
      ]
    }
  ]);
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    // buttonClass,
    drawerShow,
    selectArr,
    menuArr,
    treeRef,
    defaultProps,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleDelete,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
