/*
 * @Author: 吴文洁
 * @Date: 2019-09-10 18:26:03
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-09 19:05:49
 * @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 [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();

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

  useEffect(() => {
    storeUserId && getUserInfo();
  }, [storeUserId]);
  
  function getUserInfo() {
    const param = {
      storeUserId: User.getStoreUserId(),
    };
    BaseService.getStoreUser(param).then((res) => {
      const { nickName, phone, roleCodes, weChatAccount } = res.result;
      setNickName(nickName);
      setPhone(phone);
    });
  }

  function userMenu() {
    return (
      <div className="user-center-dropdown">
        <div className="user-detail">
          <div className="name">{nickName}</div>
          <div className="box">
            <span className="phone">{phone}</span>
            <span className="setting" onClick={() => toPersonalInfoPage()}>个人设置
              <span className="iconfont icon">&#xe79b;</span>
            </span>
          </div>
        </div>
        <div className="menu">
          <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">&#xe84e;</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();
      window.RCHistory.push({
        pathname: `/login`,
      });
    });
  }

  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={
                  ctx.xmState &&
                  ctx.xmState.storeList &&
                  ctx.xmState.storeList[0].avatar
                    ? ctx.xmState.storeList[0].avatar
                    : baseImg
                }
              />
              {ctx.xmState && ctx.xmState.storeList && (
                <span className="name">
                  {ctx.xmState.storeList[0].nickName}
                </span>
              )}
            </div>
          </Dropdown>
        </div>
      </div>
    </div>
  );
}
export default Header;
