import Buttons from "@/components/basic/Buttons";
import { setPlan } from "@/services/trackTimeDuration";
import { setScenario, setStep } from "@/store/scenario";
import { View, Text, PageContainer } from "@tarojs/components";
import "./SetSchedule.scss";
import Taro, { useDidShow, useReady } from "@tarojs/taro";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import Footer from "@/components/layout/Footer";
import PickerViews from "@/components/input/PickerViews";
import { durationDatas, durationIndex, durationTime, pickerDurations } from "../hooks/Console";
import { TimeFormatter } from "@/utils/time_format";
import Modal from "@/components/layout/Modal";
import Dial from './Dial';
import TimePicker from "@/features/common/TimePicker";
import { SetScheduleBtn } from "@/features/common/SpecBtns";
import Layout from "@/components/layout/layout";
import { NaviBarTitleShowType, TemplateType } from "@/utils/types";
import { useTranslation } from "react-i18next";
import { ColorType } from "@/context/themes/color";
import TitleView from "./TitleView";
import { jumpPage } from "../hooks/Common";
import { vibrate } from "@/utils/tools";
import { wxPubFollow } from "@/services/permission";
import { setWXFollow } from "@/store/permission";

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

  const [isOpen, setIsOpen] = useState(false)
  const [isTimeOpen, setIsTimeOpen] = useState(false)
  const [btnDisable, setBtnDisable] = useState(false)

  const pickerRef = useRef<any>(null);
  // const [count,setCount] = useState(0)
  const [beginChange, setBeginChange] = useState(true)
  const [operateType, setOperateType] = useState(0)
  const [isModalTimePicker, setIsModalTimePicker] = useState(false)

  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])
  const [chooseStart, setChooseStart] = useState(true)
  const [count, setCount] = useState(0)

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

  useEffect(() => {
    if (isOpen || isTimeOpen) {
      global.disableCanvasGesture = true
    }
    else {
      global.disableCanvasGesture = false
    }
  }, [isOpen, isTimeOpen])


  useDidShow(() => {
    setCount(count + 1)
    wxPubFollow({ force_refresh: true }).then(res => {
      dispatch(setWXFollow((res as any).wx_pub_followed));
    })
  })

  function followWxPub() {
    const resource = common.resources.filter((item: any) => {
      return item.code == 'follow_wx_pub'
    })

    // Taro.showModal({
    //   title: '提示',
    //   content: '关注公众号后可接收提醒\n点击确定，前往关注',
    //   showCancel: true,
    //   success(result) {
    //     if (result.confirm) {
    jumpPage('/pages/common/H5?title=fast16cc 关注服务号&url=' + resource[0].url)
    //   }
    // },
    // })
  }


  function start() {
    if (scenario.name == 'FAST' || scenario.name == 'SLEEP') {
      setBtnDisable(true)
      setPlan({
        scenario: scenario.name,
        schedule: scenario.name == 'FAST' ? {
          fast: {
            start_time: startTime,
            end_time: endTime,
          }
        } : {
          sleep: {
            start_time: startTime,
            end_time: endTime,
          }
        }
      }).then(res => {
        setBtnDisable(false)
        // global.checkData()
        global.indexPageRefresh()

        console.log('set schedule 3 navi back')
        Taro.navigateBack({ delta: 3 }).then(res => {

        })

        debugger
        setTimeout(() => {
          debugger
          global.popScheduleAlert(scenario, startTime)
        }, 1000)
      }).catch(e => {
        setBtnDisable(false)
      })
    }
    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)

        jumpPage('/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() {
    setBtnDisable(true)
    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,
        }
      }
    }).then(res => {
      setBtnDisable(false)
      dispatch(setStep('fast'))
      // global.checkData()
      Taro.navigateBack({ delta: 4 })
      console.log('set schedule 4 navi back')

      debugger
      setTimeout(() => {
        debugger
        global.popMixScheduleAlert(scenario.schedule.fast.start_time, scenario.schedule.sleep.start_time)
      }, 1000)



      global.indexPageRefresh()
    }).catch(e => {
      setBtnDisable(false)
    })
  }

  function onStartTimeChange(e: string) {
    setIsTimeOpen(false)
    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) {
    setIsTimeOpen(false)
    setBeginChange(false)
    setEndTime(e)
    setPickerValue(durationIndex(startTime, e, common))
    setHours(durationTime(startTime, e)[0])
    setMinutes(durationTime(startTime, e)[1])
    saveTempCache(startTime, e);
    console.log(e)
    global.updateDial(startTime, e)
  }



  function showPicker() {
    setIsOpen(true)
  }

  function durationChange(e) {
    var count = (e[0] + common.duration.min) * 60 + e[1] * common.duration.step

    var h = parseInt(count / 60)
    var m = count % 60
    setHours(h)
    setMinutes(m)
    setPickerValue(e)
    setIsOpen(false)
    if (beginChange) {
      var strEnd = TimeFormatter.calculateTimeByTimeRange(count, startTime, true)

      setEndTime(strEnd);
      saveTempCache(startTime, strEnd)
      global.updateDial(startTime, strEnd)
    }
    else {
      var strStart = TimeFormatter.calculateTimeByTimeRange(count, endTime, false)
      setStartTime(strStart);
      saveTempCache(strStart, endTime)
      global.updateDial(strStart, endTime)
    }

  }

  global.startDuration = (type) => {
    setOperateType(type)
  }

  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 (operateType == 1 && startCount % 30 == 0) {
      vibrate()
    }
    else if (operateType == 2 && endCount % 30 == 0) {
      vibrate()
    }
    else if (operateType == 3 && (startCount % 30 == 0 || endCount % 30 == 0)) {
      vibrate()
    }

    setStartTime(start)
    setEndTime(end)
    setPickerValue(durationIndex(start, end, common))
    setHours(durationTime(start, end)[0])
    setMinutes(durationTime(start, end)[1])
    saveTempCache(start, end)
  }


  global.endDuration = () => {
    setOperateType(0)
  }

  function layoutContent() {
    return <PickerViews ref={pickerRef}
      onChange={durationChange}
      items={durationDatas(common)}
      value={pickerValue} height={200}
      title={scenario.step == 'fast' ?
        t('feature.track_time_duration.dial.picker_fast_schedule_duration') :
        t('feature.track_time_duration.dial.picker_sleep_schedule_duration')}
      themeColor={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
      showBtns={true} onCancel={() => { setIsOpen(false) }} />
  }

  function pickerTitle() {
    if (scenario.step == 'fast') {
      if (chooseStart) {
        return t('feature.track_time_duration.dial.picker_fast_schedule_start_time');
      }
      return t('feature.track_time_duration.dial.picker_fast_schedule_end_time');
    }
    else {
      if (chooseStart) {
        return t('feature.track_time_duration.dial.picker_sleep_schedule_start_time');
      }
      return t('feature.track_time_duration.dial.picker_sleep_schedule_end_time');
    }
  }


  function timeContent() {
    return <TimePicker time={chooseStart ? startTime : endTime}
      color={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
      title={pickerTitle()}
      confirm={chooseStart ? onStartTimeChange : onEndTimeChange}
      cancel={() => { setIsTimeOpen(false) }} />
  }

  function detail() {
    return <View >
      {/* <Text className="subtitle">{t('page.set_schedule.fast_subtitle')}</Text> */}
      <TitleView title={scenario.step == 'fast' ? t('page.set_schedule.fast_title') : t('page.set_schedule.sleep_title')}
        subTitle={t('page.set_schedule.fast_subtitle')}
        titleColor={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
      />

      <View className="box">
        <View className="header" style={{ backgroundColor: global.isDebug ? '#EEC01F' : 'transparent' }}>
          <View className="item1" style={{ opacity: operateType == 1 || operateType == 3 ? 1 : 0.4, backgroundColor: global.isDebug ? 'pink' : 'transparent' }} onClick={() => {
            setIsModalTimePicker(true)
            setChooseStart(true)
            setIsTimeOpen(true)
          }}>
            <Text className="item_title schedule_text_key">{t('feature.track_time_duration.dial.start_time')}</Text>
            <Text className="item_text schedule_text_value">{startTime}</Text>
          </View>
          <View style={{ width: 23 }} />
          <View className="item1" style={{ opacity: operateType == 2 || operateType == 3 ? 1 : 0.4, backgroundColor: global.isDebug ? 'pink' : 'transparent' }} onClick={() => {
            setIsModalTimePicker(true)
            setChooseStart(false)
            setIsTimeOpen(true)
          }}>
            <Text className="item_title schedule_text_key">{t('feature.track_time_duration.dial.end_time')}</Text>
            <Text className="item_text schedule_text_value">{endTime}</Text>
          </View>

        </View>
        <View className="dial_bg" style={{ backgroundColor: global.isDebug ? 'pink' : 'transparent' }}>
          <Dial ref={canvasRef} />
        </View>
        <View className="duration_bg" style={{ opacity: operateType == 1 || operateType == 2 ? 1 : 0.4, backgroundColor: global.isDebug ? 'pink' : 'transparent' }} onClick={() => { setIsModalTimePicker(false); setIsOpen(true) }}>
          <Text className="duration_title schedule_text_key">{t('feature.track_time_duration.dial.duration')}</Text>
          <Text className="duration_value schedule_text_value"  >{hours > 0 ? hours + TimeFormatter.getHoursUnit(hours) : ''}{minutes > 0 ? minutes + '分钟' : ''}</Text>
        </View>

      </View>

      <Footer>
        <SetScheduleBtn title={(scenario.step == 'fast' && scenario.name == 'FAST_SLEEP') ? t('feature.common.btn_set_and_next') : t('feature.common.btn_set_and_done')}
          lowLight={operateType != 0}
          isFast={scenario.step == 'fast'}
          disable={btnDisable}
          onClick={() => start()} />
      </Footer>

      {/* <PageContainer style={{ backgroundColor: '#1c1c1c' }}
        overlayStyle='background-color:rgba(0,0,0,0.9)'
        custom-style='background-color:#1c1c1c'
        closeOnSlideDown={false}
        onAfterLeave={() => { setIsOpen(false); setIsTimeOpen(false) }}
        show={isOpen || isTimeOpen} round={true} overlay={true} position='bottom'
      >
        {
          isModalTimePicker?timeContent():layoutContent()
        }
      </PageContainer> */}
      {
        isOpen && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)} confirm={() => {
          setIsOpen(false)
          durationChange(pickerRef.current.getConfirmData())
        }} />
      }
      {
        isTimeOpen && <Modal children={timeContent()} dismiss={() => setIsTimeOpen(false)} confirm={() => {
          setIsTimeOpen(false)
        }} />
      }

    </View>
  }

  return <Layout
    titleColor={scenario.step == 'fast' ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep}
    title={scenario.step == 'fast' ? t('page.set_schedule.fast_title') : t('page.set_schedule.sleep_title')}
    titleShowStyle={NaviBarTitleShowType.scrollToShow} type={TemplateType.customHeader}>
    {
      detail()
    }
  </Layout>;
}