/*
 * @Author: 吴文洁
 * @Date: 2019-09-10 18:26:03
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-05-10 10:34:13
 * @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 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';

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 storeUserId = User.getStoreUserId();
  const enterpriseId = User.getEnterpriseId();

  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]);
  
  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({}).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>
          {menuType ? <img src='https://image.xiaomaiketang.com/xm/fe4NCjr7XF.png' className="logo" alt="" />:<img src="https://image.xiaomaiketang.com/xm/c4KiP2epBP.png" className="logo" alt="" />}
        </div>
        {menuType ? (
          <span
            className="icon iconfont cursor ml20  handLike"
            onClick={handleMenu}
          >
            &#xe83d;
          </span>
        ) : (
          <span
            className="icon iconfont cursor ml20  handLike"
            onClick={handleMenu}
          >
            &#xe615;
          </span>
        )}
        <div className="message-help">
          {list.length ? (
            <ClickOutside
              onClickOutside={() => {
                if (openDropdown) {
                  setOpenDropdown(false);
                }
              }}
              className="college-container"
            >
              <div>
                <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);
                      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="link">
                <span className="icon iconfont tool-tip-right">&#xe85d;</span>
                <div className="text">前往学院</div>
                <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="icon iconfont tool-tip-right">&#xe85e;</span>
                <div className="text">分享学院</div>
              </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;
