/*
 * @Author: 吴文洁
 * @Date: 2019-09-10 18:26:03
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-04-14 19:29:09
 * @Description:
 */
import React, { useContext, useEffect, useState } from "react";
import "./Header.less";
import { Menu, Dropdown, Modal, Tooltip, message } from "antd";
import { LIVE_SHARE } from "@/domains/course-domain/constants";
import User from "@/common/js/user";
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';

const baseImg = "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png";
const { confirm } = Modal;

function Header(props) {
  const { menuType, handleMenuType } = props;
  const [storeName, setStoreName] = useState(User.getStoreName())
  const [avatar, setAvatar] = useState('');
  const [nickName, setNickName] = useState('');
  const [phone, setPhone] = useState('');
  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();

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

  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 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/4swGidkYR6.png' className="logo" alt="" />:<img src={logoImg} 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">
          <div className="store-related">
            <div className="store-name">{storeName}</div>
            <div className="line"></div>
            <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>
          </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>
  );
}
export default Header;
