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

import { List, Spin, message } from 'antd'

import { ReactComponent as CityImg } from 'assets/city.svg'
import { default as ResearchActivitySvg } from 'assets/reseachactivity.svg'
import { default as RecommendSvg } from 'assets/recommend.svg'
import { default as GoingSvg } from 'assets/going.svg'
import { default as WaitSvg } from 'assets/wait.svg'
import { default as EndSvg } from 'assets/end.svg'
import EmptyImg from 'assets/emptydata.png'

import { useMedia } from 'Context/Media/MediaContext'
import { ActivityService, IActivityTypeListItem } from 'Activity/Activity.service'
import { INewPermissionType } from 'Material/components/NoPermission'
import ActivityBtnComponent from 'Activity/components/ActivityBtn.component'
import { IStateStringType } from 'Activity/components/ActivityBtn.component'

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

/**研选活动 */
const ResearchActivity: React.FC = () => {
  const history = useHistory()
  const media = useMedia()

  const [currentPage, setCurrentPage] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [actTypeID, setActTypeID] = useState<number | undefined>(undefined) // 活动类型，公司调研电话会-3
  const [actState, setActState] = useState<IStateStringType | undefined>(undefined) // 活动进行状态

  // 研选活动列表
  const {
    data: actData,
    loading: activityListLoading,
    run: getResearchActivityList
  } = useRequest(ActivityService.getActivityTypeList, {
    manual: true,
    formatResult: response => response.data.Data
  })
  // 获取易懂链接
  const { run: getYidongUrl } = useRequest(ActivityService.getYidongActivityDetail, {
    manual: true,
    onSuccess: res => {
      res.data.Data?.YidongActivityUrl && window.open(res.data.Data?.YidongActivityUrl, '_blank')
    }
  })
  useEffect(() => {
    getResearchActivityList({ PageSize: pageSize, CurrentIndex: 1, IsResearch: true })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 跳转到详情页
  const handleToDetail = (item: IActivityTypeListItem) => {
    if (
      item?.AuthInfo?.HasPermission &&
      item?.AuthInfo?.HasPermission !== INewPermissionType.OK &&
      (item?.YidongActivityUrl || (item as IActivityTypeListItem)?.IsYidongActivity)
    ) {
      return message.error('您暂无权限参加此活动，若想参加可以申请开通对应的试用权限')
    }
    // 易懂同步过来的活动 直接跳转
    if ((item as IActivityTypeListItem)?.IsYidongActivity) {
      item.ActivityId && getYidongUrl(item.ActivityId)
      return
    }
    if (item?.YidongActivityUrl) {
      window.open(item.YidongActivityUrl)
      return
    }
    window.open(`${window.location.origin}/activity/detail/${(item as IActivityTypeListItem).ActivityId}`)
  }
  // 筛选进行中/已结束
  const handleSelectState = (state: IStateStringType) => {
    setActState(state === actState ? undefined : state)
    getResearchActivityList({
      PageSize: pageSize,
      CurrentIndex: 1,
      IsResearch: true,
      ActiveState: state === actState ? undefined : state,
      ActivityTypeId: actTypeID
    })
  }
  // 筛选公司调研电话会
  const handleSelectType = (type: number) => {
    setActTypeID(actTypeID ? undefined : type)
    getResearchActivityList({
      PageSize: pageSize,
      CurrentIndex: 1,
      IsResearch: true,
      ActiveState: actState,
      ActivityTypeId: actTypeID ? undefined : type
    })
  }
  const handleGetActivityData = (page: number, pageSize: number) => {
    setCurrentPage(page)
    setPageSize(pageSize)
    getResearchActivityList({
      PageSize: pageSize,
      CurrentIndex: page,
      IsResearch: true,
      ActiveState: actState,
      ActivityTypeId: actTypeID
    })
    window.scrollTo(0, 0)
  }
  const stateString = [
    { state: IStateStringType.Waitting, name: '未开始', className: 'waitting-label', icon: WaitSvg },
    { state: IStateStringType.Going, name: '进行中', className: 'going-label', icon: GoingSvg },
    { state: IStateStringType.End, name: '已结束', className: 'end-label', icon: EndSvg }
  ]
  const formatState = (state: string, type: 'name' | 'className' | 'icon') => {
    const findItem = stateString.find(item => item.state === state)
    return findItem ? findItem[type] : ''
  }
  return (
    <div className={styles['research-activity-wrapper']}>
      <div className="research-title-box">
        <div className="research-title">
          <img src={ResearchActivitySvg} alt="icon" className="research-act-icon" />
          <strong>研选活动</strong>
        </div>
        <div className="research-select">
          <div
            className={`research-select-item ${actState === IStateStringType.Going ? 'research-select-active' : ''}`}
            onClick={handleSelectState.bind(this, IStateStringType.Going)}
          >
            进行中
          </div>
          <div
            className={`research-select-item ${actState === IStateStringType.End ? 'research-select-active' : ''}`}
            onClick={handleSelectState.bind(this, IStateStringType.End)}
          >
            已结束
          </div>
          <div
            className={`research-select-item ${actTypeID === 3 ? 'research-select-active' : ''}`}
            onClick={handleSelectType.bind(this, 3)}
          >
            公司调研电话会
          </div>
        </div>
      </div>
      <Spin spinning={activityListLoading}>
        {!activityListLoading && actData?.List?.length === 0 ? (
          <div className={styles['list-empty']}>
            <img src={EmptyImg} alt="没有数据" className="empty-img" />
            <span className="list-empty-text">暂无对应活动</span>
          </div>
        ) : (
          <List
            dataSource={actData?.List || []}
            renderItem={item => (
              <div
                className={`research-act-item ${item.ActivityType === 1 ? 'act-online-item' : 'act-underline-item'}`}
                onClick={handleToDetail.bind(this, item)}
              >
                <div className={`act-status-wrapper ${formatState(item.ActiveState, 'className')}`}>
                  <img src={formatState(item.ActiveState, 'icon')} alt="icon" className="act-status-icon" />
                  {formatState(item.ActiveState, 'name')}
                </div>
                <div className="research-act-oneline">
                  <div className="research-act-state">{item.ActivityType === 1 ? '线上' : '线下'}</div>
                  <div className="research-act-label no-wrap">{item.ActivityTypeName}</div>
                  <div className="research-act-label no-wrap">{item.Label}</div>
                </div>
                <div className="research-act-title-line">
                  {item.TopTime > 0 && item.ActiveState === IStateStringType.Waitting && (
                    <img src={RecommendSvg} alt="icon" className="recommend-icon" />
                  )}
                  {item.IsResearchPoints ? (
                    <div className="mfyx-label-normal mfyx-label-kd no-wrap">扣点</div>
                  ) : item.IsExternalLabel ? (
                    <div className="mfyx-label-normal mfyx-label-wbzy no-wrap">外部资源</div>
                  ) : null}
                  <span className="research-act-title">{item.ActivityName}</span>
                </div>
                <div className="research-act-time-line">
                  <span className="research-act-time">{item.ActivityTimeText}</span>
                  {item.City && (
                    <span className="research-act-city">
                      <CityImg fill="#FAA12F" className="city-icon" />
                      <span>{item.City}</span>
                    </span>
                  )}
                </div>
                <div className="research-act-btn-line">
                  <ActivityBtnComponent
                    item={item}
                    selfChange={true}
                    btnSpaceSize={media.isBigMax ? 8 : 20}
                    btnGrous={'bigcard'}
                  />
                </div>
              </div>
            )}
            pagination={{
              current: currentPage,
              total: actData?.Paging.Totals,
              hideOnSinglePage: true,
              showSizeChanger: true,
              showQuickJumper: true,
              responsive: true,
              pageSize: pageSize,
              pageSizeOptions: [10, 20, 50, 100],
              onChange: handleGetActivityData
            }}
          />
        )}
      </Spin>
    </div>
  )
}

export default ResearchActivity
