import {Image, ScrollView, Text, View} from "@tarojs/components";
import {FC, useEffect, useState} from "react";
import style from './lineChart.module.scss'
import {formatDateTime, formatTime} from "@/utils/time";
import emptyLineChart from '@/static/img/emptyLineChart.png'

export interface lineData {
  time: string
  value: number
}

interface Props {
  data: lineData[]
}

const height = 150
const LineChart: FC<Props> = ({data}) => {
  const [maxHeight, setMaxHeight] = useState<lineData>({time: '', value: 0})
  const [lineChartList, setLineChartList] = useState(data)

  useEffect(() => {
    setLineChartList(data)
    setMaxHeight(data.reduce((pre, cur) => {
      if (cur.value > pre.value) {
        return cur
      }
      return pre
    }, {time: formatDateTime(new Date(), 'MM/dd'), value: 0}))
  }, [data])

  return (
    <>
      <View className={style.records}>
        <Text>{formatDateTime(new Date(maxHeight.time), 'MM月dd日')}</Text>
        {maxHeight.value > 0 ? `日最努力` : `期间没有学习记录`}，学习了{formatTime(maxHeight.value, 0)}
      </View>
      <ScrollView scrollX={!!maxHeight.value} enhanced showScrollbar={false}>
        <View className={style.lineChart}>
          {
            !maxHeight.value && <View className={style.empty}>
              <View>暂无学习记录</View>
              <Image src={emptyLineChart} mode='widthFix' style={{width: '100%'}}/>
            </View>
          }
          {
            !!maxHeight.value
            && lineChartList.map(d => <View key={d.time}>
              <View className={style.columnBox} style={{width: "100px"}}>
                <View className={style.line} style={{height: height - 10 - (d.value / maxHeight.value * height) + "px"}}/>
                {
                  d.value > 0 && <View style={{whiteSpace: "nowrap"}}>{formatTime(d.value, 0)}</View>
                }
                <View className={style.column} style={{height: d.value / maxHeight.value * height + "px"}}/>
                <View>{d.time}</View>
              </View>
            </View>)
          }
        </View>
      </ScrollView>
    </>
  )
}

export default LineChart
