import React, { useState, useMemo } from "react";
import { connect } from "dva";
import { withRouter } from "dva/router";
import { Dropdown, Icon, Menu, message, Button, Modal, Input } from "antd";
import { HeaderSearch as OPTSearch, PictureThumb } from "@woowalker/feui";
import ModifyPassword from "../components/MainPage/ModifyPassword";
import FoUserInfoShow from "../components/MainPage/FoUserInfoShow";
import FeedbackQuestion from "../components/MainPage/FeedbackQuestion";
import GuideCanvas from "../components/MainPage/GuideCanvas";
import IconFont from "../utils/iconFont";
import { initFilter } from "../utils/common";
import config from "../config";
import "./header.less";
import Option from "./Option";

// 投屏
const DataV = (props) => {
  const navTo = () => {
    const { OrgId, Tenant, baseConfig } = props.login;
    const preUrl = baseConfig.SCREEN_URL || config.dataVUrl;
    const queryStr = `OrgId=${OrgId}&Tenant=${Tenant}`;
    const url = `${
      preUrl.indexOf("?") !== -1 ? preUrl : preUrl + "?"
    }${queryStr}`;
    window.open(url, "_blank");
  };
  return (
    <span title="投屏" onClick={navTo} className="header__right-datav">
      {/* <EnergyIcon type='icon-touping' className='header__right-icon' /> */}
    </span>
  );
};
const HeaderDataV = connect(({ login }) => ({ login }))(DataV);

// 搜索
const SearchBox = (props) => {
  const [autoCompleteData, setAutoCompleteData] = useState([]);
  const [inputVal, setInputVal] = useState("");

  const leafMenus = useMemo(() => {
    const menuForms = [];
    const menuDatas = [];
    function traverseChild(item) {
      if (!item.Menu.Nav_MenuForm || item.ChildMenus?.length) {
        item.ChildMenus.forEach((x) => {
          traverseChild(x);
        });
      } else if (item.Menu.Nav_MenuForm) {
        menuForms.push({
          MenuName: item.Menu.NAME,
          ...item.Menu.Nav_MenuForm,
        });
        menuDatas.push(item);
      }
    }

    const menus = props.login.loginInfo.Menus || [];
    menus.forEach((item) => {
      traverseChild(item);
    });

    return { menuForms, menuDatas };
  }, [props.login.loginInfo?.Menus]);

  /**
   * 搜索菜单
   * @param {*} e
   */
  const handleSearchMenu = (e) => {
    setInputVal(e.target.value);
    if (!e.target.value || e.target.value === "") {
      setAutoCompleteData([]);
      return;
    }
    const validResult = [];
    leafMenus.menuForms.forEach((item) => {
      if (
        item.CODE.toLowerCase().indexOf(e.target.value.toLowerCase()) >= 0 ||
        item.NAME.toLowerCase().indexOf(e.target.value.toLowerCase()) >= 0 ||
        item.MenuName.toLowerCase().indexOf(e.target.value.toLowerCase()) >= 0
      ) {
        validResult.push(item);
      }
    });
    setAutoCompleteData(validResult);
  };

  /**
   * 选中菜单
   * @param {*} e
   */

  const overMenu = () => {
    if (autoCompleteData.length == 0) {
      return (
        <Menu>
          <Menu.Item key="0">暂无匹配项</Menu.Item>
        </Menu>
      );
    } else {
      return (
        <Menu
          // onClick={handleMenuClick}
          style={{ height: "200px", overflow: "auto" }}
        >
          {autoCompleteData.map((item, index) => {
            return (
              <Menu.Item
                key={index}
                onClick={() => {
                  handleSelectMenu(item.ID);
                }}
              >
                {item.NAME}({item.CODE})
              </Menu.Item>
            );
          })}
        </Menu>
      );
    }
  };
  const handleSelectMenu = (e) => {
    const menu = leafMenus.menuDatas.find(
      (item) => item.Menu.Nav_MenuForm.ID === e
    );
    props.dispatch({
      type: "app/updateActivatedMenu",
      payload: {
        currActivatedTab: menu.Node.ID,
        currActivatedMenu: menu.Node,
      },
    });
    props.history.push({ pathname: `/main/${menu.Node.ID}` });
    setInputVal("");
    setAutoCompleteData([])
  };
  if (window.navigator.userAgent.indexOf("Windows") < 1) {
    return <span></span>;
  } else {
    return (
      // <OPTSearch
      //   dataSource={autoCompleteData}
      //   onChange={handleSearchMenu}
      //   onSelect={handleSelectMenu}
      // />
      // <SearchBox
      //   backgroundColor="#F7F7F7" // 自定义背景色
      //   placeholder="请输入关键词" // 输入框提示
      //   hasDropdown={true} // 是否显示下拉搜索类型
      //   onClick={handleSelectMenu} // 点击菜单执行方法
      //   onClickSearch={handleSearchMenu} // 点击搜索按钮执行
      //   size="sm" // 大小 lg or sm
      //   hasBorder={false}
      //   lists={autoCompleteData}
      // />
      <Dropdown overlay={overMenu} placement="topLeft" trigger={['click']}>
        <div className="headerInput">
          {/* <Search
            placeholder={"请输入搜索内容"}
            onSearch={handleSearchMenu}
            style={{ width: 200 }}
          /> */}
          <Input
            placeholder="搜索菜单"
            prefix={<Icon type="search" style={{ color: "#909399" ,fontSize:'18px'}} />}
            onChange={(e) => {
              handleSearchMenu(e);
            }}
            onPressEnter={(e) => {
              handleSearchMenu(e);
            }}
            value={inputVal}
          />
        </div>
      </Dropdown>
    );
  }
  //return (
  //
  // <OPTSearch
  //   dataSource={autoCompleteData}
  //   onChange={handleSearchMenu}
  //   onSelect={handleSelectMenu}
  // />
  //)
};
const HeaderSearch = withRouter(connect(({ login }) => ({ login }))(SearchBox));

// 个人中心
const User = (props) => {
  const [visible, setVisible] = useState(false);

  /**
   * 注销登录
   */
  const handleLogout = () => {
    const { OrgId, userId } = props.login;
    const logJson = initFilter(OrgId, userId, "", 0, 1, 0);
    props.dispatch({
      type: "app/addLoginOut",
      payload: logJson,
    });
    localStorage.removeItem("accessToken");
    props.history.push({ pathname: "/login" });
  };

  /**
   * 锁屏
   */
  const handleLockScreen = () => {
    localStorage.removeItem("accessToken");
    props.dispatch({
      type: "login/save",
      payload: {
        screenLocked: true,
      },
    });
  };

  /**
   * 菜单选中
   * @param {*} evt
   */
  const handleUserMenuClick = (evt) => {
    switch (evt.key) {
      case "user-menu-logout":
        handleLogout();
        break;
      case "user-menu-lockscreen":
        handleLockScreen();
        break;
      case "user-menu-cacheclean":
        window.localStorage.clear();
        message.success("清除成功，即将重新加载页面", 2, () => {
          setTimeout(() => window.location.reload(true), 500);
        });
        break;
      default:
        break;
    }
    setVisible(false);
  };

  const { loginInfo = {} } = props.login;
  return (
    <Dropdown
      visible={visible}
      onVisibleChange={setVisible}
      overlay={
        <Menu onClick={handleUserMenuClick}>
          <Menu.Item key="user-menu-userinfo">
            当前登录：{loginInfo.User?.NAME}
          </Menu.Item>
          <Menu.Item key="user-menu-UserInfoShow">
            <FoUserInfoShow>我的资料</FoUserInfoShow>
          </Menu.Item>
          <Menu.Item key="user-menu-updatepwd">
            <ModifyPassword>修改密码</ModifyPassword>
          </Menu.Item>
          {/* <Menu.Item key='user-menu-feedbackqtn'><FeedbackQuestion>问题反馈</FeedbackQuestion></Menu.Item> */}
          {/* <Menu.Item key='user-menu-lockscreen'>屏幕锁定</Menu.Item> */}
          <Menu.Item key="user-menu-cacheclean">清除缓存</Menu.Item>
          <Menu.Item>版本号:{config.version}</Menu.Item>
          <Menu.Item key="user-menu-logout">退出登录</Menu.Item>
        </Menu>
      }
    >
      <span className="header__right-user">
        <Icon type="user" className="header__right-icon" />
      </span>
    </Dropdown>
  );
};
const HeaderUser = withRouter(connect(({ login }) => ({ login }))(User));
const GuideCodePage = (props) => {
  const [showCanvas, setshowCanvas] = useState(false);
  const currVans = (val) => {
    setshowCanvas(true);
  };
  /**
   * 生产单元切换
   * @param {*} evt
   */

  if (window.navigator.userAgent.indexOf("Windows") < 1) {
    return <div></div>;
  } else {
    return (
      <div>
        <div
          onClick={() => {
            currVans();
          }}
          style={{ margin: "0px 36px", display: "flex", alignItems: "center" }}
        >
          <Icon type="qrcode" className="header__right-icon" />
        </div>
        <Modal
          title=""
          visible={showCanvas}
          width="400px"
          centered={true}
          onOk={() => {
            setshowCanvas(false);
          }}
          onCancel={() => {
            setshowCanvas(false);
          }}
          footer={null}
        >
          <GuideCanvas />
        </Modal>
      </div>
    );
  }
};
const GuideCode = withRouter(
  connect(({ login }) => ({ login }))(GuideCodePage)
);
const NavOpton = (props) => {
  const [showModal, setshowModal] = useState(false);
  const getChildCount = (val) => {
    setshowModal(val);
  };
  if (window.navigator.userAgent.indexOf("Windows") < 1) {
    return <div></div>;
  } else {
    return (
      <div>
        <div
          type="primary"
          onClick={() => {
            setshowModal(true);
          }}
        >
          {/* <Icon type='bars' className='header__right-icon'></Icon> */}
          <IconFont
            type="icon-line-108"
            style={{ fontSize: "22px", color: "#909399", cursor: "pointer" }}
          ></IconFont>
        </div>
        <Modal
          title="功能导航"
          visible={showModal}
          width="96%"
          centered={true}
          onOk={() => {
            setshowModal(false);
          }}
          onCancel={() => {
            setshowModal(false);
          }}
          className="headerModal"
        >
          <Option getCount={getChildCount}></Option>
        </Modal>
      </div>
    );
  }
};
const HeaderNav = withRouter(connect(({ login }) => ({ login }))(NavOpton));

function Header(props) {
  const { baseConfig = {} } = props.login;
  const thumbCode = baseConfig.Nav_PictureLogo
    ? baseConfig.Nav_PictureLogo.CODE
    : "";
  let isMobile = false;

  if (window.navigator.userAgent.indexOf("Windows") < 1) {
    isMobile = true;
  }

  return (
    <div className={`header ${props.matchLogin ? "login" : "nologin"}`}>
      <div className="header__left">
        <PictureThumb
          thumbCodes={thumbCode ? [thumbCode] : []}
          thumbConfigs={[{ target: thumbCode }]}
          defaultThumb={require("../assets/layout/header-logo.png")}
          className="header__left-logo"
        />
        {isMobile ? (
          <span className="header__left-slogan-mobile"> </span>
        ) : (
          <span
            className={`${
              props.matchLogin
                ? "header__left-sloganLogin"
                : "header__left-slogan"
            }`}
          >
            双重预防机制管控系统
            {/* 安全管理系统
            <span style={{ color: "#c99d03" }}>（SMS）</span> */}
            {baseConfig.SYS_NAME}{" "}
          </span>
        )}
      </div>
      {!props.matchLogin ? (
        <div className="header__right">
         
          <HeaderDataV />
          <HeaderSearch />
          <GuideCode />
          <HeaderNav />
          {/* style={{"color":"#f3eded"}} */}
          <HeaderUser />
          <b>
            {props.login.user.NAME}({props.login.user.CODE})
          </b>
        </div>
      ) : null}
    </div>
  );
}

export default connect(({ login }) => ({ login }))(Header);
