/*
 * @Author: 吴文洁
 * @Date: 2019-09-10 18:26:03
 * @LastEditors: yuananting
 * @LastEditTime: 2021-07-06 14:49:12
 * @Description:
 */
import React, { useRef, useContext, useEffect, useState } from 'react';
import './Header.less';
import { Radio, Button, Dropdown, Modal, Tooltip, message } from 'antd';
import { LIVE_SHARE } from '@/domains/course-domain/constants';
import User from '@/common/js/user';
import Service from '@/common/js/service';
import StoreService from '@/domains/store-domain/storeService';
import BaseService from '@/domains/basic-domain/baseService';
import { XMContext } from '@/store/context';
import logoImg from '@/common/images/logo.png';
import CourseService from '@/domains/course-domain/CourseService';
import qrcode from '@/libs/qrcode/qrcode.js';
import Bus from '@/core/tbus';
import ClickOutside from '../../components/ClickOutside';
import _ from 'underscore';

const baseImg = 'https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png';
const { confirm } = Modal;
const RadioGroup = Radio.Group;

function Header(props) {
  const { menuType, handleMenuType } = props;
  const [storeId, setStoreId] = useState(User.getStoreId());
  const [storeName, setStoreName] = useState(User.getStoreName());
  const [avatar, setAvatar] = useState('');
  const [nickName, setNickName] = useState('');
  const [phone, setPhone] = useState('');
  const [list, setList] = useState([]);
  const [openDropdown, setOpenDropdown] = useState(false);
  const [instScroll, setInstScroll] = useState(false);
  const ctx = useContext(XMContext);
  const htmlUrl = `${LIVE_SHARE}store/index?id=${User.getStoreId()}&userId=${User.getUserId()}&from=work_weixin`;
  const helpCenterUrl = 'https://www.yuque.com/wangzhong-zkqw0/qixue'; // 帮助中心
  const storeUserId = User.getStoreUserId();
  const enterpriseId = User.getEnterpriseId();

  const messageHelpRef = useRef(null);

  const domRef = useRef(null);
  const listRef = useRef(list);

  useEffect(() => {
    htmlUrl && handleConvertShortUrl();
    Bus.bind('storeNameChange', (value) => {
      setStoreName(value);
    });
    getStoreList();
  }, []);

  useEffect(() => {
    storeUserId && getUserInfo();
    enterpriseId ? getEnterpriseUser() : User.setIsAdmin(false);
  }, [storeUserId]);

  useEffect(() => {
    if (!messageHelpRef.current) {
      return;
    }
    if (menuType) {
      messageHelpRef.current.style.marginLeft = '194px';
    } else {
      messageHelpRef.current.style.marginLeft = '76px';
    }
  }, [menuType]);

  function getUserInfo() {
    const param = {
      storeUserId: User.getStoreUserId(),
    };
    BaseService.getStoreUser(param).then((res) => {
      const { nickName, phone } = res.result;
      setNickName(nickName);
      setPhone(phone);
      setAvatar(res.result.avatar);
    });
  }

  function getEnterpriseUser() {
    const params = {
      enterpriseId,
      userId: User.getUserId(),
    };
    BaseService.getEnterpriseUser(params).then((res) => {
      const { isAdmin } = res.result;
      User.setIsAdmin(isAdmin);
    });
  }

  function getStoreList() {
    if (!enterpriseId) return null;
    const params = {
      enterpriseId,
      userId: User.getUserId(),
    };
    Service.Hades('public/customerHades/getStoreListUser', params).then((res) => {
      const newList = _.filter(res.result, (item) => item.state === 'VALID');
      setList(newList);
      listRef.current = newList;
    });
  }

  // 动态改变校区选择的阴影
  function addShadow() {
    domRef.current = document.querySelector('#college-radio-group');
    if (listRef.current.length > 4) {
      setInstScroll(true);
    } else {
      setInstScroll(false);
    }

    // 滚动到底部阴影就消失
    domRef.current.addEventListener('scroll', scrollEventListener);
  }

  function scrollEventListener() {
    if (domRef.current.scrollHeight === 190 + domRef.current.scrollTop) {
      setInstScroll(false);
    } else {
      setInstScroll(true);
    }
  }

  function userMenu() {
    return (
      <div className='user-center-dropdown'>
        <div className='user-detail'>
          <div className='box'>
            <Tooltip title={nickName}>
              <div className='name'>{nickName}</div>
            </Tooltip>
            <span className='phone'>{phone}</span>
          </div>
          <span className='setting' onClick={() => toPersonalInfoPage()}>
            个人设置
            <span className='iconfont icon'>&#xe79b;</span>
          </span>
        </div>
        <div className='menu'>
          {User.getEnterpriseId() && (
            <div
              className='menu-item'
              key='1'
              onClick={() => {
                window.RCHistory.push({
                  pathname: '/college-manage',
                });
              }}>
              <span className='menu-before iconfont icon'>&#xe84e;</span>
              <span>进入管理后台</span>
              <span className='menu-after iconfont icon'>&#xe79b;</span>
            </div>
          )}
          <div
            className='menu-item'
            key='2'
            onClick={(e) => {
              handleLogoutConfirm();
            }}>
            <span className='menu-before iconfont icon'>&#xe870;</span>
            <span>退出登录</span>
            <span className='menu-after iconfont icon'>&#xe79b;</span>
          </div>
        </div>
      </div>
    );
  }

  function handleMenu() {
    handleMenuType();
  }

  function toPersonalInfoPage() {
    window.RCHistory.push({
      pathname: `/personal-info`,
    });
  }

  function handleLogoutConfirm() {
    return confirm({
      title: '你确定要退出登录吗？',
      content: '退出后，需重新登录',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe839; </span>,
      okText: '退出登录',
      cancelText: '点错了',
      onOk: () => {
        handleLogout();
      },
    });
  }

  function handleLogout() {
    BaseService.logout({ identifier: User.getIdentifier() }).then((res) => {
      User.removeUserId();
      User.removeToken();
      User.removeEnterpriseId();
      User.clearUserInfo();
      const url = `${LIVE_SHARE}store/index?id=${User.getCustomerStoreId() || User.getStoreId()}&userId=${User.getUserId()}&from=work_weixin`;
      window.location.href = url;
    });
  }

  function handleConvertShortUrl() {
    CourseService.getQrcode({
      urls: [htmlUrl],
    }).then((res) => {
      const { result = [] } = res;
      const qrcodeWrapDom = document.querySelector('#h5-qrcode');
      const qrcodeNode = new qrcode({
        text: result[0].shortUrl,
        size: 110,
      });

      qrcodeWrapDom && qrcodeWrapDom.appendChild(qrcodeNode);
    });
  }

  // 复制分享链接
  function handleCopy() {
    window.copyText(htmlUrl);
    message.success('已复制学院地址，快去分享吧~');
  }

  return (
    <div id='top-container' className='top-container'>
      <div className='top top-nav'>
        {/* <div>
          <img src={topLeftLogo} className="logo" alt="" />
        </div> */}
        <div className='message-help' ref={messageHelpRef}>
          {list.length ? (
            <ClickOutside
              onClickOutside={() => {
                if (openDropdown) {
                  setOpenDropdown(false);
                }
              }}
              className='college-container'>
              <div style={{ width: '100%', height: '100%' }}>
                <div className='college' onClick={() => setOpenDropdown(false)}>
                  <span
                    className='college-name'
                    onClick={(e) => {
                      e.stopPropagation();
                      setOpenDropdown(!openDropdown);
                      addShadow();
                    }}>
                    {storeName}
                  </span>
                  {list.length > 1 && (
                    <span
                      className={`icon iconfont ${list.length > 1 ? 'select' : ''}`}
                      onClick={(e) => {
                        e.stopPropagation();
                        setOpenDropdown(!openDropdown);
                        addShadow();
                      }}>
                      &#xe651;
                    </span>
                  )}
                </div>
                <div className={`select-college ${openDropdown ? 'active' : ''}`}>
                  <h2>切换学院</h2>
                  <RadioGroup
                    onChange={(e) => {
                      setStoreId(e.target.value);
                      User.setStoreId(e.target.value);
                      list.map((item) => {
                        if (item.id === e.target.value) {
                          User.setStoreUserId(item.storeUserId);
                        }
                      });
                      User.setUserId(User.getUserId());
                      User.setToken(User.getToken());
                      User.setEnterpriseId(User.getEnterpriseId());
                      window.RCHistory.push('/home');
                      window.location.reload();
                    }}
                    value={storeId}
                    id='college-radio-group'>
                    {_.map(list, (item) => (
                      <Radio value={item.id} key={item.id}>
                        <span className='name'>{item.storeName}</span>
                      </Radio>
                    ))}
                  </RadioGroup>
                  {instScroll && <div className='scroll-shadow'></div>}
                  {/* <div className="control">
                    <Button
                      size="small"
                      onClick={() => {
                        setOpenDropdown(false);
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      size="small"
                      type="primary"
                      onClick={() => {
                        User.setStoreId(storeId);
                        window.location.reload();
                      }}
                    >
                      确定
                    </Button>
                  </div> */}
                </div>
              </div>
            </ClickOutside>
          ) : (
            <div className='store-related'>
              <div className='store-name'>{storeName}</div>
            </div>
          )}
          <div className='right-box'>
            <div className='link-to-store'>
              <div className='right-bg-img'>
                <img src='https://image.xiaomaiketang.com/xm/WCwjyyXYda.png'></img>
              </div>
              <div className='link'>
                <span className='link-btn'>
                  <span className='icon iconfont tool-tip-right'>&#xe85d;</span>
                  <span className='text'>前往学院</span>
                </span>
                <div className='store-popover'>
                  <div className='pc-url'>
                    <div className='name'>网页端学院</div>
                    <div
                      className='url-link'
                      onClick={() => {
                        window.open(htmlUrl);
                      }}>
                      {'立即前往 >'}
                    </div>
                  </div>
                  <div className='h5-url'>
                    <div className='name'>手机端学院</div>
                    <div id='h5-qrcode'></div>
                    <div className='tip'>微信扫码，打开学院</div>
                  </div>
                </div>
              </div>
              <div className='share' onClick={handleCopy}>
                <span className='share-btn'>
                  <span className='icon iconfont tool-tip-right'>&#xe85e;</span>
                  <span className='text'>分享学院</span>
                </span>
              </div>
              <div className='help'>
                <a href={helpCenterUrl} target='_blank' className='help-btn'>
                  <span className='icon iconfont tool-tip-right'>&#xe8ed;</span>
                  <span className='text'>帮助中心</span>
                </a>
              </div>
            </div>
            <Dropdown overlay={userMenu()} arrow>
              <div className='user'>
                <img
                  style={{
                    width: 32 + 'px',
                    height: 32 + 'px',
                    borderRadius: '50%',
                    overflow: 'hidden',
                    flexShrink: 0,
                  }}
                  src={avatar || baseImg}
                />
                <span className='name'>{nickName}</span>
              </div>
            </Dropdown>
          </div>
        </div>
      </div>
    </div>
  );
}
export default Header;
