import React, { useContext, useEffect, useMemo, useState } from "react";
import { deepFindOne, findExpandedKeys, getComponentOptions, searchExpandedKeys } from "_util";
import { ScreenContext } from "config-provider";
import { EasyRadio, EasyTreeSelect } from "config-types";
import styles from "./index.less";
import { getCalcNewValue, tranValueBySetChildGroup } from "./utils";

const DEFAULT_SCOPE_OPTIONS = [
  { name: "当前", value: "current" },
  { name: "全局", value: "global" },
];

export default function EasyComponents(props) {
  const {
    value,
    scope = "current",
    scopeOptions = DEFAULT_SCOPE_OPTIONS,
    multiple = true,
    onChange,
    onScopeChange,
  } = props;
  let {
    componentsById = {},
    panelsById = {},
    screensById = {},
    comContainersById = {},
    screenId,
    stateId,
  } = useContext(ScreenContext);
  const [expandedKeys, setExpandedKeys] = useState([]);

  let componentOptions = getComponentOptions({
    componentsById,
    panelsById,
    screensById,
    comContainersById,
    screenId,
    stateId,
    mode: scope,
  });

  const handleTreeExpand = (keys) => {
    setExpandedKeys(keys);
  };

  const handleSearch = (v) => {
    if (v) {
      // 搜索时展开搜索结果的tree节点
      const keyArr = [...searchExpandedKeys(componentOptions, v).tempExpanedKeys];
      setExpandedKeys(keyArr);
    } else {
      // 搜索框清空后再按选中项展开tree节点
      const keyArr = [...findExpandedKeys(componentOptions, value).tempExpanedKeys];
      setExpandedKeys(keyArr);
    }
  };

  // select下拉时，展开选中的tree节点
  const handleSelectDropdown = (open) => {
    if (open) {
      const keyArr = [...findExpandedKeys(componentOptions, value).tempExpanedKeys];
      setExpandedKeys(keyArr);
    }
  };

  // 修复current模式组件未找到，切换至global模式
  // useEffect(() => {
  //   let res;
  //   if (Array.isArray(value)) {
  //     res =
  //       value.length > 0 &&
  //       value.some((d) => !deepFindOne(componentOptions, (item) => item.value === d, "children"));
  //   } else {
  //     res = value && !deepFindOne(componentOptions, (item) => item.value === value, "children");
  //   }

  //   if (res && scope === "current") {
  //     onScopeChange("global");
  //   }
  // }, []);

  const treeSelectValue = useMemo(() => {
    if (!multiple) {
      return value;
    }
    return tranValueBySetChildGroup({ value, componentOptions });
  }, [value, multiple, componentOptions]);

  return (
    <div className={scope !== "agentScreen" ? styles.line : ""}>
      <EasyRadio value={scope} options={scopeOptions} onChange={onScopeChange} />
      {scope !== "agentScreen" && (
        <EasyTreeSelect
          value={treeSelectValue}
          multiple={multiple}
          options={componentOptions}
          treeExpandedKeys={expandedKeys}
          onChange={(v) => {
            if (multiple && Array.isArray(v)) {
              onChange?.(
                getCalcNewValue({ oldValue: treeSelectValue, newValue: v, componentOptions }),
              );
            } else {
              onChange?.(v);
            }
          }}
          onTreeExpand={handleTreeExpand}
          onDropdownVisibleChange={handleSelectDropdown}
          onSearch={handleSearch}
          showCheckedStrategy={EasyTreeSelect.SHOW_CHILD}
        />
      )}
    </div>
  );
}
