import React, { useEffect, useReducer } from "react";
import { Tree, Input, Card, Tooltip } from "antd";
import styles from "./index.less";
import { doFetch } from "@/utils/doFetch";
import Schedule from "./Schedule";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { useRequest } from "umi";
const { Search } = Input;
const initState = {
  searchValue: "",
  expandedKeys: [],
  autoExpandParent: false,
  treeData: [],
  checkedNode: {},
  show: false,
};
function reducer(state, action) {
  if (action.type == "changeSearch") {
    return {
      ...state,
      autoExpandParent: true,
      expandedKeys: action.expandedKeys,
      searchValue: action.searchValue,
    };
  } else if (action.type == "expand") {
    return {
      ...state,
      autoExpandParent: false,
      expandedKeys: action.expandedKeys,
    };
  } else if (action.type == "getData") {
    return {
      ...state,
      treeData: action.treeData,
    };
  } else if (action.type == "checked") {
    return {
      ...state,
      checkedNode: action.checkedNode,
    };
  } else if (action.type == "flod") {
    return {
      ...state,
      show: action.value,
    };
  }
}
const getParentKey = (key, system) => {
  let parentKey;
  for (let i = 0; i < system.length; i++) {
    const node = system[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
const Calendar = (props) => {
  const [state, dispatch] = useReducer(reducer, initState);
  const {
    searchValue,
    expandedKeys,
    autoExpandParent,
    treeData,
    checkedNode,
    show,
  } = state;
  useEffect(() => {
    reload();
  }, []);
  function reload() {
    doFetch({ url: "/ngic-auth/sysFactory/queryTreeList", params: {} }).then(
      (res) => {
        if (res.code == "0000") {
          let treeData = res?.data?.dataList || [];
          dispatch({ type: "getData", treeData });
          if (checkedNode.key) {
            findChecknode(treeData, checkedNode, (res) => {
              dispatch({ type: "checked", checkedNode: res });
            });
          } else {
            dispatch({
              type: "checked",
              checkedNode: treeData?.length > 0 ? treeData[0] : {},
            });
          }
        }
      }
    );
  }
  const loop = (data) => {
    return data.map((item) => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: "#f50" }}>{searchValue}</span>
            {afterStr}
            <span style={{ color: `${item.isOpen ? "#1890ff" : "#ccc"}` }}>
              {item.isOpen ? "（已开启）" : "（未开启）"}
            </span>
          </span>
        ) : (
          <span>
            {item.title}
            <span style={{ color: `${item.isOpen ? "#1890ff" : "#ccc"}` }}>
              {item.isOpen ? "（已开启）" : "（未开启）"}
            </span>
          </span>
        );
      if (item.children) {
        return { title, key: item.key, children: loop(item.children) };
      }

      return {
        title,
        key: item.key,
      };
    });
  };
  const onExpand = (expandedKeys) => {
    dispatch({ type: "expand", expandedKeys });
  };
  const searchTree = (e) => {
    let value;
    if (e) {
      value = e.target.value;
    } else {
      value = val;
    }
    const dataLists = getAllList();
    const expandedKeys = dataLists
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, treeData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    dispatch({ type: "changeSearch", expandedKeys, searchValue: value });
  };
  const selectTree = (selectedKeys, selectedNodes) => {
    const dataLists = getAllList();
    let checkedNode = dataLists.filter((it) => it.key == selectedKeys[0])[0];
    dispatch({ type: "checked", checkedNode });
  };

  function findChecknode(data, check, callback) {
    let newCheckdata;
    for (let i = 0; i < data.length; i++) {
      let it = data[i];
      if (it.key == check?.key) {
        newCheckdata = {
          key: it.key,
          title: it.title,
          type: it.type,
          isOpen: it.isOpen,
          parentKey: it.parentKey,
        };
        callback(newCheckdata);
      } else if (it.children) {
        findChecknode(it.children, check, callback);
      }
    }
  }

  function getAllList() {
    const dataLists = [];
    const generateLists = (data) => {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        dataLists.push({
          key,
          title: node.title,
          type: node.type,
          isOpen: node.isOpen,
          parentKey: node.parentKey,
        });
        if (node.children) {
          generateLists(node.children, node.key);
        }
      }
    };
    generateLists(treeData);
    return dataLists;
  }
  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        backgroundColor: "#fff",
        minHeight: 300,
      }}
    >
      <div style={{ width: "100%", border: "1px solid rgba(0, 0, 0, 0.06)" }}>
        <div style={{ padding: "16px 20px", fontSize: 16 }}>
          {props.route.name}
        </div>
      </div>
      <div style={{ display: "flex" }}>
        <div
          className={styles.leftTree}
          style={{ width: `${show ? 200 : 18}` }}
        >
          {show ? (
            <Tooltip title="收起">
              <div
                onClick={() => {
                  dispatch({ type: "flod", value: false });
                }}
              >
                <MenuFoldOutlined style={{ color: "#f50", fontSize: 18 }} />
              </div>
            </Tooltip>
          ) : (
            <Tooltip title="展开">
              <div
                onClick={() => {
                  dispatch({ type: "flod", value: true });
                }}
              >
                <MenuUnfoldOutlined style={{ color: "#f50", fontSize: 18 }} />
              </div>
            </Tooltip>
          )}
          {show ? (
            <>
              <Search
                style={{ marginBottom: 8 }}
                placeholder="请输入"
                onChange={searchTree}
              />
              <Tree
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                treeData={loop(treeData)}
                onSelect={selectTree}
              />
            </>
          ) : null}
        </div>
        <div className={`${styles.rightTable} specialpropertiesCard`}>
          <Schedule checkedNode={checkedNode} reloadTree={reload} />
        </div>
      </div>
    </div>
  );
};

export default Calendar;
