import {FC, useEffect, useState} from "react";
import {Picker} from "@tarojs/components";
import {dateDate, DateTime, dateTimePicker, DateTimePickers, getIndex, getTime} from './utils'

interface Props {
  children?: JSX.Element
  disabled?: boolean
  defaultValue?: string
  onChange?: (time: string) => void
  name?:string
}

const DateTimePicker: FC<Props> = (props) => {
  const [defaultValue, setDefaultValue] = useState<DateTime>(dateDate(new Date(props.defaultValue || Date.now())))   // 默认时间 或者 当天时间
  const datePicker = dateTimePicker(defaultValue.year, defaultValue.year)  // 时间选择器数据（年，月，日，时间）
  const [activityArray, setActivityArray] = useState<DateTimePickers>([])
  const [value, setValue] = useState<number[]>([])


  useEffect(() => {
    setDefaultValue(dateDate(new Date(props.defaultValue || Date.now())))
    const data = datePicker(defaultValue.year, defaultValue.month)
    setValue(getIndex(data, defaultValue))
    setActivityArray(data)
  }, [props.defaultValue])


  function change(e) {
    props?.onChange?.(getTime(activityArray, e.detail.value))
  }

  function columnChange(e) {
    const oldValue: number[] = JSON.parse(JSON.stringify(value))
    oldValue[e.detail.column] = e.detail.value
    setValue(oldValue)

    let year = activityArray[0][oldValue[0]].id
    let month = activityArray[1][oldValue[1]].id

    switch (e.detail.column) {
      case 0:
        year = e.detail.value
        break
      case 1:
        month = e.detail.value + 1
        break
    }
    if ([0, 1].includes(e.detail.value)) {
      const data = datePicker(year, month)
      setActivityArray(data)
    }
  }

  return (
    <Picker
      name={props.name}
      value={value}
      range={activityArray}
      rangeKey='name'
      disabled={props.disabled}
      mode="multiSelector"
      range-key='name'
      onChange={change}
      onColumnChange={columnChange}
    >
      {props.children}
    </Picker>
  )
}

export default DateTimePicker
