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 { useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Footer from "@/components/layout/Footer";
import PickerViews from "@/components/input/PickerViews";
// import "taro-ui/dist/style/components/float-layout.scss";
import { durationDatas, durationIndex, durationTime, pickerDurations } from "../hooks/Console";
import { TimeFormatter } from "@/utils/time_format";
import Modal from "@/components/layout/Modal";
import Dial from './Dial';

export default function Component() {
  const isFastFirst = true;
  const dispatch = useDispatch();
  const canvasRef = useRef(null);
  const [scenario] = useState(useSelector((state: any) => state.scenario))
  // const scenario = useSelector((state: any) => state.scenario);
  const common = useSelector((state: any) => state.common);

  const [isOpen, setIsOpen] = useState(false)

  const pickerRef = useRef<any>(null);
  // 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)

  global.startTime = startTime
  global.endTime = endTime
  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])

  useReady(() => {
    if (global.schedule_fast && scenario.step == 'fast') {
      scheduleObj = global.schedule_fast
    }
    if (global.schedule_sleep && scenario.step == 'sleep') {
      scheduleObj = global.schedule_sleep
    }
    setStartTime(scheduleObj.start_time)
    setEndTime(scheduleObj.end_time)
    setPickerValue(durationIndex(scheduleObj.start_time, scheduleObj.end_time, common))
    setHours(durationTime(scheduleObj.start_time, scheduleObj.end_time)[0])
    setMinutes(durationTime(scheduleObj.start_time, scheduleObj.end_time)[1])


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

  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))
        }

        saveTempCache(startTime, endTime)

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

  function saveTempCache(strStart, strEnd) {
    if (scenario.step == 'fast') {
      global.schedule_fast = {
        start_time: strStart,
        end_time: strEnd,
      }
    }
    if (scenario.step == 'sleep') {
      global.schedule_sleep = {
        start_time: strStart,
        end_time: strEnd,
      }
    }

  }

  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])
    saveTempCache(e, endTime);

    global.updateDial(e,endTime)
  }

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

    setPickerValue(durationIndex(startTime, e, common))
    setHours(durationTime(startTime, e)[0])
    setMinutes(durationTime(startTime, e)[1])
    saveTempCache(startTime, e);
    global.updateDial(startTime,e)
  }



  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) {
      var strEnd = TimeFormatter.calculateTimeByTimeRange(list[0][e[0]] * 60 + list[1][e[1]], startTime, true)
      setEndTime(strEnd);
      saveTempCache(startTime, strEnd)
      global.updateDial(startTime,strEnd)
    }
    else {
      var strStart = TimeFormatter.calculateTimeByTimeRange(list[0][e[0]] * 60 + list[1][e[1]], endTime, false)
      setStartTime(strStart);
      saveTempCache(strStart, endTime)
      global.updateDial(strStart,endTime)
    }

  }

  global.updateDuration = (start,end)=>{
    var  startCount = parseInt(start.split(':')[0]) * 60 + parseInt(start.split(':')[1])
    var  endCount = parseInt(end.split(':')[0]) * 60 + parseInt(end.split(':')[1])
    if (startCount %15==0 || endCount %15==0) {
      Taro.vibrateShort()
    }
    
    setStartTime(start)
    setEndTime(end)
    setPickerValue(durationIndex(start,end,common))
    setHours(durationTime(start,end)[0])
    setMinutes(durationTime(start,end)[1])
    saveTempCache(start,end)
  }

  function layoutContent() {
    return <PickerViews ref={pickerRef} onChange={durationChange} items={durationDatas(common)} value={pickerValue} height={200} showBtns={true} onCancel={() => { setIsOpen(false) }} />
  }

  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,display:'flex',alignItems:'center',justifyContent:'center' }}>
        <Dial ref={canvasRef}/>
      </View>
      <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>
    } />
    {
      isOpen && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)} confirm={()=>{
        setIsOpen(false)
        durationChange(pickerRef.current.getConfirmData())
      }}/>
    }


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

  </View>;
}