import React, { useState } from 'react';

import { message } from 'antd';
import _ from 'lodash';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

import { useIntl } from '@/locales/localeExports';
import Icon from '@ant-design/icons';

import { actionCreators } from '../../containers/App/store';
import HeaderSearch from '../HeaderSearch';
import Avatar from './AvatarDropdown';
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="#5F718C"
      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="#5F718C"
      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 OrderIcon = props => <Icon component={orderSvg} {...props} />;
const HomeIcon = props => <Icon component={homeSvg} {...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 { theme, layout } = props;
  const [options, setOptions] = useState([]);
  let className = styles.right;

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

  const intl = useIntl();

  /* eslint-disable */
  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([]);
  };

  const goHome = event => {
    event.stopPropagation();
    const url = _.isString(props.global.get('homepage'))
      ? props.global.get('homepage')
      : props.global.get('homepage.url');
    //      // props.history.replace(`/civweb4/${url}`)
    url ? (
      window.share.event.emit('listenerMointer', {
        label: '首页',
        url: url,
      })
    ) : 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}`);
    } else {
      message.warning('对不起，您没有菜单权限！');
    }
  };

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

  return (
    <div className={className}>
      <HeaderSearch
        className={`${styles.action} ${styles.search}`}
        placeholder={intl.formatMessage({id:'component.search.menu.placeholder'})}
        defaultValue=""
        options={options}
        {...props}
        onSelect={handleSelect}
        onChange={handleSearch}
        onSearch={handleSearch}
      />
      <div className={styles.nav}>
        <HomeIcon onClick={goHome} title={intl.formatMessage({id: 'component.header.icon.home'})} />
        <OrderIcon onClick={handleOrder} title={intl.formatMessage({id: 'component.header.icon.order'})} />
      </div>
      <NoticeIconView title={intl.formatMessage({id: 'component.header.icon.alarm'})} />
      <Avatar menu global={props.global} updateCurrentIndex={props.updateCurrentIndex} updateConfig={props.updateConfig} logout={props.logout}/>
      {/* <SelectLang className={styles.action} /> */}
    </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,
)(withRouter(GlobalHeaderRight));
