import React, { useState, useRef } from 'react';
import { message } from 'antd';
import _ from 'lodash';
import { connect } from 'react-redux';
import Icon from '@ant-design/icons';
import classNames from 'classnames';
import { useHistory } from '@wisdom-utils/runtime';
import { HeaderSearch, useIntl} from '@wisdom-utils/components';
import { AvatarDropdown as Avatar } from '../../layouts/AppLayout/components/GlobalHeader';
import { actionCreators } from '../../containers/App/store';
import styles from './index.less';
import NoticeIconView from './NoticeIconView';
/* eslint-disable */
const orderSvg = () => (
  <svg
    version="1.1"
    x="0px"
    y="0px"
    width="24px"
    height="24px"
    viewBox="0 0 24 24"
    enableBackground="new 0 0 24 24"
    space="preserve"
  >
    <path
      fill="hsla(221, 100%, 95%, 0.7)"
      d="M7.223,13.131c-0.445,0-0.815,0.364-0.815,0.816c0,0.446,0.37,0.816,0.815,0.816
      c0.446,0,0.816-0.37,0.816-0.816C8.039,13.495,7.669,13.131,7.223,13.131L7.223,13.131z M7.223,16.574L7.223,16.574
      c-0.445,0-0.815,0.371-0.815,0.817c0,0.45,0.37,0.814,0.815,0.814c0.446,0,0.816-0.364,0.816-0.814
      C8.039,16.945,7.669,16.574,7.223,16.574L7.223,16.574z M7.223,9.688L7.223,9.688c-0.445,0-0.815,0.366-0.815,0.817
      c0,0.445,0.37,0.815,0.815,0.815c0.446,0,0.816-0.37,0.816-0.815C8.039,10.054,7.669,9.688,7.223,9.688L7.223,9.688z M20.469,4.533
      L20.469,4.533h-2.246V4.082c0-0.268-0.22-0.48-0.485-0.48h-2.622c-0.138-0.59-0.434-1.1-0.839-1.505
      c-0.59-0.591-1.388-0.95-2.28-0.95c-0.884,0-1.677,0.359-2.262,0.95C9.323,2.502,9.022,3.012,8.879,3.602H6.263
      c-0.267,0-0.492,0.213-0.492,0.48v0.451H3.548c-0.451,0-0.821,0.363-0.821,0.814v16.688c0,0.452,0.37,0.817,0.821,0.817h16.921
      c0.438,0,0.805-0.365,0.805-0.817V5.348C21.273,4.896,20.907,4.533,20.469,4.533L20.469,4.533z M10.671,3.027
      c0.405-0.404,0.718-0.653,1.325-0.653c0.614,0,0.933,0.249,1.337,0.653c0.221,0.227,0.158,0.256,0.273,0.574h-3.208
      C10.516,3.283,10.44,3.254,10.671,3.027 M7.015,4.822L7.015,4.822h9.982v1.054H7.015 M19.647,21.215L19.647,21.215H4.359V6.158
      h1.411v0.451c0,0.267,0.226,0.486,0.492,0.486h11.475c0.266,0,0.485-0.22,0.485-0.486V6.158h1.425V21.215L19.647,21.215z
      M16.742,9.765L16.742,9.765H9.659c-0.267,0-0.485,0.468-0.485,0.74c0,0.267,0.219,0.739,0.485,0.739h7.083
      c0.277,0,0.491-0.473,0.491-0.739C17.233,10.232,17.02,9.765,16.742,9.765L16.742,9.765z M16.742,16.65L16.742,16.65H9.659
      c-0.267,0-0.485,0.468-0.485,0.741c0,0.271,0.219,0.728,0.485,0.728h7.083c0.277,0,0.491-0.457,0.491-0.728
      C17.233,17.118,17.02,16.65,16.742,16.65L16.742,16.65z M16.742,13.213L16.742,13.213H9.659c-0.267,0-0.485,0.462-0.485,0.735
      c0,0.271,0.219,0.734,0.485,0.734h7.083c0.277,0,0.491-0.464,0.491-0.734C17.233,13.675,17.02,13.213,16.742,13.213L16.742,13.213z"
    />
  </svg>
);
const homeSvg = () => (
  <svg
    version="1.1"
    x="0px"
    y="0px"
    width="24px"
    height="24px"
    viewBox="0 0 24 24"
    enableBackground="new 0 0 24 24"
    space="preserve"
  >
    <path
      fill="hsla(221, 100%, 95%, 0.7)"
      d="M23.359,13.561v-1.313L12.057,1.064L0.642,12.247v1.37h2.84v9.318h7.381v-4.935h2.271v4.935h7.385v-9.318
	    L23.359,13.561z M18.815,11.917v9.319H14.84v-4.935H9.161v4.935H5.185v-9.319H3.311l8.746-8.551l8.577,8.551H18.815z"
    />
  </svg>
);

const favitorSvg = () => (<svg t="1631171489722" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="16457" width="24" height="24"><path d="M512 87.806c-234.721 0-424.194 189.474-424.194 424.194s189.474 424.194 424.194 424.194 424.194-189.474 424.194-424.194-189.474-424.194-424.194-424.194zM783.484 442.715l-137.155 100.393c-7.069 5.655-9.899 14.141-7.069 22.624l52.317 161.194c5.655 18.382-15.553 33.935-31.108 22.624l-137.155-100.393c-7.069-5.655-16.967-5.655-24.037 0l-137.155 100.393c-15.553 11.312-36.763-4.242-31.108-22.624l53.731-162.608c2.829-8.484 0-16.967-7.069-22.624l-137.155-100.393c-15.553-11.312-7.069-35.349 11.312-35.349h169.678c8.484 0 16.967-5.655 18.382-14.141l52.317-161.194c5.655-18.382 32.522-18.382 38.177 0l52.317 161.194c2.829 8.484 9.899 14.141 18.382 14.141h169.678c21.21 0 28.278 25.452 12.725 36.763z" p-id="16458" fill="hsla(221, 100%, 95%, 0.7)"></path></svg>);
const themeSvg = () => (<svg t="1631362986014" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
  <path d="M552.75 563.239c44.4 26.348 99.1 26.348 143.5 0C740.65 536.89 768 488.197 768 435.5c0-81.462-64.247-147.5-143.5-147.5S481 354.038 481 435.5c0 52.697 27.35 101.39 71.75 127.739z" fill="hsla(221, 100%, 95%, 0.7)" p-id="2351"></path>
  <path d="M471.264 952c-18.842 0-38.581-1.796-60.115-4.49l-5.384-0.899c-152.533-23.352-256.614-171.55-261.1-177.837-147.149-224.541-73.574-451.777 65.5-577.52C348.34 65.511 578.934 11.621 780.814 174.19c130.102 105.085 169.58 250.588 171.375 256.875v1.797c18.843 102.39 3.59 177.836-45.76 226.337-75.368 72.752-200.086 49.4-217.134 45.807-23.328-2.695-40.376 4.49-52.938 19.76-13.458 17.064-16.15 39.518-11.664 52.991 12.562 37.723 14.356 66.464 5.384 88.02C604.058 922.361 551.12 952 471.264 952z m-51.973-80.488l5.083 0.849c82.179 12.72 132.164-3.393 152.497-49.188 0-0.849 4.236-11.873-6.778-45.796-11.013-30.53-2.541-70.39 19.486-97.528 22.875-28.834 56.763-41.556 96.581-37.315l2.542 0.848c0.847 0 105.9 22.898 160.122-29.683 33.04-32.226 43.207-88.199 28.805-166.221-3.39-11.025-39.819-130.603-144.872-214.562-166.053-135.69-356.674-90.743-471.894 13.57-105.9 96.68-183.843 280.71-53.374 480.007 0.848 0 89.804 127.21 211.802 145.02z" fill="hsla(221, 100%, 95%, 0.7)" p-id="2352"></path>
  <path d="M203 529c0-29.823 24.177-54 54-54s54 24.177 54 54-24.177 54-54 54-54-24.177-54-54z m90-115.235A54 54 0 0 1 266 367c0-29.823 24.177-54 54-54s54 24.177 54 54a54 54 0 0 1-81 46.765zM427 278c0-29.823 24.177-54 54-54s54 24.177 54 54-24.177 54-54 54-54-24.177-54-54z m180 44c0-29.823 24.177-54 54-54s54 24.177 54 54-24.177 54-54 54-54-24.177-54-54z m90 144c0-29.823 24.177-54 54-54s54 24.177 54 54-24.177 54-54 54-54-24.177-54-54z" fill="hsla(221, 100%, 95%, 0.7)"></path></svg>)
const OrderIcon = props => <Icon component={orderSvg} {...props} />;
const HomeIcon = props => <Icon component={homeSvg} {...props} />;
const FavitorIcon = props => <Icon component={favitorSvg} {...props}/>
const ThemeIcon = props => <Icon component={themeSvg} {...props}/>
const MESSAGE_BOX_URL =
  'product/maintenance/CaseManage/CaseDoingBox/StardCaseDoingBoxView|isDelay=1';

export const getConfig = (widgets, url, key) => {
  let widgetconfig = {};
  if (widgets) {
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < widgets.length; i++) {
      const widget = widgets[i];

      if (widget && widget[key])
        widget[key] = widget[key].replace(/\\/g, '/').trim();
      // eslint-disable-next-line eqeqeq
      if (widget[key] && url.toLowerCase() === widget[key].toLowerCase()) {
        widgetconfig = widget;
        break;
      } else {
        const children = widget.widgets ? widget.widgets : widget.routes;
        if (children) {
          widgetconfig = getConfig(children, url, key);
          if (widgetconfig) {
            break;
          }
        }
      }
    }
  }
  return widgetconfig;
};
const GlobalHeaderRight = props => {
  const [options, setOptions] = useState([]);
  const homeRef = useRef(null);
  const favitorRef = useRef(null);
  const history = useHistory();
  const { theme, layout } = props;
  let className = styles.right;

  if (theme === 'dark' && layout === 'top') {
    className = `${styles.right}  ${styles.dark}`;
  }
  const intl = useIntl();


  const goHome = event => {
    event.stopPropagation();
    let url = _.isString(props.global.get('homepage'))
      ? props.global.get('homepage')
      : props.global.get('homepage.url');
    if(!props.global.get('home')) {
      url = `civweb4/${url.replace(/^\//, '').replace(/^civweb4\//, '')}`
    }
    window.share.event.emit('goHome', `/${url}`);
    // url ? (
    //   window.share.event.emit('listenerMointer', {
    //     label: '首页',
    //     url: url.replace(/^civweb4\//, ''),
    //   })
    // ) : null;
  };


  const handleOrder = event => {
    event.stopPropagation();
    const widgetConfig = getConfig(
      props.global.get('widgets').concat(props.global.get('uiwidgets')),
      MESSAGE_BOX_URL,
      'url',
    );

    if (Object.keys(widgetConfig).length > 0) {
      props.history.push(`/civweb4/${MESSAGE_BOX_URL}`);
      setCurrentIndex(2);
    } else {
      message.warning('对不起,您没有菜单权限!');
    }
  };

  const handlerFavitor = event => {
    // setCurrentIndex(1);
    history.push('/commonmenu');
    window.share && window.share.event && window.share.event.emit('event:favitor', {
      name: "常用",
      path: '/commonmenu',
      icon: <FavitorIcon/>
    });
  }

  const handlerTheme = () => {
    window.share.event.emit('event:theme');
  }

  const handleSelect = (value, data) => {
    window.share.event.emit('addTips', options, data);
  };

  const handleSearch = value => {
    // eslint-disable-next-line no-undef
    const search = new AMap.Autocomplete();
    const areaName =
      // eslint-disable-next-line no-undef
      createStoreage.get('globalConfig').mapsettings.areasettings &&
      // eslint-disable-next-line no-undef
      createStoreage.get('globalConfig').mapsettings.areasettings.areaName;
    const area = (areaName || '') + value;
    setOptions([]);
    // eslint-disable-next-line no-unused-expressions
    value
      ? search.search(area, (status, res) => {
        if (res && res.tips) {
            const result = res.tips.map(item => {
              item.value = item.name;
              item.label = (
                <>
                  <span>{item.name}</span>
                  <span style={{ color: '#c1c1c1' }}>
                    {item.district + item.address}
                  </span>
                </>
              );
              return item;
            });

            setOptions(result);
          }
        })
      : setOptions([]);
  };
  return (
    <div className={className}>
       <HeaderSearch
          className={`${styles.action} ${styles.search} ${styles.extendsearch}`}
          placeholder={intl.formatMessage({id:'component.search.menu.placeholder'})}
          offset="46px"
          defaultValue=""
          mode="tiled"
          options={options}
          {...props}
          onSelect={handleSelect}
          onChange={handleSearch}
          onSearch={handleSearch}
      />
      <div className={styles.nav}>
        <div className={classNames(styles.item)} onClick={goHome} ref={homeRef}>
            <HomeIcon  title={intl.formatMessage({id: 'component.header.icon.home'})} />
            <span>首页</span>
        </div>
        {
          // 云平台去掉常用菜单
          props.global && props.global.userInfo && props.global.userInfo.Groups && props.global.userInfo.Groups.length
          ? null
          : (
            <div className={classNames(styles.item)} onClick={handlerFavitor} ref={favitorRef}>
                <FavitorIcon></FavitorIcon>
                <span>常用</span>
            </div>
          )
        }
        {/*<div className={classNames(styles.item)} onClick={handlerTheme}>*/}
        {/*  <ThemeIcon/>*/}
        {/*  <span>主题</span>*/}
        {/*</div>*/}
        <div className={classNames(styles.item)}>
            <OrderIcon onClick={handleOrder} title={intl.formatMessage({id: 'component.header.icon.order'})} />
            <span>工单</span>
        </div>
      </div>
      <NoticeIconView title={intl.formatMessage({id: 'component.header.icon.alarm'})} />
      <Avatar  menu config={props.global} updateCurrentIndex={props.updateCurrentIndex} updateConfig={props.updateConfig} logout={props.logout}/>
    </div>
  );
};

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  flatMenu: state.getIn(['global', 'flatMenu']),
  menu: state.getIn(['global', 'menu']),
  recentKeywords: state.getIn(['global', 'recentKeywords']),
  recentVisited: state.getIn(['global', 'recentVisited']),
  recentProducts: state.getIn(['global', 'recentProducts']),
});
const mapDispatchToProps = dispatch => ({
  updateRecentKeywords(keyword) {
    dispatch(actionCreators.updateRecentKeywords(keyword));
  },
  updateRecentVisited(history) {
    dispatch(actionCreators.updateRecentVisited(history));
  },
  updateRecentProduct(history) {
    dispatch(actionCreators.updateRecentProduct(history));
  },
  clearRecentProduct() {
    dispatch(actionCreators.clearRecentProduct());
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index))
  },
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config))
  },
  updateComplexConfig(config) {
    dispatch(actionCreators.updateComplexConfig(config))
  },
  logout() {
    dispatch(actionCreators.logout())
  }
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(GlobalHeaderRight);