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

import { ReactComponent as Close2 } from 'assets/close2.svg'

import { getQueryString } from 'utils/getQueryString'
import { useMedia } from 'Context/Media/MediaContext'
import { useLogin2p } from 'Login2p/Login2pContext'
import MasonryContainer from 'Material/components/Masonry.component'
import { IItemType } from '../../Material/components/Item.component'
import AudioFix from 'Activity/components/AudioFix'
import { IBannerListRes, INewestList, ITagList, NewestService } from 'Newest/Newest.service'
import { IAudioDetail, IPermissionItem } from 'Activity/Activity.service'
import CustormSwiper from './CustomSwiper'
import ColumnInfoEdit from 'Column/components/ColumnInfoEdit'
import { IColumnInfo } from 'Column/Column.service'

import styles from '../css/NewestIndex.module.scss'

const pageSize = 20
/**
 * 首页
 */
const NewestLibrary: React.FC = props => {
  const media = useMedia()
  const login2p = useLogin2p()
  const history = useHistory()

  // const _pageSize = login2p.jwt ? pageSize : media.isMaxWrap ? 3 : 5
  const [data, setData] = useState<INewestList[]>([])
  const [hasMore, setHasMore] = useState<boolean>(true)
  const [page, setPage] = useState<number>(1) // 当前页
  const [audioVisible, setAudioVisible] = useState<boolean>(false)
  const [audioItem, setAudioItem] = useState<IAudioDetail>()
  const [actTagKeyword, setActTagKeyword] = useState<string>() // 活动标签/报告标签
  const [themeKeyword, setThemeKeyword] = useState<string>() // 主题标签
  const [columnCloseFlag, setColumnCloseFlag] = useState<boolean>(true) // 是否关闭专栏icon
  const [editInfoVisible, setEditInfoVisible] = useState<boolean>(false) // 修改专栏信息

  // const [tagCheckList, setTagCheckList] = useState<string[]>([]) // 记录标签归类List
  // const [permissionID, setPermissionID] = useState<number | undefined>(undefined) // 选中的行业
  let timer: NodeJS.Timeout | null = null
  useEffect(() => {
    setData([])
    setPage(1)
    // setPermissionID(undefined)
    setActTagKeyword(undefined)
    setThemeKeyword(undefined)
    // const pid = getQueryString('pid')
    // const ids = getQueryString('ids')
    // pid && setPermissionID(Number(pid))
    // ids && setActTagKeyword(ids.split(',').map(item => item))
    // !pid && !ids && setTagCheckList([])

    getNewestList({ PageSize: pageSize, CurrentIndex: 1, HashtagKeyword: themeKeyword, LabelKeyword: actTagKeyword })

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [history.location.search])

  // 拉取Banner
  const { loading: bannerLoading, data: bannerList } = useRequest(NewestService.getBannerList, {
    formatResult: response => response.data.Data
  })
  // 拉取标签
  const { data: tagData } = useRequest(NewestService.getCustomTagList, {
    formatResult: response => response.data.Data
  })

  // 拉取数据
  const { loading: dataLoading, run: getNewestList } = useRequest(NewestService.getNewestList, {
    manual: true,
    onSuccess: res => {
      res.data.Data?.List &&
        setData(login2p.jwt ? [...data, ...res.data.Data?.List] : res.data.Data?.List.slice(0, pageSize))
      setHasMore(res.data.Data ? !res.data.Data?.Paging?.IsEnd : false)
    }
  })

  // banner数据处理
  const handleRenderBanner = (data?: IBannerListRes) => {
    if (!data) return
    // 计算有几组数据
    let listCout = 0
    if (data.ListA.length > 0) listCout += 1
    if (data.ListB.length > 0) listCout += 1
    if (data?.ListC?.length > 0) listCout += 1
    // 一块都没有呢
    if (listCout === 0) return
    // 3块都有呢，为T3模式
    let _ListA = data.ListA
    let _ListB = data.ListB
    let _ListC = data?.ListC
    // 2块呢，为T2模式
    if (listCout === 2) {
      _ListA = data.ListA.length > 0 ? data.ListA : data.ListB
      _ListB = data.ListA.length > 0 ? (data.ListB.length > 0 ? data.ListB : data?.ListC) : data?.ListC
      _ListC = []
    }
    if (listCout === 1) {
      _ListA = data.ListA.length > 0 ? data.ListA : data.ListB.length > 0 ? data.ListB : data?.ListC
      _ListB = []
      _ListC = []
    }
    return (
      <div className={styles['newest-top-banner']}>
        <div className={`newest-banner-box ${listCout === 1 ? 'banner-t1' : 'banner-t2'} `}>
          <CustormSwiper name="bannera" list={_ListA} boxSize={listCout === 1 ? 'block' : 'large'} />
        </div>
        {(_ListB.length > 0 || _ListC.length > 0) && (
          <div className="banner-right-t2">
            <div className={`newest-banner-box ${listCout === 2 ? '' : 'banner-right-t3 m-r-sm'}`}>
              <CustormSwiper name="bannerb" list={_ListB} boxSize={listCout === 2 ? 'middle' : 'small'} />
            </div>
            {_ListC.length > 0 && (
              <div className="newest-banner-box banner-right-t3 m-l-sm">
                <CustormSwiper name="bannerc" list={_ListC} boxSize="small" />
              </div>
            )}
          </div>
        )}
      </div>
    )
  }

  const handleLoadMoreData = () => {
    if (!login2p.jwt || dataLoading || !hasMore) return
    setPage(page + 1)
    getNewestList({
      PageSize: pageSize,
      CurrentIndex: page + 1,
      HashtagKeyword: themeKeyword,
      LabelKeyword: actTagKeyword
    })
  }
  const handleOnClick = (item: INewestList) => {
    if (!item) return
    // 视频播放
    if (item.Source === IItemType.Activityvideo) {
      const url = `${window.location.origin}/activity/video/${(item as INewestList).SourceId}`
      window.open(url)
      return
    }
    if (item.Source === IItemType.Roadshow) {
      const url = `${window.location.origin}/indepth/video/${item.Roadshow.ChartPermissionId}/${item.Roadshow.IndustrialManagementId}/${item.Roadshow?.Id}`
      window.open(url)
      return
    }

    // 音频播放
    if (item.Source === IItemType.Activityvoice && item.Activityvoice) {
      setAudioItem({
        ActivityId: item.SourceId,
        Name: item.Activityvoice.Title,
        Url: item.Activityvoice.ResourceUrl,
        Type: item.Activityvoice.Type
      })
      setAudioVisible(true)
      return
    }
    if (item.Source === IItemType.AskserieVideo && item.AskserieVideo) {
      setAudioItem({
        ActivityId: item.SourceId,
        Name: item.AskserieVideo.Title,
        Url: item.AskserieVideo.ResourceUrl,
        Type: item.AskserieVideo.Type
      })
      setAudioVisible(true)
      return
    }
  }
  const handleCloseAudio = () => {
    setAudioVisible(false)
  }
  // 标签样式
  const handleIncludeIds = (keyword: string, type?: 'activity' | 'theme') => {
    if (type === 'theme') {
      return themeKeyword === keyword
        ? 'newestindex-label-theme-item act-newestindex-theme-label'
        : 'newestindex-label-theme-item'
    }
    return actTagKeyword === keyword ? 'newestindex-label-item act-newestindex-label' : 'newestindex-label-item'
  }
  // 标签点击
  const handleClickTag = (tagItem: string, type: 'activity' | 'theme') => {
    const labelClick: {
      [key: string]: () => void
    } = {
      ['activity']: () => (tagItem === actTagKeyword ? setActTagKeyword(undefined) : setActTagKeyword(tagItem)),
      ['theme']: () => (tagItem === themeKeyword ? setThemeKeyword(undefined) : setThemeKeyword(tagItem))
    }
    labelClick[type]()

    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    timer = setTimeout(() => {
      timer = null
      setData([])
      setPage(1)
      getNewestList({
        PageSize: pageSize,
        CurrentIndex: 1,
        HashtagKeyword: type === 'theme' ? (tagItem === themeKeyword ? undefined : tagItem) : themeKeyword,
        LabelKeyword: type === 'activity' ? (tagItem === actTagKeyword ? undefined : tagItem) : actTagKeyword
      })
    })

    // history.replace(
    //   `${permissionID ? '?pid=' + permissionID : ''}${
    //     IDs.length > 0 ? (permissionID ? '&' : '?') + 'ids=' + IDs.toString() : ''
    //   }`
    // )
  }
  // const handleClickPermission = (permissionItem: IPermissionItem) => {
  //   setPermissionID(permissionID === permissionItem.ChartPermissionId ? undefined : permissionItem.ChartPermissionId)

  //   history.replace(
  //     `${permissionID !== permissionItem.ChartPermissionId ? '?pid=' + permissionItem.ChartPermissionId : ''}${
  //       actTagKeyword.length > 0
  //         ? (permissionID !== permissionItem.ChartPermissionId ? '&' : '?') + 'ids=' + actTagKeyword.toString()
  //         : ''
  //     }`
  //   )
  // }
  const handleDeleteIcon = (e: React.MouseEvent<SVGSVGElement, MouseEvent>) => {
    e.stopPropagation()
    setColumnCloseFlag(false)
  }
  const handleToColumn = () => {
    if (!login2p.userInfo?.IsImproveInformation) {
      setEditInfoVisible(true)
      return
    }
    history.push(
      `/column/view/${login2p.userInfo?.SpecialColumnId}${
        login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''
      }`
    )
  }
  const handleSaveEditEnd = () => {
    handleCloseEdit()
    history.push(
      `/column/view/${login2p.userInfo?.SpecialColumnId}${
        login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''
      }`
    )
  }
  const handleCloseEdit = () => {
    setEditInfoVisible(false)
  }

  return (
    <>
      {login2p.userInfo?.IsAuthor && columnCloseFlag ? (
        <div className={styles['fixed-column-wrapper']} onClick={handleToColumn}>
          <div className="fixed-column-text">我的专栏</div>
          <Close2 className="fixed-column-close" onClick={handleDeleteIcon} />
        </div>
      ) : null}
      {editInfoVisible ? (
        <ColumnInfoEdit
          visible={editInfoVisible}
          info={{ Id: login2p.userInfo?.SpecialColumnId } as IColumnInfo}
          onClose={handleCloseEdit}
          onRefresh={handleSaveEditEnd}
        />
      ) : null}
      <AudioFix audioDetail={audioItem as IAudioDetail} visible={audioVisible} onClose={handleCloseAudio} />
      {handleRenderBanner(bannerList)}
      {/* {tagData && tagData?.ListPermission?.length > 0 && (
        <div className={styles['newestindex-label-wrapper']}>
          {tagData?.ListPermission?.map((item: IPermissionItem) => (
            <div
              className={`newest-permission-item ${
                permissionID === item.ChartPermissionId ? 'newest-act-permission' : ''
              }`}
              key={item.ChartPermissionId}
              onClick={handleClickPermission.bind(this, item)}
            >
              {item.PermissionName}
            </div>
          ))}
        </div>
      )} */}
      {tagData && tagData?.List1?.length > 0 && (
        <div className="m-r-md g-inline-block">
          <div className={styles['newestindex-label-wrapper']}>
            {tagData?.List1?.map((item: string, index: number) => (
              <div className={handleIncludeIds(item)} key={index} onClick={handleClickTag.bind(this, item, 'activity')}>
                {item}
              </div>
            ))}
          </div>
        </div>
      )}
      {tagData && tagData?.List2?.length > 0 && (
        <div className="g-inline-block">
          <div className={styles['newestindex-label-wrapper']}>
            {tagData?.List2?.map((item: string, index: number) => (
              <div className={handleIncludeIds(item)} key={index} onClick={handleClickTag.bind(this, item, 'activity')}>
                {item}
              </div>
            ))}
          </div>
        </div>
      )}
      {tagData && tagData?.List3?.length > 0 && (
        <div className={styles['newestindex-label-wrapper']}>
          {tagData?.List3?.map((item: string, index: number) => (
            <div
              className={handleIncludeIds(item, 'theme')}
              key={index}
              onClick={handleClickTag.bind(this, item, 'theme')}
            >
              {item}
            </div>
          ))}
        </div>
      )}
      <div>
        <MasonryContainer
          loadMore={handleLoadMoreData}
          hasMore={hasMore}
          loading={dataLoading || bannerLoading}
          dataSource={data || []}
          itemType={IItemType.NormalChart}
          onItemClick={handleOnClick}
        />
      </div>
    </>
  )
}

export default NewestLibrary
