import {Text, View} from "@tarojs/components";
import Tabs, {OnChangOpt, TabList} from "@/components/tabs/tabs";
import {everyDay, formatTime, getMonday, getSunday, monthEnd, monthFirst} from "@/utils/time";
import LineChart from "@/components/lineChart/lineChart";
import {CSSProperties, FC, useEffect, useState} from "react";
import {StatisticsParam, userApi} from "@/api";
import styles from './learningRecord.module.scss'
// import Spin from "@/components/spinner";
import {Profile} from "@/store";
import Taro from "@tarojs/taro";
import debounce from "@/utils/debounce";

const tabList: TabList<any>[] = [
  {
    title: '日',
    value: {
      start_time: new Date().setHours(0, 0, 0, 0),
      end_time: new Date().setHours(24, 0, 0, 0)
    }
  },
  {
    title: '周', value: {
      start_time: getMonday(),
      end_time: getSunday()
    }
  },
  {
    title: '月', value: {
      start_time: monthFirst(),
      end_time: monthEnd()
    }
  },
]

interface Props {
  userId?: string | number
  style?: CSSProperties
  className?: string
}


/**
 * 学习记录折线图
 */
const LearningRecord: FC<Props> = ({userId, style, className}) => {
  const [lineData, setLineData] = useState<any[]>([])
  // const [loading, setLoading] = useState(false)
  const {token} = Profile.useContainer()

  async function getStatistics(data: StatisticsParam) {
    try {
      if (!userId) return;
      setLineData([])
      const res = await userApi.statistics(userId, data)
      const everyDayValue = everyDay(data.start_time, Number(data.end_time), res.data)
      setLineData(everyDayValue)
    } catch (e) {
      setLineData([])
    }
  }

  function tabChange({tab}: OnChangOpt<StatisticsParam>) {
    if (!token) {
      Taro.navigateTo({url: '/pages/login/login'})
      return
    }
    // getStatistics(tab?.value! as StatisticsParam)
    debounce(()=>{
      // console.log(this,'this')
      getStatistics(tab?.value! as StatisticsParam)
    })
  }

  useEffect(() => {
    userId && setTimeout(() => {getStatistics(tabList[0].value)},500)
  }, [userId])

  return (<View className={[styles.box, className].filter(Boolean).join(' ')} style={{display: 'block', ...style}}>
    <Tabs tabList={tabList} onChange={tabChange} backMode/>
    <View style={{position: "relative"}}>
      {/*<Spin enable={loading} block/>*/}
      <View className={styles.total}>
        总共学习
        <Text style={{margin: '0 10px', color: '#00D6AC'}}>
          {formatTime(lineData.reduce((pre, cur) => pre + cur.value, 0) || 0)}
        </Text>
      </View>
      <LineChart data={lineData}/>
    </View>
  </View>)
}

export default LearningRecord
