import styles from '@/components/Operation/index.module.scss'
import ImageUrl from '@/utils/package/imageUrl';
import { useEffect, useState, memo } from "react";
type OperationKeyType = 'minimize' | 'quit' | 'maximize' | 'unmaximize' | 'hide' | 'show';
type OperationType = {
  icon: string;
  key: OperationKeyType;
  title: string;
  onClick: Function;
  show: boolean;
}
const Operation: React.FC = () => {
  const [_windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const [operationList, setOperationList] = useState<OperationType[]>([{
    icon: ImageUrl.icon17,
    key: 'minimize',
    title: '最小化',
    onClick: (key: OperationKeyType) => {
      window.electron.setViewStatus(key)
    },
    show: true,
  },
  {
    icon: ImageUrl.icon20,
    key: 'maximize',
    title: '最大化',
    onClick: (key: OperationKeyType) => {
      window.electron.setViewStatus(key)
    },
    show: true,
  },
  {
    icon: ImageUrl.icon19,
    key: 'unmaximize',
    title: '还原大小',
    onClick: (key: OperationKeyType) => {
      window.electron.setViewStatus(key)
    },
    show: false,
  },
  {
    icon: ImageUrl.icon18,
    key: 'quit',
    title: '关闭',
    onClick: (key: OperationKeyType) => {
      if (location.hash.indexOf('/meeting') === -1) {
        window.electron.setViewStatus(key)
      } else {
        window.electron.quit(false)
      }
    },
    show: true,
  },])
  useEffect(() => {
    getIsMaximized()
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
      getIsMaximized()
    };
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  const getIsMaximized = (): void => {
    window.electron.getIsMaximized().then((res: boolean) => {
      changeOperationList(res ? 'maximize' : 'unmaximize')
    })
  }

  const changeOperationList = (str: OperationKeyType): void => {
    const newOperationList = [...operationList]
    const unmaximize = newOperationList.find((item: OperationType) => item.key === 'unmaximize') as OperationType;
    const maximize = newOperationList.find((item: OperationType) => item.key === 'maximize') as OperationType;
    unmaximize.show = str === 'maximize' ? true : false;
    maximize.show = str === 'maximize' ? false : true;
    setOperationList(newOperationList)
  }

  return (
    <>
      <div className={`${styles.operation} drag`}>
        {
          operationList.map((item: OperationType, index: number) => {
            return (item.show ?
              <div title={item.title} key={index} onClick={() => item.onClick(item.key)}>
                <img src={item.icon} alt="" />
              </div> : null
            )
          })
        }
      </div>
    </>
  )
}
export default memo(Operation)