import * as React from 'react';
import { history, useModel } from 'umi';
import { Popover, Divider, Modal, message } from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react';
import { useCallback, useMemo, useRef, useState } from 'react';
import _ from 'lodash';
import styles from './index.less';
import { useClickAway } from 'ahooks';
import { Avatar, ListItem } from '@/lib';
import { Session, Text } from '@/utils';
import Setting from '../Settings';
import classNames from 'classnames';
import defaultLogo from '@/assets/logo.svg';
import API from '@/api';
import { useMobStore } from '@/hooks';
import { baseLayoutStore } from '@/layouts/BaseLayout/Store';
import moment from 'moment'

const UserInfo: React.FC = observer(() => {
  const [visible, setVisible] = useState<boolean>(false);
  const logoRef = useRef(null);

  const user = Session.get();

  useClickAway(
    () => {
      setVisible(false);
    },
    () => logoRef.current,
  );

  const path = useMemo(() => {
    if (_.isEmpty(user.avatar)) {
      return null;
    }
    return /http(s):.*/.test(user.avatar)
      ? user.avatar
      : `/gateway/fileservice/api/file/view/${user.avatar
      }?access_token=${Session.getAccessToken()}`;
  }, [user]);

  const avatar = useMemo(() => {
    return (
      <Avatar
        icon={user.icon}
        path={path}
        name={user.name}
        size="normal"
        style={{ background: baseLayoutStore.layout === 'side' ? 'rgba(0,0,0,.1)' : 'rgba(255,255,255,.2)' }}
      />
    )
  }, [path])

  return (
    <Popover
      visible={visible}
      title={null}
      content={<Menu />}
      placement="bottom"
      trigger="click"
      overlayClassName={styles.overlay}
      overlayInnerStyle={{ borderRadius: 8 }}
    >
      <div
        className={styles.btn}
        ref={logoRef}
        onClick={() => setVisible(!visible)}
      >
        <Item data={{ icon: avatar, title: user.name, company: user.orgName }} />
      </div>
    </Popover>
  );
});

const ModalStyle = {
  padding: 0,
  minHeight: '70vh',
  maxHeight: '70vh',
  overflow: 'hidden auto',
};

const Menu = observer(() => {
  const [visible, setVisible] = useState<boolean>(false);
  const [isOrgVisible, setIsOrgVisible] = useState<boolean>(false);
  const { refresh } = useModel('@@initialState');
  const logout = useCallback(() => {
    API.AccountService.fakeLogout().then(({ success }) => {
      if (success) {
        Session.destroy();
        refresh && refresh();
        history.push('/passport/sign-in');
      }
    });
  }, []);

  return (
    <div className={styles.menu}>
      <div className={styles.username}>Hi {Session.get().name}， {moment().format('a')}好！</div>
      <ListItem
        ghost
        onClick={() => setIsOrgVisible(true)}
        style={{ cursor: 'pointer' }}
        data={{
          id: 'switch',
          color: '#666',
          icon: 'icon-company',
          label: '组织切换',
          path: '',
        }}
      />
      <Divider style={{ margin: '12px 0' }} />
      <ListItem
        ghost
        onClick={() => setVisible(!visible)}
        style={{ cursor: 'pointer' }}
        data={{
          id: 'setting',
          color: '#666',
          icon: 'icon-setting',
          label: '个人设置',
        }}
      />
      <Divider style={{ margin: '12px 0' }} />
      <ListItem
        ghost
        onClick={logout}
        style={{ cursor: 'pointer' }}
        data={{
          id: 'LOGOUT',
          color: '#666',
          icon: 'icon-logout',
          label: '退出登陆',
          path: '',
        }}
      />
      {visible && (
        <Modal
          title="个人设置"
          centered
          bodyStyle={ModalStyle}
          visible={visible}
          destroyOnClose
          onCancel={() => setVisible(false)}
          footer={[]}
          width={'65vw'}
        >
          <Setting />
        </Modal>
      )}
      {isOrgVisible && (
        <Modal
          width={450}
          title="租户/组织切换"
          visible={isOrgVisible}
          footer={null}
          maskClosable={false}
          onCancel={(e) => {
            e.stopPropagation();
            setIsOrgVisible(false);
          }}
        >
        </Modal>
      )}
    </div>
  );
});

interface ItemProps {
  data: any;
  onClick?: Function;
}
const Item = observer(({ data = {}, onClick }: ItemProps) => {
  const store = useMobStore('baseLayoutStore')
  const classes = classNames({
    [styles['item']]: true,
    [styles.dark]: store.layout !== 'side'
  });
  return (
    <div className={classes} style={{ color: baseLayoutStore.layout === 'side' ? '#666' : '#eee' }}>
      <div className={styles.logo}>
        {typeof data.icon === 'string' ? <img src={data.icon || defaultLogo} /> : data.icon}
      </div>
      <div className={styles.content}>
        <div className={styles.label}>
          <div className={styles.title} >{Text.toShortText(data.company || '未加入组织', 6)}</div>
        </div>
      </div>
      <div className={styles.icon}>
        <CaretDownOutlined />
      </div>
    </div>
  );
});

export default UserInfo;
