import Buttons from "@/components/basic/Buttons";
import { setPlan } from "@/services/trackTimeDuration";
import { setScenario, setStep } from "@/store/scenario";
import { View, Text } from "@tarojs/components";
import "./SetSchedule.scss";
import Taro, { useReady } from "@tarojs/taro";
import TimePickers from "@/components/input/TimePickers";
// import { AtList, AtListItem } from 'taro-ui'
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Footer from "@/components/layout/Footer";
import PickerViews from "@/components/input/PickerViews";
// import { AtFloatLayout } from "taro-ui";
// import "taro-ui/dist/style/components/float-layout.scss";
import { durationDatas, durationIndex, durationTime, pickerDurations } from "../hooks/Console";
import { TimeFormatter } from "@/utils/time_format";

export default function Component() {
  const isFastFirst = false;
  const dispatch = useDispatch();
  
  const scenario = useSelector((state: any) => state.scenario);
  const common = useSelector((state: any) => state.common);

  const [isOpen, setIsOpen] = useState(false)

  // const [count,setCount] = useState(0)
  const [beginChange, setBeginChange] = useState(true)
  var scheduleObj: { start_time: any; end_time: any; };
  if (scenario.name == 'FAST') {
    scheduleObj = scenario.schedule.fast
  }
  else if (scenario.name == 'SLEEP') {
    scheduleObj = scenario.schedule.sleep
  }
  else {
    if (scenario.step == 'fast') {
      scheduleObj = scenario.schedule.fast
    }
    else {
      scheduleObj = scenario.schedule.sleep
    }
  }

  const [startTime, setStartTime] = useState(scheduleObj.start_time)
  const [endTime, setEndTime] = useState(scheduleObj.end_time)
  const [pickerValue, setPickerValue] = useState(durationIndex(scheduleObj.start_time, scheduleObj.end_time, common))

  const [hours, setHours] = useState(durationTime(scheduleObj.start_time, scheduleObj.end_time)[0])
  const [minutes, setMinutes] = useState(durationTime(scheduleObj.start_time, scheduleObj.end_time)[1])

  function start() {
    if (scenario.name == 'FAST' || scenario.name == 'SLEEP') {
      setPlan({
        scenario: scenario.name,
        schedule: scenario.name == 'FAST' ? {
          fast: {
            start_time: startTime,
            end_time: endTime,
          }
        } : {
          sleep: {
            start_time: startTime,
            end_time: endTime,
          }
        }
      }).then(res => {
        Taro.navigateBack({ delta: 3 })
        // console.log('success')
      })
    }
    else {
      if ((scenario.step == 'fast' && isFastFirst) || (scenario.step == 'sleep' && !isFastFirst)) {
        var obj = JSON.parse(JSON.stringify(scenario))
        if (isFastFirst) {
          obj.schedule.fast = {
            start_time: startTime,
            end_time: endTime,
          }
          dispatch(setStep('sleep'))
          dispatch(setScenario(obj))
        }
        else {
          obj.schedule.sleep = {
            start_time: startTime,
            end_time: endTime,
          }
          dispatch(setStep('fast'))
          dispatch(setScenario(obj))
        }

        Taro.navigateTo({
          url: '/pages/clock/SetSchedule'
        })
      }
      else {
        commit()
      }
    }
  }

  function commit() {
    setPlan({
      scenario: scenario.name,
      schedule: {
        fast: {
          start_time: isFastFirst ? scenario.schedule.fast.start_time : startTime,
          end_time: isFastFirst ? scenario.schedule.fast.end_time : endTime,
        }, sleep: {
          start_time: !isFastFirst ? scenario.schedule.sleep.start_time : startTime,
          end_time: !isFastFirst ? scenario.schedule.sleep.end_time : endTime,
          // start_time: startTime,
          // end_time: endTime,
        }
      }
    }).then(res => {
      dispatch(setStep('fast'))
      Taro.navigateBack({ delta: 4 })
    })
  }

  function onStartTimeChange(e: string) {
    setBeginChange(true)
    setStartTime(e)

    setPickerValue(durationIndex(e, endTime, common))
    setHours(durationTime(e, endTime)[0])
    setMinutes(durationTime(e, endTime)[1])
  }

  function onEndTimeChange(e: string) {
    setBeginChange(false)
    setEndTime(e)

    setPickerValue(durationIndex(startTime, e, common))
    setHours(durationTime(startTime, e)[0])
    setMinutes(durationTime(startTime, e)[1])
  }

  useReady(() => {
    var title = scenario.step == 'fast' ? 'Fast schedule' : 'Sleep schedule'
    Taro.setNavigationBarTitle({
      title: title
    })
  })

  function showPicker() {
    setIsOpen(true)
  }

  function durationChange(e) {
    var list = durationDatas(common)
    setHours(list[0][e[0]])
    setMinutes(list[1][e[1]])
    setPickerValue(e)
    setIsOpen(false)
    if (beginChange) {
      setEndTime(TimeFormatter.calculateTimeByTimeRange(list[0][e[0]] * 60 + list[1][e[1]], startTime, true));
    }
    else {
      setStartTime(TimeFormatter.calculateTimeByTimeRange(list[0][e[0]] * 60 + list[1][e[1]], endTime, false));
    }
  }

  function layoutContent() {
    return <View style={{ color: '#000' }}>
      <PickerViews onChange={durationChange} items={durationDatas(common)} value={pickerValue} height={200} showBtns={true} onCancel={() => { setIsOpen(false) }} />
    </View>
  }

  return <View >
    {/* <Text>场景名称{scenario.name}</Text> */}

    <View className="box">
      <View className="header">
        <View className="item">
          <TimePickers time={startTime} content={scenario.step == 'fast' ? 'Fast starts\n' + startTime : 'Sleep starts\n' + startTime} change={onStartTimeChange} />
        </View>
        <View className="item">
          <TimePickers time={endTime} content={scenario.step == 'fast' ? 'Fast ends\n' + endTime : 'Sleep ends\n' + endTime} change={onEndTimeChange} />
        </View>


      </View>
      <View style={{ flex: 1 }} />
      <Text className="duration" onClick={() => { setIsOpen(true) }}>{hours > 0 ? hours + ' hours ' : ''}{minutes > 0 ? minutes + ' minutes' : ''}</Text>
    </View>

    <Footer child={
      <Buttons title={scenario.step == 'fast' ? 'Set fast schedule' : 'Set sleep schedule'} style={{ backgroundColor: scenario.step == 'fast' ? '#AAFF00' : '#00ffff', width: 320 }} onClick={() => start()}></Buttons>
    } />

    <AtFloatLayout
      isOpened={isOpen}
      onClose={() => {
        setIsOpen(false)
      }}>
      {
        layoutContent()
      }
    </AtFloatLayout>

  </View>;
}