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';

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)
    sessionStorage.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 { edit, 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 = sessionStorage.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
      }
      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;
  }

  let items = []
  if (menu) {
    items.push({ label: '个人中心', key: 'center', icon: <UserOutlined /> })
    items.push({ label: '个人设置', key: 'settings', icon: <SettingOutlined /> })
  }
  if (currentUser?.powerLevel === 999) {
    items.push({ label: '管理系统', key: 'admin', icon: <SendOutlined /> })
  }
  items.push({ label: '切换公司', key: 'company', icon: <SwapOutlined /> })
  items.push({ label: '修改密码', key: 'edit', icon: <EditOutlined /> })
  items.push({ label: '退出登录', key: 'logout', icon: <LogoutOutlined /> })

  // 切换公司
  const setCompanyHandle = (companyId: number) => {
    selectCompany.run(companyId).then((res: any) => {
      setDialogVisible(false)
      sessionStorage.setItem('Admin-Token', res?.data?.token)
      window.location.reload()
    })
  }
  return (
    <>
      <HeaderDropdown menu={{ items, onClick: onMenuClick }}>
        <span className={`${styles.action} ${styles.account}`} onClick={() => {
          let AdminToken: any = sessionStorage.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="修改密码"
        open={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;