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

import { Row, Col, List, Spin, message } from 'antd'
import { default as PeopleSvg } from 'assets/people.svg'

import { CommunityService, IListIndustrialList } from './Community.service'
import SmallComponent from 'Indepth/components/Small.component'
import ArticleCard from 'Indepth/components/ArticleCard'
import { useLogin2p } from 'Login2p/Login2pContext'
import styles from './css/AuthorInfo.module.scss'

type IAuthorInfoProps = {
  authorID: number // 作者ID
}
/**作者详情页*/
const AuthorInfo: React.FC<IAuthorInfoProps> = props => {
  const { authorID } = props
  const history = useHistory()
  const login2p = useLogin2p()

  const [actAuthorID, setActAuthorID] = useState<number>() // 选中的作者ID
  const [actSmTab, setActSmTab] = useState<number>(2)
  const smTab = [
    { key: 2, label: '更新时间' },
    { key: 1, label: '关注度' }
  ]

  useEffect(() => {
    if (authorID) {
      setActAuthorID(authorID)
      getKOLList(9999, 1, actSmTab)
      getAuthorDetail(authorID)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authorID])

  // 作者列表
  const {
    data: authorList,
    run: getKOLList,
    refresh: refreshAuthor
  } = useRequest(CommunityService.getKOLList, {
    manual: true,
    formatResult: response => response.data.Data.List
  })

  // 拉取作者详情
  const {
    data: dataInfo,
    loading: detailloading,
    run: getAuthorDetail,
    refresh
  } = useRequest(CommunityService.getAuthorDetail, {
    manual: true,
    formatResult: response => response.data.Data
  })

  // 作者的关注与取消关注
  const { run: applyAuthorFllow } = useRequest(CommunityService.postFlowDepartment, {
    manual: true,
    onSuccess: res => {
      res.data.Success
        ? message.success(res.data.Data.Status === 1 ? '关注成功' : '取消关注')
        : message.error('操作失败')
      res.data.Success && refreshAuthor()
    }
  })
  // 关注与取消关注（作者）
  const handleApplyFllow = (ID: number) => {
    applyAuthorFllow(ID)
  }
  // 作者的点击
  const handleSelectAuthor = (ID: number) => {
    setActAuthorID(ID)
    history.push(`/community/author/${ID}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
    window.scrollTo(0, 0)
  }

  const handleChangeSmTab = (key: number) => {
    setActSmTab(key)
    getKOLList(9999, 1, key)
  }
  const handleToOther = (item: IListIndustrialList) => {
    history.push(
      `/community/theme/${item.IndustrialManagementId}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`
    )
  }

  return (
    <Spin spinning={detailloading}>
      <div className={`page-max-width m-t-md`}>
        <Row wrap={false}>
          <Col flex={'320px'} className={styles['author-left']}>
            <SmallComponent
              title={
                <div className="author-title">
                  <div className="author-title-content">
                    {smTab.map(item => (
                      <div
                        className={`smtab-item ${actSmTab === item.key ? 'act-smtab' : ''}`}
                        key={item.key}
                        onClick={handleChangeSmTab.bind(this, item.key)}
                      >
                        {item.label}
                      </div>
                    ))}
                  </div>
                </div>
              }
              list={authorList || []}
              activeCategrayID={actAuthorID}
              hasFocus={true}
              onFllow={handleApplyFllow}
              onSelect={handleSelectAuthor}
            />
          </Col>
          <Col flex={'auto'}>
            {actAuthorID && (
              <div className={styles['author-right-top']}>
                <div className="author-header">
                  <img src={dataInfo?.ImgUrl || PeopleSvg} alt="头像" className="author-header-img" />
                </div>
                <div className="author-cp">
                  <div className="author-name">
                    <span>{dataInfo?.NickName}</span>
                  </div>
                  <div className="author-count">
                    <span className="count-span">
                      <span className="blue-text">{dataInfo?.FllowNum}</span> 粉丝
                    </span>
                    <span className="count-span">
                      <span className="blue-text">{dataInfo?.ArticleNum}</span> 报告
                    </span>
                    <span className="count-span">
                      <span className="blue-text">{dataInfo?.CollectNum}</span> 获得收藏
                    </span>
                  </div>
                  <div className="author-link-wrapper">
                    {dataInfo?.ListIndustrial?.map((cItem, cIndex) => (
                      <div key={cIndex} className="author-link g-ellipsis" onClick={handleToOther.bind(this, cItem)}>
                        #&nbsp;{cItem.IndustryName}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
            <div className="i-article-list">
              <List
                dataSource={dataInfo?.List || []}
                renderItem={item => (
                  <ArticleCard
                    key={item.ArticleId}
                    articleItem={item}
                    className="i-article-white-bg m-b-md"
                    jumpType="theme"
                    onCollect={refresh}
                  />
                )}
              />
            </div>
          </Col>
        </Row>
      </div>
    </Spin>
  )
}

export default AuthorInfo
