import React, { useCallback, useState } from 'react';
import { CloseOutlined, EditOutlined, LogoutOutlined, SendOutlined, SettingOutlined, SwapOutlined, SwapRightOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Input, Menu, message, Modal, Spin } from 'antd';
import { history, useModel } from 'umi';
import { getPageQuery } from '@/utils/utils';
import { outLogin, selectCompanyApi } from '@/services/login';
import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { useAjax } from '@/Hook/useAjax';
import { api } from '@/services/api'
import useCopy from '@/Hook/useCopy';
import { ReactComponent as LaunchSvg } from '@/assets/launch.svg'

export interface GlobalHeaderRightProps {
  menu?: boolean;
}
let headImg = require('../../../public/headImg2.png')
/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  // await outLogin();
  const { redirect } = getPageQuery();
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    outLogin()
    // setCookie('Admin-Token', '1', -300)
    localStorage.removeItem('Admin-Token')
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: window.location.href,
      }),
    });
  }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { copy } = useCopy()
  const selectCompany = useAjax((companyId: number) => selectCompanyApi(companyId), { formatResult: true })
  const { initialState, setInitialState } = useModel('@@initialState');
  const { modifyPassword } = useModel('useOperating.useUser')
  const [visible, setVisible] = useState<boolean>(false)
  const [oldPassWord, setOldPassWord] = useState<string>('')
  const [passWord, setPassWord] = useState<string>('')
  const [OkPassWord, setOkPassWord] = useState<string>('')
  const [dialogVisible, setDialogVisible] = useState<boolean>(false)
  const onMenuClick = useCallback(
    (event: any) => {
      const { key } = event;
      if (key === 'logout') {
        setInitialState({ ...initialState, currentUser: undefined });
        loginOut();
        return;
      }
      if (key === 'edit') {
        setVisible(true)
        console.log('修改密码')
        return;
      }
      if (key === 'company') {
        setDialogVisible(() => true)
        return
      }
      if (key === 'admin') {
        let token = localStorage.getItem('Admin-Token')
        window.open(api.includes('test') || api === 'api' ? `http://test.zanxiangnet.com/admin/#/login?token=${token}` : `https://mp.zanxiangnet.com/admin/#/login?token=${token}`)
        return
      }
      if (key === 'release') {
        let token = localStorage.getItem('Admin-Token')
        window.open(api.includes('test') || api === 'api' ? `http://test.adq.zanxiangnet.com/#/user/login?token=${token}` : `http://adq.zanxiangnet.com/#/user/login?token=${token}`)
        return
      }
      history.push(`/account/${key}`);
    },
    [],
  );
  const submit = useCallback(() => {
    if (!oldPassWord) {
      message.error('请输入旧密码!')
      return
    }
    if (!passWord) {
      message.error('请输入新密码!')
      return
    }
    if (!OkPassWord) {
      message.error('请输入确认密码!')
      return
    }
    if (passWord.length < 6) {
      message.error('密码需要6位以上!')
      return
    }
    if (passWord !== OkPassWord) {
      message.error('两次输入的密码不一致!')
      return
    }
    if (passWord === OkPassWord && oldPassWord) {
      modifyPassword.run({ oldPassword: oldPassWord, password: passWord, userId: initialState?.currentUser?.userId }).then((res) => {
        if (res) {
          message.success('修改密码成功！')
          setVisible(false)
          loginOut();
        }
      })
    }
  }, [passWord, oldPassWord, OkPassWord])
  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      {menu && (
        <Menu.Item key="center">
          <UserOutlined />
          个人中心
        </Menu.Item>
      )}
      {menu && (
        <Menu.Item key="settings">
          <SettingOutlined />
          个人设置
        </Menu.Item>
      )}
      {menu && <Menu.Divider />}
      {
        currentUser?.powerLevel === 999 && <Menu.Item key="admin">
          <SendOutlined />
          管理系统
        </Menu.Item>
      }
      <Menu.Item key="release">
        <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><LaunchSvg /></span>
        新投放系统
      </Menu.Item>
      <Menu.Item key="company">
        <SwapOutlined />
        切换公司
      </Menu.Item>
      <Menu.Item key="edit">
        <EditOutlined />
        修改密码
      </Menu.Item>
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );

  // 切换公司
  const setCompanyHandle = (companyId: number) => {
    selectCompany.run(companyId).then((res: any) => {
      setDialogVisible(false)
      localStorage.setItem('Admin-Token', res?.data?.token)
      window.location.reload()
    })
  }
  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`} onClick={() => {
          let AdminToken: any = localStorage.getItem('Admin-Token')
          copy(AdminToken)
        }}>
          <Avatar size="small" className={styles.avatar} src={currentUser.avatar || headImg} alt="avatar" />
          <span className={`${styles.name} anticon`}>{currentUser.name}</span>
        </span>
      </HeaderDropdown>
      <Modal
        title="修改密码"
        visible={visible}
        onOk={submit}
        onCancel={() => setVisible(false)}
      >
        <p className={styles.editPasswordP}>
          <label>旧密码</label>
          <Input
            value={oldPassWord}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              let value = e.target.value
              setOldPassWord(value)
            }}
          />
        </p>
        <p className={styles.editPasswordP}>
          <label>新密码</label>
          <Input
            value={passWord}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              let value = e.target.value
              setPassWord(value)
            }}
          />
        </p>
        <p className={styles.editPasswordP}>
          <label>确认密码</label>
          <Input
            value={OkPassWord}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              let value = e.target.value
              setOkPassWord(value)
            }}
          />
        </p>
      </Modal>
      <div className={styles.dialog} style={{ display: dialogVisible ? 'block' : 'none' }}>
        <div className={styles.companyAccount}>
          <div className={styles.close} onClick={() => { setDialogVisible(false) }}><CloseOutlined style={{ color: '#000' }} /></div>
          <h3>切换公司账户</h3>
          <div className={styles.chooseTableBlock}>
            <Spin spinning={selectCompany?.loading}>
              {initialState?.currentUser?.companyList?.map((item: any) => {
                if (item.companyId != initialState.currentUser?.onlineCompanyId) {
                  return <div className={`${styles.acTableLineContent} ${styles.acTableLine}`} key={item?.companyId} onClick={() => { setCompanyHandle(item?.companyId) }}>
                    <div className={styles.actname}>{item?.companyInfo?.companyName}</div>
                    <div className={styles.right}> <div className={styles.actcha}>{item?.powerLevel === 999 ? '超级管理员' : item?.powerLevel === 100 ? '系统管理员' : item?.powerLevel === 99 ? '管理员' : '普通用户'}</div> <SwapRightOutlined className={styles.iconRight} /></div>
                  </div>
                } else {
                  return <div className={`${styles.acTableLineContent} ${styles.acNone}`} key={item?.companyId}>
                    <div className={styles.actname}>{item?.companyInfo?.companyName}</div>
                    <div className={styles.right}> <div className={styles.actcha}>{item?.powerLevel === 999 ? '超级管理员' : item?.powerLevel === 100 ? '系统管理员' : item?.powerLevel === 99 ? '管理员' : '普通用户'}</div> <SwapRightOutlined className={styles.iconRight} /></div>
                  </div>
                }
              })}
            </Spin>
          </div>
        </div>
      </div>
    </>
  );
};

export default AvatarDropdown;