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

import ImgCrop from 'antd-img-crop'
import { Empty, Spin, Tooltip, Upload, message } from 'antd'
import { RightOutlined } from '@ant-design/icons'
import { UploadChangeParam } from 'antd/es/upload'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'

import { ReactComponent as ColumnNew } from 'assets/columnnew.svg'
import { ReactComponent as ColumnCenterSvg } from 'assets/columncenter.svg'
import { ReactComponent as ColumnMessageSvg } from 'assets/columnmessage.svg'
import { ReactComponent as ReseachSvg } from 'assets/reseachactivity.svg'
import { ReactComponent as PhotoSvg } from 'assets/photo.svg'
import EmptyImg from 'assets/empty.png'

import { useLogin2p } from 'Login2p/Login2pContext'
import { ColumnService, IColumnAuthorList, IColumnDetail, IColumnInfo } from './Column.service'
import { MaterialService } from 'Material/Material.service'
import ColumnContent from './components/ColumnContent'
import ColumnInfoEdit from './components/ColumnInfoEdit'
import ColumnCenter from './components/ColumnCenter'
import ColumnMessage from './components/ColumnMessage'
import LikesCollections from './components/LikesCollections'
import ColumnFansModal from './components/ColumnFansModal'
import styles from './css/ColumnIndex.module.scss'

interface IColumnIndexProps {
  columnId: number // 专栏ID
}
const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!')
  }
  // const isLt2M = file.size / 1024 / 1024 < 2
  // if (!isLt2M) {
  //   message.error('Image must smaller than 2MB!')
  // }
  return isJpgOrPng
}
/**研选专栏 */
const ColumnIndex: React.FC<IColumnIndexProps> = props => {
  const login2p = useLogin2p()
  const history = useHistory()
  const location = useLocation()
  const pageSize = 20
  const [editInfoVisible, setEditInfoVisible] = useState<boolean>(false) // 修改专栏信息
  const [openCenter, setOpenCenter] = useState<boolean>(false) // 打开内容中心
  const [openMessage, setOpenMessage] = useState<boolean>(false) // 打开留言管理
  const [actColumnAuthorID, setActColumnAuthorID] = useState<number | undefined>(undefined) // 当前选中的专栏ID
  const [columnAuthorListHasMore, setColumnAuthorListHasMore] = useState<boolean>(true) // 专栏作者列表的加载更多
  const [columnAuthorListCurrentPage, setColumnAuthorListCurrentPage] = useState<number>(1) // 专栏作者列表的当前页码
  const [columnAuthorList, setColumnAuthorList] = useState<IColumnAuthorList[]>([]) // 专栏作者列表

  const [columnListHasMore, setColumnListHasMore] = useState<boolean>(true) // 专栏文章列表的加载更多
  const [columnListCurrentPage, setColumnListCurrentPage] = useState<number>(1) // 专栏文章列表的当前页码
  const [columnList, setColumnList] = useState<IColumnDetail[]>([]) // 专栏文章列表

  const [collectionsShow, setCollectionsShow] = useState<boolean>(false) // 获赞与收藏的开关
  const [fansModalShow, setFansModalShow] = useState<boolean>(false) // 粉丝开关

  useEffect(() => {
    getColumnAuthorList(pageSize, 1)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  useEffect(() => {
    setColumnList([])
    setColumnListCurrentPage(1)
    setColumnListHasMore(true)
    setActColumnAuthorID(props.columnId)
    getColumnList(pageSize, 1, props.columnId ? props.columnId : undefined)
    props.columnId && getAuthorDetail(props.columnId)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.columnId])

  // 研选专栏列表
  const {
    data: columnAuthor,
    loading: columnAuthorListLoading,
    run: getColumnAuthorList
  } = useRequest(ColumnService.getColumnAuthorList, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      setColumnAuthorList([...columnAuthorList, ...(res?.List || [])])
      setColumnAuthorListHasMore(res ? !res?.Paging?.IsEnd : false)
    }
  })
  // 专栏笔记列表
  const { loading: columnListLoading, run: getColumnList } = useRequest(ColumnService.geColumnList, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      setColumnList([...columnList, ...(res?.List || [])])
      setColumnListHasMore(res ? !res?.Paging?.IsEnd : false)
    }
  })
  // 专栏作者详情
  const {
    data: columnInfo,
    run: getAuthorDetail,
    refresh: columnDetailRefresh
  } = useRequest(ColumnService.getAuthorDetail, {
    manual: true,
    formatResult: response => response.data.Data
  })
  // 专栏添加关注
  const { run: postColumnFollow } = useRequest(ColumnService.postColumnAuthorFollow, {
    manual: true,
    onSuccess: res => {
      res.data.Success && columnDetailRefresh()
    }
  })
  // 专栏头像更换
  const { run: postUpdateAuthorHeadImg } = useRequest(ColumnService.postUpdateAuthorHeadImg, {
    manual: true,
    onSuccess: res => {
      if (res.data.Success) {
        setColumnAuthorList([])
        setColumnAuthorListCurrentPage(1)
        setColumnAuthorListHasMore(true)
        columnDetailRefresh()
        getColumnAuthorList(pageSize, 1)
      }
    }
  })
  // 上传图片
  const { run: uploadImg } = useRequest(MaterialService.postUploadImage, {
    manual: true,
    onSuccess: res => {
      message.info(res.data.Msg)
      res.data.Success && postUpdateAuthorHeadImg(props.columnId, res.data?.Data?.ResourceUrl)
    }
  })
  // 滚动分页拉取专栏作者数据
  const handleGetMoreColumnAuthorListData = () => {
    if (columnAuthorListLoading || !columnAuthorListHasMore) return
    setColumnAuthorListCurrentPage(columnAuthorListCurrentPage + 1)
    getColumnAuthorList(pageSize, columnAuthorListCurrentPage + 1)
  }
  // 滚动分页拉取专栏文章数据
  const handleGetMoreColumnListData = () => {
    if (columnListLoading || !columnListHasMore) return
    setColumnListCurrentPage(columnListCurrentPage + 1)
    getColumnList(pageSize, columnListCurrentPage + 1, props.columnId ? props.columnId : undefined)
  }

  const onPreview = async (file: UploadFile) => {
    let src = file.url as string
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsDataURL(file.originFileObj as RcFile)
        reader.onload = () => resolve(reader.result as string)
      })
    }
    const image = new Image()
    image.src = src
    const imgWindow = window.open(src)
    imgWindow?.document.write(image.outerHTML)
  }

  const handleOpenModel = (type: 'editInfo' | 'openCenter' | 'openCreate' | 'openMessage') => {
    if (type !== 'editInfo' && !columnAuthor?.IsImproveInformation) {
      message.error('请先完善专栏信息')
      return
    }
    switch (type) {
      case 'editInfo':
        setEditInfoVisible(true)
        break
      case 'openCenter':
        setOpenCenter(true)
        break
      case 'openMessage':
        setOpenMessage(true)
        break
      case 'openCreate':
        window.open(`/column/editor/${props.columnId}`)
        break
      default:
        break
    }
  }

  const handleClose = (type: 'editInfo' | 'openCenter' | 'openMessage') => {
    switch (type) {
      case 'editInfo':
        setEditInfoVisible(false)
        break
      case 'openCenter':
        setOpenCenter(false)
        break
      case 'openMessage':
        setOpenMessage(false)
        break
      default:
        break
    }
  }
  const uploadButton = (
    <div className="hover-img">
      <PhotoSvg className="hover-img-center" />
    </div>
  )
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    className: `avatar-uploader ${styles['column-upload']}`,
    listType: 'picture-card',
    showUploadList: false,
    withCredentials: true,
    beforeUpload: beforeUpload,
    customRequest: option => {
      uploadImg(option.file)
    },
    onChange: (info: UploadChangeParam<UploadFile>) => {
      if (info.file.status === 'uploading') {
        return
      }
    },
    onPreview: onPreview
  }
  const handleSetActColumn = (item: IColumnAuthorList) => {
    if (item.Id === actColumnAuthorID) {
      setActColumnAuthorID(undefined)
      history.push(`/column${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
    } else {
      setActColumnAuthorID(item.Id)
      history.push(`/column/view/${item.Id}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
    }
  }
  const handleChangeCollection = (id: number) => {
    const newList = JSON.parse(JSON.stringify(columnList))
    const findIndex = newList.findIndex((item: IColumnDetail) => item.Id === id)
    if (findIndex !== -1) {
      newList[findIndex].IsCollect ? newList[findIndex].CollectNum-- : newList[findIndex].CollectNum++
      newList[findIndex].IsCollect = !newList[findIndex].IsCollect
      setColumnList(newList)
    }
  }
  const handleChangeLike = (id: number) => {
    const newList = JSON.parse(JSON.stringify(columnList))
    const findIndex = newList.findIndex((item: IColumnDetail) => item.Id === id)
    if (findIndex !== -1) {
      newList[findIndex].IsLikeCount ? newList[findIndex].LikeCount-- : newList[findIndex].LikeCount++
      newList[findIndex].IsLikeCount = !newList[findIndex].IsLikeCount
      setColumnList(newList)
    }
  }
  // 关注专栏
  const handleOnFollowColumn = () => {
    // 检查是否登录了，未登录进入登录页面
    if (!login2p.jwt) {
      history.push(`/login2p?next=${encodeURIComponent(location.pathname + location.search)}`)
      return
    }
    postColumnFollow(props.columnId, columnInfo?.IsFollow ? 2 : 1)
  }

  // 保存专栏编辑信息刷新
  const handleSaveEditInfo = () => {
    setColumnAuthorList([])
    setColumnAuthorListCurrentPage(1)
    setColumnAuthorListHasMore(true)
    columnDetailRefresh()
    getColumnAuthorList(pageSize, 1)
  }

  // 显示获赞和收藏弹框
  const showCollectionsFansModal = (type: string) => {
    if (props.columnId && columnInfo?.UserId === login2p.userInfo?.UserId && columnInfo?.Status === 1) {
      type === '粉丝' ? setFansModalShow(true) : setCollectionsShow(true)
    }
  }
  // 获赞和收藏弹框的关闭事件
  const CollectionFansClose = (type: string) => {
    console.log(type)
    type === 'Fans' ? setFansModalShow(false) : setCollectionsShow(false)
  }

  if (columnAuthor?.List?.length === 0)
    return (
      <div className={styles['column-empty-wrapper']}>
        <Empty image={EmptyImg} description={<span className={styles['gray-tips']}>暂无数据</span>} />
      </div>
    )
  return (
    <div className={`page-max-width ${styles['columnindex-page']} g-flex g-flex-v-top`}>
      <div className="columnindex-left-wrapper">
        <InfiniteScroll
          initialLoad={false}
          pageStart={0}
          loadMore={handleGetMoreColumnAuthorListData}
          hasMore={columnAuthorListHasMore}
          useWindow={false}
        >
          <div className="g-flex g-flex-v-center m-b">
            <ReseachSvg />
            <span className="columnindex-title">专栏作者</span>
          </div>
          <div className="columnindex-list-wrapper">
            {columnAuthor?.IsAuthor && !columnAuthor?.IsImproveInformation && (
              <div className="spec-list-item my-column-box g-flex g-flex-v-top">
                <img src={columnAuthor.HeadImg} alt="图片" className="spec-item-img m-r-sm" />
                <div className="g-flex-c1 g-flex g-flex-between">
                  <div className="com-fw-bold com-fz16">我的专栏</div>
                  <div
                    className={`com-cursor-p ${styles['gray-tips']}`}
                    onClick={handleOpenModel.bind(this, 'editInfo')}
                  >
                    待完善信息
                    <RightOutlined size={24} className="m-l-sm" />
                  </div>
                </div>
              </div>
            )}
            {columnAuthorList?.map((item: IColumnAuthorList, index: number) => (
              <div
                className={`spec-list-item com-cursor-p ${
                  actColumnAuthorID === item.Id ? 'spec-list-active-item' : ''
                } ${item.UserId === login2p.userInfo?.UserId ? 'my-column-box' : ''}`}
                key={item.Id}
                onClick={handleSetActColumn.bind(this, item)}
              >
                <div className="g-flex g-flex-v-center m-b-md">
                  <img src={item.HeadImg} alt="图片" className="spec-item-img m-r-sm" />
                  <div className="g-flex-c1">
                    <div className="com-fz16 com-fw-bold m-b-sm spec-item-lh20">{item.SpecialName}</div>
                    <div className="spec-item-author-time g-flex g-flex-wap g-flex-v-center g-flex-between">
                      <span className="g-flex-c1">{item.NickName}</span>
                      <span className="g-ta-rt">{item.LatestPublishDate}</span>
                    </div>
                  </div>
                </div>
                <div className="spec-item-content">专栏介绍：{item.Introduction}</div>
              </div>
            ))}
          </div>
        </InfiniteScroll>
      </div>
      <div className="columnindex-middle-wrapper">
        {!!props.columnId && columnInfo && (
          <div
            className="columnindex-author-wrapper g-flex g-flex-v-center m-b-sm"
            style={{ background: `url(${columnInfo?.BgImgPc}) no-repeat center/cover` }}
          >
            <div className="columnindex-author-img-wrapper">
              {columnInfo?.UserId === login2p.userInfo?.UserId ? (
                <>
                  <ImgCrop modalTitle="编辑头像" modalWidth={387}>
                    <Upload {...uploadProps} style={{ borderRadius: 'none !important' }}>
                      <img src={columnInfo?.HeadImg} alt="" className="columnindex-author-img com-cursor-p" />
                      {uploadButton}
                    </Upload>
                  </ImgCrop>
                  {columnInfo.Status === 1 && (
                    <div
                      className="columnindex-author-btn com-cursor-p"
                      onClick={handleOpenModel.bind(this, 'editInfo')}
                    >
                      编辑专栏
                    </div>
                  )}
                </>
              ) : (
                <>
                  <img src={columnInfo?.HeadImg} alt="" className="columnindex-author-img" />
                  <div className="columnindex-author-btn com-cursor-p" onClick={handleOnFollowColumn}>
                    {columnInfo?.IsFollow ? `已关注` : '+ 关注专栏'}
                  </div>
                </>
              )}
            </div>
            <div className="columnindex-author-right g-flex-c1">
              <div className="columnindex-author-line g-flex g-flex-v-center g-flex-between g-flex-wap">
                <div className="columnindex-author-name-wrapper m-b ">
                  <div className="column-name">{columnInfo?.SpecialName}</div>
                  <div className="com-fz16">{columnInfo?.NickName}</div>
                </div>
                <div className="columnindex-count-wrapper g-flex g-flex-v-center m-b ">
                  <div className="columnindex-count-item">
                    <div className="columnindex-count">{columnInfo?.SpecialArticleNum || 0}</div>
                    <div className="columnindex-count-title">文章</div>
                  </div>
                  <div
                    className="columnindex-count-item"
                    onClick={() => {
                      showCollectionsFansModal('收藏')
                    }}
                  >
                    <div className="columnindex-count">{columnInfo?.CollectNum || 0}</div>
                    <div className="columnindex-count-title">获赞与收藏</div>
                  </div>
                  <div
                    className="columnindex-count-item"
                    onClick={() => {
                      showCollectionsFansModal('粉丝')
                    }}
                  >
                    <div className="columnindex-count">{columnInfo?.FollowNum || 0}</div>
                    <div className="columnindex-count-title">粉丝</div>
                  </div>
                </div>
              </div>
              <div className="columnindex-label-line g-flex g-flex-v-center g-flex-wap">
                {columnInfo?.Label.split(',').map((item, index) => (
                  <span className="columnindex-label" key={index}>
                    {item}
                  </span>
                ))}
              </div>
              <Tooltip title={columnInfo?.Introduction} overlayInnerStyle={{ width: '400px' }} placement="topLeft">
                <div className="columnindex-introduce g-ellipsis">{columnInfo?.Introduction}</div>
              </Tooltip>
            </div>
          </div>
        )}
        <div className="columnindex-middle-content">
          {!columnListLoading && (columnList?.length || 0) === 0 ? (
            <div className={styles['column-empty-wrapper']}>
              <Empty
                image={EmptyImg}
                description={
                  <span className={styles['gray-tips']}>
                    {columnInfo?.UserId === login2p.userInfo?.UserId
                      ? '还没有发布过内容，快去发布新内容吧'
                      : '该专栏下还没有任何内容哦'}
                  </span>
                }
              />
            </div>
          ) : (
            <InfiniteScroll
              initialLoad={false}
              pageStart={0}
              loadMore={handleGetMoreColumnListData}
              hasMore={columnListHasMore}
              useWindow
            >
              <div className="columnindex-right-title">专栏文章</div>
              <Spin spinning={columnListLoading}>
                <div className="columnindex-note-list-wrapper">
                  {columnList?.map((item: IColumnDetail, index) => (
                    <div className="note-item" key={index}>
                      <ColumnContent
                        detail={item}
                        type="list"
                        onCollect={handleChangeCollection}
                        onLike={handleChangeLike}
                      />
                    </div>
                  ))}
                </div>
              </Spin>
            </InfiniteScroll>
          )}
        </div>
      </div>
      {props.columnId && columnInfo?.UserId === login2p.userInfo?.UserId && columnInfo?.Status === 1 ? (
        <div className="columnindex-right-wrapper">
          <div className="columnindex-right-title">创作中心</div>
          <ColumnNew
            className="columnindex-right-svg columnindex-svg-new"
            onClick={handleOpenModel.bind(this, 'openCreate')}
          />
          <div className="columnindex-right-text">发布新内容</div>
          <ColumnCenterSvg
            className="columnindex-right-svg columnindex-svg-center"
            onClick={handleOpenModel.bind(this, 'openCenter')}
          />
          <div className="columnindex-right-text">内容中心</div>
          <ColumnMessageSvg
            className="columnindex-right-svg columnindex-svg-center"
            onClick={handleOpenModel.bind(this, 'openMessage')}
          />
          <div className="columnindex-right-text">留言管理</div>
        </div>
      ) : null}
      {editInfoVisible ? (
        <ColumnInfoEdit
          visible={editInfoVisible}
          info={
            !columnAuthor?.IsImproveInformation
              ? ({ Id: columnAuthor?.SpecialColumnId } as IColumnInfo)
              : columnInfo
              ? columnInfo
              : ({ Id: columnAuthor?.SpecialColumnId } as IColumnInfo)
          }
          onClose={handleClose.bind(this, 'editInfo')}
          onRefresh={handleSaveEditInfo}
        />
      ) : null}
      {openCenter ? <ColumnCenter open={openCenter} onClose={handleClose} /> : null}
      {openMessage ? <ColumnMessage open={openMessage} onClose={handleClose} /> : null}
      <LikesCollections open={collectionsShow} columnInfoFrom={columnInfo} onClose={CollectionFansClose} />
      <ColumnFansModal open={fansModalShow} onClose={CollectionFansClose} />
    </div>
  )
}

export default ColumnIndex
