import React, { useRef, useState, useEffect } from 'react';

import { message, Popover, Select } from 'antd';
import _ from 'lodash';
import { connect } from 'react-redux';
import { store } from '@wisdom-utils/utils';
import Icon from '@ant-design/icons';
import { AvatarDropdown as Avatar, useIntl } from '@wisdom-utils/components';
import HeaderSearch from '@wisdom-utils/components/lib/layout/components/HeaderSearch';
import { useHistory, useAliveController } from '@wisdom-utils/runtime';
import order from '../../assets/basic/message.png';
import notice from '../../assets/basic/notice.png';
import search from '../../assets/basic/search.png';
import SvgComponent from './stationsvg';
import { actionCreators } from '../../containers/App/store';
import styles from './index.less';
import NoticeIconView from './NoticeIconView';

/* eslint-disable */

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 FavitorIcon = props => <Icon component={favitorSvg} {...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([]);
  let [showStationList,setStationList]=useState([])
  const homeRef = useRef(null);
  const favitorRef = useRef(null);
  const history = useHistory();
  const { theme, layout, global } = props;
  const [stationvalue, setStationValue] = useState('');
  const roleStationArr = useRef([]);
  let stationOpen=useRef(false)
  let slectDom=useRef(null)
  let [update,setUpdate]=useState(false)
  let className = styles.right;
  const { clear } = useAliveController();
  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 handleFeedback = event => {
    event.stopPropagation();
    window.open(`https://work.panda-water.cn/feedback/?site_code=${props.global.get('userInfo.site')}`);
  }

  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([]);
  };

  const renderHeaderSearch = () => {
    return (
        <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}
      />
    )
  }

  const logout = () => {
    clear();
    props.logout();
  }

  const renderTopMenu = () => {
    if(!props.global || !props.global.topMenu) return null;
    const topMenus = props.global.topMenu.split(',') || [];
    return topMenus.map(name => {
      switch (name) {
        // 搜索,首页,常用,反馈,消息
        case '搜索':
          return (
            <div className={styles.opteration}>
              <Popover
                placement="bottomRight"
                content={renderHeaderSearch()}
                trigger="click"
                overlayClassName={styles.searchPopupWrapper}
              >
                <Icon component={() => <img src={search} alt="icon" className={styles.active} />} />
              </Popover>
            </div>
          );
        case '反馈':
          return (
            <div className={styles.opteration}>
              <Icon component={() => <img src={order} alt="icon" />} onClick={handleFeedback} />
            </div>
          );
        case '消息':
          return <NoticeIconView bell={<Icon component={() => <img src={notice} alt="icon" />} />} />;
        default:
          return null;
      }
    })
  }
  let resetMenu=()=>{
    if(window.qiankunIsCache){
      store&&store.set('event:refreshCurrentMenu', {
        dropCache: true
      });
    }
  }
  let stationSerach=(value)=>{
    let showstation = roleStationArr.current.filter((item)=>{
      if(item.description){
        return item.description.includes(value)
      }else{
        return item.name.includes(value)
      }
    })
    setStationList(showstation)
  }
  let closePan=(name,stationname)=>{
    stationOpen.current=false
    setUpdate(stationOpen.current)
    currentStationChange(name,stationname)
  }
  const currentStationChange = (value,stationname) => {
    setStationValue(value);
    const arr = roleStationArr.current.filter(item => item.name == stationname);
    window._menuStation = arr.length ? arr[0] : {};
    localStorage.setItem('globMenuStation', arr.length ? JSON.stringify(arr[0]) : '{}')
    if(window.share && window.share.event && window.share.event.emit) {  //更改获取站点信息
      window.share.event.emit("changeGlobMenuStation", window._menuStation)
    }
    setTimeout(()=>{
      slectDom.current.blur()
    },200)
    resetMenu()
  };
  useEffect(() => {
    if (global.userInfo) {
      if(window._changeStation){
        roleStationArr.current = global.userInfo.roles.filter(item => item.name.includes('站点_'));
        if (roleStationArr.current.length) {
          let stationname=roleStationArr.current[0].description?roleStationArr.current[0]:roleStationArr.current[0].name
          let saveOption=roleStationArr.current[0]
          if(global.mapsettings&&global.mapsettings.layers){
            global.mapsettings.layers.forEach((item)=>{
              if(item.layerType=="PipenetLayer"){
                let roalarr = item.roleNames?item.roleNames.split(","):[]
                if(roalarr.length){
                  roalarr.forEach((result)=>{
                    if(result.includes('站点_')){
                      // stationname=result
                      roleStationArr.current.forEach((respon)=>{
                        if(respon.name==result){
                          saveOption=respon
                          stationname=respon.description?respon.description:respon.name
                        } 
                      })
                    }
                  })
                }
              }
            })
          }
          window._menuStation = saveOption;
          setStationList(roleStationArr.current)
          localStorage.setItem('globMenuStation',JSON.stringify(saveOption))
          setStationValue(stationname);
        }
      }
    }
  }, [global.userInfo]);
  return (
    <div className={className}>
      {renderTopMenu()}
      {
        roleStationArr.current.length>1&&(
          <div className={styles.curentPersonStationWriper}>
              <div className={styles.currentPersonStationSlect}>
                <Select 
                  style={{ width: '100%' }} 
                  ref={slectDom}
                  bordered={false}
                  onSearch={stationSerach}
                  // onChange={currentStationChange}
                  onFocus={()=>{stationOpen.current=true;setUpdate(stationOpen.current)}}
                  onBlur={()=>{
                    setTimeout(()=>{
                      stationOpen.current=false
                      setUpdate(stationOpen.current)
                    },500)
                  
                  }}
                  open={stationOpen.current}
                  value={stationvalue} 
                  showSearch
                  dropdownRender={(menu) => {
                    return  (
                        <>
                            <ul className={styles.scalnameSlectMenu}>
                                {
                                    showStationList.map((item)=>{
                                        return (
                                          <li style={{
                                            background: item.description ?
                                              item.description == stationvalue ?
                                                global.variableTheme.primaryColor+"47" : "" : item.name == stationvalue ? global.variableTheme.primaryColor+"47" : "",
                                                color:item.description?item.description==stationvalue?global.variableTheme.primaryColor:"#C0CEDC":item.name==stationvalue?global.variableTheme.primaryColor:"#C0CEDC",
                                          }} onClick={() => { closePan(item.description ? item.description : item.name, item.name) }}>
                                                  <span style={{margin:"0 5px",width:"10px",height:'14px',display:"flex",alignItems:"center",justifyContent:"center"}}>
                                                    <SvgComponent></SvgComponent>
                                                  </span>
                                                 
                                                  
                                                <span
                                                  title={item.description?item.description:item.name}
                                                  style={{
                                                    color:item.description?item.description==stationvalue?global.variableTheme.primaryColor:"#000":item.name==stationvalue?global.variableTheme.primaryColor:"#000",
                                                    fontWeight:item.description?item.description==stationvalue?"600":"400":item.name==stationvalue?"600":"400",
                                                  }}>{item.description?item.description:item.name}</span>
                                            </li>
                                        )
                                    })
                                }
                            </ul>
                        </>
                    )
                }} 
                >
                </Select>
              </div>
          </div>
        )
      }
      <Avatar menu config={props.global} updateCurrentIndex={props.updateCurrentIndex} updateConfig={props.updateConfig} logout={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);