import React, { useEffect, FC, useState } from 'react';
import { connect, ConnectedProps, useDispatch } from 'react-redux';
import {
  DownOutlined,
  EasyVFilled,
  UserCircleOutlined,
  RenewalSquareOutlined,
  SwapOutlined,
  GiftOutlined,
  KeySquareOutlined,
  AppstoreOutlined,
  LogoutOutlined
} from '@easyv/react-icons';
import { Layout, Menu, Dropdown } from '@easyv/antd';
import { Link, NavLink } from 'react-router-dom';
import TenantModal from './TenantModal';
// import Extend from '../containers/screen-list/components/Extend';
import AccessKeyModal from './AccessKeyModal';
import PasswordResetModal from './PasswordResetModal';
import GeneralSettingModal from './GeneralSettingModal';
import { loginOut } from 'models/user';
import { getApps } from 'models/app';
import { RootState } from 'models';
import VersionNotice from './VersionNotice';
import defaultLogo from 'images/logo.png';
import styles from './MainLayout.less';
import EasySpace from 'components/easySpace';
import TrialUpgrade from 'components/TrialUpgrade';
import IconButton from './IconButton';
import moment from 'moment';
import EasyvHelpDropdown from './EasyvHelpDropdown';
import EasyvTooltip from './EasyvTooltip';
import { getSpace } from 'models/space';
import localIcon from 'images/local.svg';
import saasVipIcon from 'images/saas_vip.svg';
import saasBasicIcon from 'images/saas_basic.svg';
import saasAdvancedIcon from 'images/saas_advanced.svg';
import saasPersonalIcon from 'images/saas_personal.svg';
import EasyvModal, { useProductPermissionModalRef } from './EasyvModal';
import { setScreenState } from 'models/screen-detail';
import PlatformMigrate from './PlatformMigrate';
import useProductionInfo from './easyUse/useProductionInfo';
import { getRenewalRedirectUrl, resultLocalProductionName, resultSaasProdcutionName ,getAssetsUrl} from 'utils/utils';
import { useAuth } from 'components/easyUse';
import PersonalModal from './PersonalModal';
import { modules } from 'constants/authority';
import classnames from 'classnames';
import { UserType } from 'models/user.types';

type PropsFromRedux = ConnectedProps<typeof connector>;

const goToHomePage = () => {
  window.location.href = window.appConfig.HOME_URL ? window.appConfig.HOME_URL : '/';
};

const { LOGO } = window.appConfig;

const MainLayout: FC<PropsFromRedux> = ({ userInfo, userType, loginOut, getApps, children }) => {
  const [visible, setVisible] = useState(false);
  const [qianyi, setQianYi] = useState(false);
  const { userName = '', tenantName = '', role = 0, type, exp, edition, tenantId, skuId } = userInfo;
  const productionInfo = useProductionInfo();
  const { isRenew = false } = productionInfo;
  const dispatch = useDispatch();
  const { checkAuth } = useAuth();

  let { supportMobile = true } = edition || {};
  const { id, trialChanged } = edition || {};
  const expiredAt = edition?.expiredAt;

  const userEnv = window.appConfig.USER_ENV;
  const modalRef = useProductPermissionModalRef();
  useEffect(() => {
    if (!(isLocal && type === 'education')) {
      getApps();
      dispatch(getSpace());
      dispatch(setScreenState(''));
    }
  }, []);

  const admin = role > 0;
  const isLocal = window.appConfig.LOCAL; //是否本地部署
  const enableAdmin = isLocal ? type === 'community' || type === 'lifelong' : true;
  supportMobile = isLocal ? true : supportMobile;

  const isPermanent = !(parseInt(exp?.split('年')[0] || '0') < 2050); //运行平台是否永久（大于2050算作永久）

  const uicMenu = [
    <Menu.Item key="1">
      <TenantModal>
        <SwapOutlined style={{ marginRight: 6 }} />
        <span title={tenantName} style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {tenantName}
        </span>
      </TenantModal>
    </Menu.Item>,
    <Menu.Item key="2">
      <a target="_blank" href={window.appConfig.USER_CENTER_URL} rel="noopener" style={{ color: '#333' }}>
        <UserCircleOutlined style={{ marginRight: 6 }} />
        <span>用户中心</span>
      </a>
    </Menu.Item>
  ];

  const localMenu = [
    <Menu.Item key="6">
      <PasswordResetModal>
        <i className="icon iconfont icon-xiugaimima-" style={{ marginRight: 6, fontSize: 14 }} />
        <span>修改密码</span>
      </PasswordResetModal>
    </Menu.Item>
    // <Menu.Item key="17">
    //   <Extend>
    //     <i className="icon iconfont icon-xiangmu1" style={{ marginRight: 6 }} />
    //     <span>项目数扩容</span>
    //   </Extend>
    // </Menu.Item>
  ];

  const opMenu = [
    checkAuth('changeIdentity') && (
      <Menu.Item key="5">
        <a href={`/login/verify?return_to=${window.location.href}`} rel="noopener" className={styles.itemA}>
          <SwapOutlined className={styles.itemIcon} />
          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>切换身份</span>
        </a>
      </Menu.Item>
    ),
    <Menu.Item key="2">
      <a href={`${window.appConfig.USER_CENTER_URL}`} rel="noopener" className={styles.itemA}>
        <UserCircleOutlined className={styles.itemIcon} />
        <span>用户中心</span>
      </a>
    </Menu.Item>
  ];
  if (userType !== UserType.COLLABORATORS) {
    opMenu.push(
      <Menu.Item key="66">
        <a href={`${window.appConfig.USER_CENTER_URL}/invite-friends`} rel="noopener" className={styles.itemA}>
          <GiftOutlined className={styles.itemIcon} />
          <span>邀请有礼</span>
        </a>
      </Menu.Item>
    );
  }

  if (skuId && [4, 5, 6, 8].includes(skuId)) {
    opMenu.push(
      <Menu.Item key="3">
        <a target="_blank" href={getRenewalRedirectUrl(isRenew, userInfo?.edition?.id)} rel="noopener" className={styles.itemA}>
          <RenewalSquareOutlined className={styles.itemIcon} />
          <span>续费</span>
        </a>
      </Menu.Item>
    );
  }

  const menuData = userEnv === 'uic' ? uicMenu : userEnv === 'op' ? opMenu : localMenu;
  if (checkAuth(modules.componentDevelop)) {
    menuData.push(
      <Menu.Item key="33">
        <AccessKeyModal>
          <KeySquareOutlined style={{ marginRight: 6, display: 'flex' }} />
          <span>Accesskey管理</span>
        </AccessKeyModal>
      </Menu.Item>
    );
  }

  const versionProbation = () => {
    setVisible(true);
  };

  const menu = (
    <Menu className={styles.dropdownMenu}>
      <Menu.Item key="1" style={{ padding: '0' }}>
        <div className={styles.certificateInfo}>
          <div>
            <p style={{ paddingBottom: 6, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              {/* <ProductIcon type={type}/> */}
              <span>
                {!isLocal && <TypeIcon type={isLocal ? type : id} />}
                <span>
                  {isLocal
                    ? type && resultLocalProductionName(type)
                    : Array.isArray(resultSaasProdcutionName(skuId!, isRenew)) && resultSaasProdcutionName(skuId!, isRenew)?.[0]}
                </span>
              </span>
              {trialChanged === 0 && (skuId === 7 || skuId === 2) && (
                <span
                  className={classnames(styles.applyProbation, skuId === 7 ? styles.personal : styles.senior)}
                  onClick={versionProbation}>
                  {skuId === 7 ? '申请高级版试用' : '申请个人版试用'}
                </span>
              )}
            </p>
            <p className={styles.account}>账号ID：{tenantId}</p>
            {!isLocal && <p className={styles.account}>{moment(expiredAt).format('YYYY-MM-DD')}到期</p>}
          </div>
          {isLocal && type != 'lifelong' && !isPermanent && (
            <div
              style={{
                fontSize: 14,
                marginTop: 6
              }}>
              <span style={{ color: '#b4b7c1' }}>{`${exp}过期`}</span>
              <Link to="/active" style={{ marginLeft: 8 }}>
                升级
              </Link>
            </div>
          )}
        </div>
      </Menu.Item>

      {userEnv === 'uic' ? uicMenu : userEnv === 'op' ? opMenu : localMenu}
      {checkAuth('generalSetting') && (
        <Menu.Item key="7">
          <GeneralSettingModal>
            <AppstoreOutlined style={{ marginRight: 6, display: 'flex' }} />
            <span>通用设置</span>
          </GeneralSettingModal>
        </Menu.Item>
      )}
      <Menu.Divider key="89" className={styles.divider} />
      <Menu.Item key="4">
        <div className={styles.itemA} onClick={loginOut}>
          <LogoutOutlined className={styles.itemIcon} />
          <span>退出</span>
        </div>
      </Menu.Item>
    </Menu>
  );

  const onVisibleChange = (visible) => {
    if (visible) {
      if (isLocal && window.location.pathname.includes('/qianyi')) {
        setQianYi(true);
      } else {
        setQianYi(false);
      }
    }
  };

  return (
    <Layout className={styles.container}>
      <header className={styles.header}>
        <div className={styles.logo} onClick={goToHomePage}>
          <img className={styles.img} src={LOGO ? getAssetsUrl(LOGO) : defaultLogo} />
          <i className="icon iconfont icon-arrow_right_link" />
        </div>
        <div className={styles.menu}>
          <NavLink
            exact
            to="/"
            className={styles.menuItem}
            isActive={(match, location) => {
              if (match || location.pathname.includes('/screens/trash') || location.pathname.includes('/qianyi')) {
                return true;
              } else {
                return false;
              }
            }}>
            <i className={'icon iconfont ' + styles.icon1} />
            我的应用
          </NavLink>

          <NavLink to="/source" className={styles.menuItem}>
            <i className={'icon iconfont ' + styles.icon2} />
            我的数据
          </NavLink>

          {checkAuth('showSupportMobile') &&
            (supportMobile ? (
              <NavLink to="/app" className={styles.menuItem}>
                <span>终端交互</span>
                {!isLocal && (
                  <IconButton style={{ marginLeft: '8px', color: '#fff' }} type={isRenew ? 'renew_advanced' : 'saas_advanced'} />
                )}
              </NavLink>
            ) : (
              <EasyvTooltip title="升级以获得高级功能 >>">
                <p className={styles.menuItem}>
                  <span
                    onClick={() => {
                      modalRef.current?.show('app', 'saas_advanced');
                    }}>
                    终端交互
                  </span>
                  <IconButton style={{ marginLeft: '8px', color: '#fff' }} type={isRenew ? 'renew_advanced' : 'saas_advanced'} />
                </p>
              </EasyvTooltip>
            ))}
          {checkAuth(modules.componentDevelop) ? (
            <NavLink to="/constants" className={styles.menuItem}>
              <span>组件开发</span>
              {!isLocal && <IconButton style={{ marginLeft: '8px', color: '#fff' }} type={isRenew ? 'renew_vip' : 'saas_vip'} />}
            </NavLink>
          ) : !isLocal && id !== 'saas_personal' ? (
            <EasyvTooltip title="升级以获得高级功能 >>">
              <p className={styles.menuItem}>
                <span
                  onClick={() => {
                    modalRef.current?.show('constants', 'saas_vip');
                  }}>
                  组件开发
                </span>
                <IconButton style={{ marginLeft: '8px', color: '#fff' }} type={isRenew ? 'renew_vip' : 'saas_vip'} />
              </p>
            </EasyvTooltip>
          ) : null}
          {type !== 'education' && window.appConfig.USER_ENV === 'local' && admin && (
            <NavLink to="/users" className={styles.menuItem}>
              用户管理
            </NavLink>
          )}

          {enableAdmin && admin && (
            <NavLink to="/admin" className={styles.menuItem}>
              后台管理
            </NavLink>
          )}

          {/* 独立部署和renew或者saas尊享版或者高级版可用 */}
          {isLocal ? (
            <NavLink to="/spaceShipList" className={styles.menuItem}>
              门户管理
            </NavLink>
          ) : checkAuth('openSpaceshipList') ? (
            <NavLink to="/spaceShipList" className={styles.menuItem}>
              <span>门户管理</span>
              <IconButton style={{ marginLeft: '8px', color: '#fff' }} type={isRenew ? 'renew_advanced' : 'saas_advanced'} />
            </NavLink>
          ) : checkAuth('showSpaceshipList') ? (
            <EasyvTooltip title="升级以获得高级功能 >>">
              <p
                className={styles.menuItem}
                onClick={() => {
                  modalRef.current?.show('cockpit', 'saas_advanced');
                }}>
                <span>门户管理</span>
                <IconButton style={{ marginLeft: '8px', color: '#fff' }} type={isRenew ? 'renew_advanced' : 'saas_advanced'} />
              </p>
            </EasyvTooltip>
          ) : null}

          {checkAuth(modules.resource) && (
            <NavLink to="/resource" className={styles.menuItem}>
              资源中心
            </NavLink>
          )}
        </div>
        <div className={styles.space} />

        <div className={styles.userInfo}>
          {skuId && [2, 7].includes(skuId) && (
            <span style={{ marginRight: 24 }}>
              <TrialUpgrade skuId={skuId} />
            </span>
          )}
          {checkAuth(modules.space) && <EasySpace />}
          <EasyvHelpDropdown />
          <div className={styles.square}>
            <EasyVFilled className={styles.avatar} />
          </div>

          <Dropdown overlay={menu} trigger={['click']} onVisibleChange={(visible) => onVisibleChange(visible)}>
            <span className={styles.cursor}>
              <span className={styles.titleHidden} title={userName}>
                {userName}
              </span>
              <DownOutlined style={{ fontSize: 14, lineHeight: '10px' }} />
            </span>
          </Dropdown>
        </div>
      </header>
      <Layout className={styles.layout}>{userName && children}</Layout>
      <div className={styles.bc}></div>
      {!isLocal && <VersionNotice />}
      {/* TODO后续独立部署版本要加上独立部署限制 */}
      {isLocal && <PlatformMigrate />}
      <EasyvModal.ProductPermissionModal ref={modalRef} />

      <PersonalModal visible={visible} changeVisible={setVisible} />
    </Layout>
  );
};

const TypeIcon = ({ type }) => {
  const code = window.appConfig.LOCAL ? 'local' : type;
  let url = '';
  switch (code) {
    case 'local':
      url = localIcon;
      break;
    case 'saas_vip':
      url = saasVipIcon;
      break;
    case 'saas_basic':
      url = saasBasicIcon;
      break;
    case 'saas_advanced':
      url = saasAdvancedIcon;
      break;
    case 'saas_personal':
      url = saasPersonalIcon;
      break;
  }
  return url ? (
    <img
      style={{
        marginLeft: '-4px',
        lineHeight: '19px',
        marginRight: 5
      }}
      src={url}
      alt=""
    />
  ) : null;
};

function mapStateToProps({ user }: RootState) {
  const { userInfo } = user;
  const userType = user.userType;
  return {
    userInfo,
    userType
  };
}

const mapDispatchToProps = {
  loginOut: loginOut,
  getApps: getApps
};

const connector = connect(mapStateToProps, mapDispatchToProps);

export default connector(MainLayout);
