/* eslint-disable */
import React, { useCallback, useMemo, useRef, useState, useContext } from "react";
import { StarFilled } from "@ant-design/icons";
import * as commonServices from '@/services/services';
import { Modal, message } from 'antd-v4';
import { AutoComplete, Input } from "antd-v4";
import * as commonUtils from "@/utils/utils"; /* 通用方法 */
import config from '@/utils/config';
import * as commonFunc from "@/components/Common/commonFunc";
const MenuSearchPopovor = props => {

  const { menuPanel, onSetMenuSearchPopoverVisible, onAddPane, app, dispatch, updateMenuPanel } = useMemo(
    () => {
      return props;
    },
    []
  );

  const { modelCenter, kpiData } = app;

  const popovorRef = useRef(null);
  const handleTabClick = useCallback(option => {
    const { data, type } = option;
    if (type === 1) {
      const record = data;
      const newsId = record.sId;
      const newKey = new Date().getTime().toString();
      const route = record.sName;
      const title = record.sMenuName;
      const pane = {
        title, route, formId: newsId, key: newKey, sModelsType: record.sModelType, fromKey: "1", sSrcModelsId: '1',
        currentIndex: 0,
      };
      onAddPane(pane);
      return;
    } else if (type === 2) {
      const record = data;
      const newsId = record.sResultModelId;
      const newKey = new Date().getTime().toString();
      const route = record.sResultModelName;
      const title = record.sResultModelMenuName;
      const pane = {
        title, route, formId: newsId, key: newKey, sModelsType: record.sResultModelType, fromKey: "1",
        currentIndex: 0,
      };
      onAddPane(pane);
      return
    }

    const paneKey = new Date().getTime().toString();
    const formId = data.sId;
    const route = data.sName;
    const title = data.sMenuName;
    const sModelsType = data.sModelType;
    const { sProcName } = data;
    for (const each of app.panes) {
      /* 解决导航栏打开页签，Modal不消失问题 */
      each.notCurrentPane = true;
    }
    const pane = {
      title,
      route,
      formId,
      key: paneKey,
      sModelsType,
      sProcName,
      notCurrentPane: false
    };
    onAddPane(pane);
  });
  function getAddParameter(value, url) {
    /* 增加常用操作 */
    dispatch({ type: 'app/getAddParameter', payload: { value, url } });
  }
  function getDelParameter(value, url) {
    /* 删除常用操作 */
    dispatch({ type: 'app/getDelParameter', payload: { value, url } });
  }
  const handleStarClick = useCallback(async (e, data) => {
    e.stopPropagation();
    const { sId, sName, sMenuName, iCommonlyUsed } = data;
    const value = { sFormId: sId, sFormUrl: sName, sFormName: sMenuName };
    const { token } = props.app;
    if (iCommonlyUsed === '0') {
      const addUrl = `${config.server_host}parameter/addParameter?sModelsId=${sId}`;
      getAddParameter(value, addUrl)
    } else {
      const delUrl = `${config.server_host}parameter/deleteParameter?sModelsId=${sId}`;
      getDelParameter(value, delUrl)
    }
    onSetMenuSearchPopoverVisible(false)
    // todo更新数据，重新渲染
    setTimeout(() => {
      const url = `${config.server_host}business/getBuMenu?sModelsId=100`;
      dispatch({ type: 'menuPanel/getMenuPanel', payload: { url } });
    }, 300);
  });
  const handleGetSearchInputOption = useCallback(() => {
    const renderTitle = (title, title1) => (
      <span>
        {title1}
        <span
          style={{
            float: "right"
          }}
        >
          {title}
        </span>
      </span>
    );
    const renderItem = (title, data, bStar) => ({
      value: title,
      data: data,
      label: (
        <div
          style={
            {
              display: "flex",
              justifyContent: "space-between"
            }
          }
        >
          {title}
          {
            <span>
              <StarFilled
                style={{ color: bStar ? "#f6c136" : "#E6E6E6" }}
                onClick={(event) => handleStarClick(event, data)}
              />
            </span>
          }
        </div>
      )

    });
    const options = [];
    const commonlyUsedOption = [];

    if (menuPanel.panelMenus) {
      menuPanel.panelMenus.forEach(item => {
        if (commonUtils.isNotEmptyArr(item.children)) {
          item.children.forEach(item1 => {
            if (commonUtils.isNotEmptyArr(item1.children)) {
              const label = renderTitle(item.sMenuName, item1.sMenuName);
              const temp = { label, options: [] };
              const temp1 = { label, options: [] };
              item1.children.forEach(item2 => {
                const value = {
                  ...item2,
                  parentMenu: item1,
                  grandParentMenu: item
                };
                if (item2.iCommonlyUsed === "1") {
                  temp1.options.push(renderItem(item2.sMenuName, value, true));
                } else {
                  temp.options.push(renderItem(item2.sMenuName, value));
                }
              });
              if (commonUtils.isNotEmptyArr(temp.options)) {
                options.push(temp);
              }
              if (commonUtils.isNotEmptyArr(temp1.options)) {
                commonlyUsedOption.push(temp1);
              }
            }
          });
        }
      });
    }

    const columnWorkMatters = commonFunc.showMessage(app.commonConst, 'columnWorkMatters');
    const columnContent = commonFunc.showMessage(app.commonConst, 'columnContent');
    const { model = {} } = kpiData || modelCenter || {};
    const modelOptions = [{ label: renderTitle('', columnWorkMatters), options: [] }, { label: renderTitle('', columnContent), options: [] }];
    Object.keys(model).filter((_, index) => index === 0).forEach(key => {
      const value = model[key];
      value.forEach(item => {
        const { sId, sMenuUnMemo, sResultModelId, sMenuWorkFruit } = item;
        modelOptions[0].options.push({
          label: sMenuUnMemo,
          value: sId,
          data: item,
          type: 1
        });
        modelOptions[1].options.push({
          label: sMenuWorkFruit,
          value: `${sId},${sResultModelId}`,
          data: item,
          type: 2
        });
      });
    });

    return [...commonlyUsedOption, ...options, ...modelOptions];
  }, [menuPanel.panelMenus]);

  const searchTitle = commonFunc.showMessage(app.commonConst, 'btnSearch') || '搜索';

  return (
    <div ref={popovorRef}>
      <AutoComplete
        style={{ width: 250 }}
        popupClassName="certain-category-search-dropdown"
        options={handleGetSearchInputOption()}
        autoFocus
        defaultOpen
        onBlur={() => {
          onSetMenuSearchPopoverVisible(false);
        }}
        filterOption={(inputValue, option) => {
          let result = false;
          const { data, value } = option;
          if (commonUtils.isNotEmptyObject(data)) {
            const { sMenuName, parentMenu = {}, grandParentMenu = {}, sMenuUnMemo, sMenuWorkFruit } = data;
            const { sMenuName: sMenuName1 } = parentMenu;
            const { sMenuName: sMenuName2 } = grandParentMenu;
            const bMenuWorkFruit = value.includes(',');
            const result0 =
              sMenuName && sMenuName.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
            const result1 =
              sMenuName1 && sMenuName1.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
            const result2 =
              sMenuName2 && sMenuName2.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
            const result3 =
              !bMenuWorkFruit && sMenuUnMemo && sMenuUnMemo.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
            const result4 =
              bMenuWorkFruit && sMenuWorkFruit && sMenuWorkFruit.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1;
            result = result0 || result1 || result2 || result3 || result4;
          }
          return result;
        }}
        onSelect={(_, option) => {
          // popovorRef.current.animate([{ width: '250px' }, { width: 0 }], {
          //   duration: 2000, iterations: 1
          // });
          handleTabClick(option);
          onSetMenuSearchPopoverVisible(false);
        }}
      >
        <Input.Search size="large" placeholder={searchTitle} />
      </AutoComplete>
    </div>
  );
};

export default MenuSearchPopovor;
