import {Image, ScrollView, Swiper, SwiperItem, View} from "@tarojs/components";
import {userApi} from "@/api";
import {useCallback, useEffect, useState} from "react";
import Tabs, {OnChangOpt, TabList} from "@/components/tabs/tabs";
import Empty from "@/components/empty/empty";
import Taro from "@tarojs/taro";
import styles from './collect.module.scss'
import Spin from "@/components/spinner";
import Img from "@/components/image/image";
import {rfc33392time} from "@/utils/day";
import play from "@/static/img/play.png";
import PageScript from "@/components/pageScript/pageScript";

interface KillData {
  data: any[]
  total: number
  page: number
}

const Profession = () => {
  const [tabs, setTabs] = useState<TabList[]>([])
  const [categoryId, setCategoryId] = useState<number | null>(null)
  const [data, setData] = useState<Map<number, KillData>>(new Map)
  const [enable, setEnable] = useState(true)

  /**
   * more 开启加载更多
   */
  async function getData(more = false) {
    if (!categoryId) return;
    const oldData = new Map<number, KillData>(data)
    const categoryData = oldData.get(categoryId)
    const page = more ? (categoryData?.page || 0) + 1 : categoryData?.page || 1

    /** 无更多 */
    if (more && categoryData && categoryData.data.length >= categoryData.total) {
      return
    }

    try {
      const data = await userApi.collectList(categoryId!, page, 10)
      // const dataList = data.list.reduce((pre, cur) => {
      //   const index = pre.findIndex(d => d.id === cur.id)
      //   if (index === -1) {
      //     pre.push(cur)
      //   } else {
      //     pre.splice(index, 1, cur)
      //   }
      //   return pre
      // }, categoryData?.data || [])
      oldData.delete(categoryId)
      oldData.set(categoryId, {
        data: data.list,
        total: data.total,
        page: page
      })
      setData(oldData)
    } catch (e) {
    }
  }

  Taro.useDidShow(useCallback(() => {
    if (categoryId) {
      let tempMap = new Map()
      tempMap.set(categoryId, {
        data: [],
        total: undefined,
        page: 1
      })
      setData(tempMap)
      getData()
    }
  }, [data]))

  useEffect(() => {
    categoryId && getData()
  }, [categoryId])

  async function getCategory() {
    try {
      const res = [{name: '视频', id: 2}, {name: '文章', id: 1}, {name: '课程', id: 3}, {name: '其他', id: 4}]
      const newTabs = res.map<TabList>(d => ({title: d.name, value: d.id}))
      setTabs(newTabs)
      setCategoryId(newTabs[0].value as number)
    } catch (e) {
    }
    setEnable(false)
  }

  function tabsChange(tab: OnChangOpt) {
    setCategoryId(tab.tab?.value as number)
  }

  function jumpInfo(info: any) {
    console.log(info, 'info')
    if (info.article) {
      Taro.navigateTo({url: `/pages/preview/brand/article/article?id=${info.owner_id}`})
    } else if (info.course) {
      Taro.navigateTo({url: `/pages/business/videoInfo/videoInfo?id=${info.owner_id}`})
    } else if (info.video_records) {
      Taro.navigateTo({url: `/pages/preview/videoFull/videoFull?id=${info.owner_id}`})
    } else if (info.brand) {
      Taro.navigateTo({url: `/pages/preview/brand/info/info?id=${info.owner_id}`})
    }
  }

  function swiperChange(e) {
    const categoryId = tabs[e.target.current].value
    setCategoryId(Number(categoryId))
  }

  Taro.useLoad(getCategory)

  function KillList(data: KillData): JSX.Element {
    if (!data?.data?.length) {
      return <Empty name='暂无数据'/>
    }
    return (
      <ScrollView
        scrollY
        onScrollToLower={() => getData(true)}
        className={styles.height}>
        {
          data.data.map(d =>
            <View onClick={() => jumpInfo(d)} className={styles.box} key={d.id}>
              {
                d.brand &&
                <>
                  <Img width={128} height={128} src={d.brand.logo} mode='aspectFill' className={styles.image}/>
                  <View className={styles.rightBox}>
                    <View className='font-weight mb-2 font-28'>{d.brand.name}</View>
                    <View className={styles.desc}>{d.brand.graphic_introduction || '暂无品牌简介'}</View>
                  </View>
                </>
              }
              {
                d.article &&
                <>
                  <View className={styles.articleLeftBox}>
                    <View className='font-weight mb-2 font-28 lh-40'>{d.article.title}</View>
                    <View className={styles.desc}>{rfc33392time(d.article.created_at)} {d.article.page_view}阅读</View>
                  </View>
                  <Img width={172} height={128} src={d.article.logo} mode='aspectFill' className={styles.image}/>
                </>
              }
              {
                d.video_records &&
                <>
                  <Img width={192} height={192} src={d.video_records.url_path} mode='aspectFill'
                       className={styles.image}/>
                  <Image src={play} className={styles.play} mode='aspectFit'/>
                  <View className={styles.videoRightBox}>
                    <View className='font-weight mb-2 font-28 lh-40'>{d.video_records.title}</View>
                    <View className={styles.desc}>{d.video_records.introduction}</View>
                    <View className={`${styles.desc} mt-2`}>播放量: {d.video_records.video_view}</View>
                  </View>
                </>
              }
              {
                d.course &&
                <>
                  <Img width={192} height={138} src={d.course.thumb} mode='aspectFill' className={styles.image}/>
                  <View className={styles.courseRightBox}>
                    <View className='font-weight mb-2 font-28 lh-40'>{d.course.title}</View>
                    <View className={styles.desc}>课时:{d.course.class_hour}节 销量：{d.course.charge}</View>
                  </View>
                </>
              }
            </View>
          )
        }
        <PageScript/>
      </ScrollView>
    )
  }


  return (
    <>
      <Spin enable={enable} overlay/>
      <View className='bg-white'>
        <Tabs tabList={tabs} onChange={tabsChange} current={categoryId!}/>
      </View>

      <Swiper
        current={tabs.findIndex(d => d.value === categoryId)}
        onChange={swiperChange}
        className={styles.height}
        style={{paddingTop: '10px'}}>
        {
          tabs.map(d => <SwiperItem key={d.title}>
            {KillList(data.get(Number(d.value))!)}
          </SwiperItem>)
        }
      </Swiper>
    </>
  )
}
export default Profession
