import React, { useEffect, useState } from 'react'
import { Link, useHistory, useLocation } from 'react-router-dom'
import useRequest from '@ahooksjs/use-request'

import { Avatar, Button, Col, Row, message } from 'antd'
import QrcodeIcon from 'assets/qrcode-icon.svg'
import AppletImg from 'assets/applet.png'
import OfficialImg from 'assets/official.png'
import VipDay from 'assets/vipday.png'
import VipMonth from 'assets/vipmonth.png'
// import LogoImg from 'assets/logo.png'
import MySetPassword from 'SetPassword/mySet.password'
import ModifyPassword from 'SetPassword/modify.password'

import { useLogin2p } from './Login2p/Login2pContext'
import { useMedia } from 'Context/Media/MediaContext'
import ApplyPermission from 'Material/components/ApplyPermission'
import HeadSearch from 'Search/components/HeadSearch'
import { INewPermissionType, ITryType } from 'Material/components/NoPermission'
import { MaterialService } from 'Material/Material.service'
import styles from './styles/NewPage.module.scss'

// 凡是vmp.tsx中Route的key={'new'}，都来一套
const urlList = [
  { path: '/column', key: 'community' },
  { path: '/community', key: 'community' },
  { path: '/activity', key: 'activity' },
  { path: '/indepth', key: 'indepth' },
  { path: '/material', key: 'material' },
  { path: '/my', key: 'newest' },
  { path: '/search', key: 'newest' },
  { path: '/', key: 'newest' }
]

const NewPage: React.FC = props => {
  const location = useLocation()
  const history = useHistory()
  const media = useMedia()
  // const personalized = usePersonalized()
  const login2p = useLogin2p()
  const [activityKey, setActivityKey] = useState<string>('newest')
  const [hoverKey, setHoverKey] = useState<string>('newest')
  const [searchWord, setSearchWord] = useState<string>()
  const [visibleApply, setVisibleApply] = useState(false)
  const [visiblePassword, setVisiblePassword] = useState(false)
  const [visibleModifyPassword, setVisibleModifyPassword] = useState(false)
  const [isShowMenu, setIsShowMenu] = useState<boolean>(false)
  const [isShowMobileMenu, setIsShowMobileMenu] = useState<boolean>(false) // 识别报告详情页+活动详情页，适配移动菜单

  const handleToMy = () => {
    history.push(`/my${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
  }
  // const headMenu = [
  //   { key: 'newest', path: '/', label: '最新' },
  //   { key: 'material', path: '/material', label: '素材库' },
  //   { key: 'indepth', path: '/indepth', label: '深度研究' },
  //   { key: 'activity', path: '/activity', label: '活动' },
  //   { key: 'community', path: '/community', label: '研选社区' }
  // ]
  const { run: applyTry } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Success
        ? message.success('已提交给您的对口销售，请耐心等待。')
        : message.info(res.data.Msg || res.data.ErrMsg)
    }
  })

  useEffect(() => {
    handleChangeMenuKey(location)
    history.listen(location => {
      window.scrollTo(0, 0)
      handleChangeMenuKey(location)
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleChangeMenuKey = (location: any) => {
    if (location.pathname.includes('/search')) {
      const searchArr = location.pathname.split('/')
      setSearchWord(searchArr[2])
    } else {
      setSearchWord(undefined)
    }
    const findKey = urlList.find(item => location.pathname.includes(item.path))?.key
    setActivityKey(findKey ? findKey : 'newest')
    setHoverKey(findKey ? findKey : 'newest')
    // 识别报告详情页+活动详情页，适配移动菜单
    if (media.isSmallMax) {
      const routhStr = [
        '/material/info',
        '/activity/info',
        '/activity/detail',
        '/internal/article',
        '/column/detail',
        '/activity/medium/detail'
      ]
      let flag = false
      routhStr.forEach(item => {
        if (location.pathname.includes(item)) {
          setIsShowMobileMenu(true)
          flag = true
        }
      })
      if (!flag) {
        setIsShowMobileMenu(false)
      }
    } else {
      setIsShowMobileMenu(false)
    }
  }

  // const handleClickMenu = (item: { key: string; path: string; label: string }) => {
  //   setActivityKey(item.key)
  //   setHoverKey(item.key)
  //   setSearchWord(undefined)
  //   history.push(item.path)
  // }
  // const handleMenuOver = (key: string) => {
  //   setHoverKey(key)
  // }
  /** 搜索框的事件 */
  const handleToDoSearch = (value: string) => {
    setSearchWord(value)
    history.push(`/search/${value}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
  }
  const handleMobileLogout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('smtoken')
    window.location.reload()
  }
  // 提交申请权限
  const handleToApplyPower = () => {
    if (!login2p.jwt) return
    // HasPermission=2,4,6，已提交过申请的，提示：您已提交过申请，请等待销售与您联系。
    if (
      login2p.userInfo?.HasPermission === INewPermissionType.HasApplyQY ||
      login2p.userInfo?.HasPermission === INewPermissionType.HasApplyFICC ||
      login2p.userInfo?.HasPermission === INewPermissionType.HasApplyPotential
    ) {
      message.info('您已提交过申请，请等待销售与您联系。')
      return
    }
    // HasPermission=3，5，不弹表单，直接提交申请
    if (
      login2p.userInfo?.HasPermission === INewPermissionType.NoApplyQY ||
      login2p.userInfo?.HasPermission === INewPermissionType.NoApplyFICC
    ) {
      applyTry({ ApplyMethod: 1 })
      return
    }
    // HasPermission=7，弹表单填写，提交申请
    setVisibleApply(true)
  }

  const handleOKApply = () => {
    setVisibleApply(false)
  }

  // 设置修改密码
  const handlePassword = () => {
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    login2p.userInfo?.IsSetPassword ? setVisibleModifyPassword(true) : setVisiblePassword(true)
  }
  return (
    <div className={styles['newpage-header']} style={{ minWidth: isShowMobileMenu ? 'auto' : '1024px' }}>
      {isShowMobileMenu ? (
        <div className={styles['newpage-mobile-header']}>
          <div className="newpage-mobile-menu-wrapper">
            <Link to="/" className={styles['logo-wrapper']}>
              <img
                src="https://hzstatic.hzinsights.com/cygx_web/ico/logo_inedx.png"
                className={styles.headerLogo}
                alt="logo"
              />
            </Link>
            {login2p.jwt ? (
              <img
                src={login2p.userInfo?.Headimgurl}
                alt="头像"
                className="mobile-menu-person-img"
                onClick={() => setIsShowMenu(!isShowMenu)}
              />
            ) : (
              <Link to={`/login2p?next=${encodeURIComponent(location.pathname + location.search)}`}>
                <Button type="primary" className="mobile-login2p-btn">
                  登录
                </Button>
              </Link>
            )}

            {/* <MenuOutlined className="mobile-menu-icon" onClick={() => setIsShowMenu(!isShowMenu)} /> */}
          </div>
          {isShowMenu ? (
            <div className="newpage-mobile-menu-list">
              {/* <div className="mobile-search">
              <HeadSearch onSearch={handleToDoSearch} defaultKeyword={searchWord} className="mobile-search-reset" />
            </div>
            {login2p.jwt ? (
              <>
                <div className="mobile-center-wrapper" onClick={() => setIsOpen(!isOpen)}>
                  <div>
                    <img
                      src={login2p.userInfo?.Headimgurl || auth.userInfo?.avatar}
                      alt="头像"
                      className="mobile-person-img"
                    />
                    <div className="mobile-person-name"> {login2p.userInfo?.UserName || auth.userInfo?.name}</div>
                  </div>
                  {isOpen ? <UpOutlined /> : <DownOutlined />}
                </div>
                {isOpen ? (
                  <div className="mobile-person-content">
                    <div className="mobile-person-phone">{login2p.userInfo?.Mobile || auth.userInfo?.phone_number}</div>
                    <div className="mobile-person-company">{login2p.userInfo?.CompanyName || '弘则研究'}</div>
                    <div className="mobile-person-power">
                      {login2p.userInfo?.PermissionName?.map((item, index) => (
                        <div className={item ? 'mobile-person-power-one' : ''} key={index}>
                          {item}
                        </div>
                      ))}
                    </div>
                  </div>
                ) : null}
              </>
            ) : null}
            {headMenu.map(item => (
              <div
                className={`mobile-header-item ${activityKey === item.key ? 'mobile-header-act' : ''} `}
                key={item.key}
                onClick={handleClickMenu.bind(this, item)}
                onMouseOver={handleMenuOver.bind(this, item.key)}
              >
                {item.label}
              </div>
            ))}
            <div className="mobile-header-item" onClick={handleToMy}>
              个人中心
            </div> */}
              {login2p.jwt ? (
                <div className="mobile-header-item g-flex g-flex-between">
                  <div>{login2p.userInfo?.Mobile}</div>
                  <div onClick={handleMobileLogout}>退出</div>
                </div>
              ) : null}
              {/* (
              <div className="mobile-header-item" onClick={login2p.logout}>
                <Link to={`/login2p?next=${location.pathname+ location.search}`}>
                  <Button type="primary" className="mobile-login2p-btn">
                    登录
                  </Button>
                </Link>
              </div>
            ) */}
            </div>
          ) : null}
        </div>
      ) : (
        <Row wrap={false} justify="space-around" align="middle">
          <Col className={styles['reset-padding']}>
            <Link
              to={`/${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`}
              className={styles['logo-wrapper']}
            >
              <img
                src="https://hzstatic.hzinsights.com/cygx_web/ico/logo_inedx.png"
                className={styles.headerLogo}
                alt="logo"
              />
              {/* <span className={styles['header-text']}>查研观向</span> */}
            </Link>
          </Col>
          <Col className={styles['reset-padding']}>
            {/* <div className={styles['header-menu-wrapper']} onMouseLeave={() => setHoverKey(activityKey)}>
            {headMenu.map(item => (
              <div
                className={`${styles['header-item']} ${activityKey === item.key ? styles['header-act'] : ''} ${
                  hoverKey === item.key ? styles['header-underline'] : ''
                }`}
                key={item.key}
                onClick={handleClickMenu.bind(this, item)}
                onMouseOver={handleMenuOver.bind(this, item.key)}
              >
                {item.label}
              </div>
            ))}
          </div> */}
          </Col>
          <Col flex="auto" className={`${styles['reset-padding']} ${styles['search-header']}`}>
            {/* <SearchOutlined className={styles.fz19} onClick={handleOpenSearch} /> */}
            <HeadSearch
              onSearch={handleToDoSearch}
              defaultKeyword={searchWord}
              placeholder="搜索"
              className={styles['search-header-max']}
            />
          </Col>
          <Col className={styles['reset-padding']}>
            <div className={styles['qrcode-wrapper']}>
              <img src={QrcodeIcon} alt="图片" className="qrcode-img" />
              <div className="qrcode-box">
                <div className="qrcode-smbox">
                  <img src={AppletImg} alt="二维码" className="qrcode-code" />
                  <div className="g-ta-ct">
                    手机扫码
                    <br />
                    体验微信小程序功能
                  </div>
                </div>
                <div className="qrcode-smbox">
                  <img src={OfficialImg} alt="二维码" className="qrcode-code" />
                  <div className="g-ta-ct">关注【买方研选】公众号 及时获取报告和活动通知</div>
                </div>
              </div>
            </div>
          </Col>
          <Col className={styles['reset-padding']}>
            {login2p.jwt ? (
              <div className={styles['center-wrapper']}>
                <Avatar src={login2p.userInfo?.Headimgurl} shape={'circle'} className="header-avatar" />
                <div className="person-center-wrapper">
                  <div className="person-wrapper">
                    <img src={login2p.userInfo?.Headimgurl} alt="头像" className="person-img" />
                    <div className="person-content">
                      <div className="person-name"> {login2p.userInfo?.UserName || '--'}</div>
                      <div className="person-phone">{login2p.userInfo?.Mobile}</div>
                      <div className="person-company">{login2p.userInfo?.CompanyName || '--'}</div>
                    </div>
                  </div>
                  <div className="person-power-wraper">
                    {login2p.userInfo?.HasPermission === INewPermissionType.OK ? (
                      <div className="person-haspower">
                        {login2p.userInfo?.PermissionStatus && (
                          <div className="person-haspower-label">{login2p.userInfo?.PermissionStatus}</div>
                        )}

                        <div className="person-haspower-text">
                          {login2p.userInfo?.StartDate && login2p.userInfo?.EndDate && (
                            <div>
                              {login2p.userInfo?.StartDate}~{login2p.userInfo?.EndDate}
                            </div>
                          )}
                          {login2p.userInfo?.PermissionStatus.includes('试用') ? null : (
                            <div>
                              剩余研选点数：
                              <span className="hightlight-text">{login2p.userInfo?.CompanyPointsNum || 0}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    ) : (
                      <div className="person-nopower">
                        <span>暂无权限，可点击</span>
                        <div className="person-nopower-btn" onClick={handleToApplyPower}>
                          申请
                        </div>
                      </div>
                    )}
                  </div>
                  {login2p.userInfo?.UserCardType !== 0 ? (
                    <div className="person-vip-card-wrapper">
                      {login2p.userInfo?.UserCardType === 1 ? (
                        <img src={VipDay} alt="vip" className="person-vip-card-img" />
                      ) : (
                        <img src={VipMonth} alt="vip" className="person-vip-card-img" />
                      )}
                      <span className="person-vip-timetext">有效期至{login2p.userInfo?.UserCardEndDate}</span>
                    </div>
                  ) : null}
                  {/* <div className="person-power">
                  {login2p.userInfo?.PermissionName?.map((item, index) => (
                    <div className={item ? 'person-power-one' : ''} key={index}>
                      {item}
                    </div>
                  ))}
                </div> */}
                  <div className="divide-line" />
                  <div className="person-line person-center-link" onClick={handleToMy}>
                    个人中心
                  </div>
                  {login2p.userInfo && login2p.userInfo.IsAuthor && (
                    <div className="person-line person-center-link" onClick={handlePassword}>
                      {login2p.userInfo?.IsSetPassword ? '修改登录密码' : '设置登录密码'}
                    </div>
                  )}
                  <div className="person-line person-exit" onClick={login2p.logout}>
                    退出
                  </div>
                </div>
              </div>
            ) : (
              <Link to={`/login2p?next=${encodeURIComponent(location.pathname + location.search)}`}>
                <Button type="primary" className={styles['login2p-btn']}>
                  登录
                </Button>
              </Link>
            )}
          </Col>
        </Row>
      )}
      <ApplyPermission visible={visibleApply} onCloseModel={handleOKApply} />
      <MySetPassword
        visible={visiblePassword}
        encryptionPhone={login2p.userInfo?.Mobile || ''}
        phoneAreaCode={login2p.userInfo?.OutboundCountryCode || ''}
        onCancelPassword={() => {
          setVisiblePassword(false)
        }}
      />
      <ModifyPassword
        visible={visibleModifyPassword}
        onCancelPassword={() => {
          setVisibleModifyPassword(false)
        }}
      />
    </div>
  )
}

export default NewPage
