import './WashingMachine.scss';
import { View, Image } from '@tarojs/components';

import Home from './views/Home';
import Location from './views/Location';
import Appoint from './views/Appoint';

import Taro, {
  useState,
  useCallback,
  useEffect,
  usePullDownRefresh,
  useRef,
} from '@tarojs/taro';
import AppointmentCard from './components/AppointmentCard';
import CloseIcon from '../../images/washingmachine/ic_yuyueguanbi@2x.png';
import { useSelector } from '@tarojs/redux';
import { WasherStoreState } from '@/store/rootReducers/washer';
import useWasherStart from './hooks/useWasherStart';
import { beginWasher } from '@/api/washingMachine';

const WashingMachine = () => {
  const HomeRef = useRef(Promise.resolve);
  const LocationRef = useRef(Promise.resolve);
  const AppointRef = useRef(Promise.resolve);
  const getRef = (name: string, fun) => {
    if (name === 'Home') {
      HomeRef.current = fun;
    } else if (name === 'Location') {
      LocationRef.current = fun;
    } else if (name === 'Appoint') {
      AppointRef.current = fun;
    }
  };
  const [showState, setShowState] = useState('Home');
  const [showLocation, setShowLocation] = useState(false);
  const [showAppoint, setShowAppoint] = useState(false);
  const orderDetail = useSelector(
    (state: { washer: WasherStoreState }) => state.washer.orderDetail,
  );
  const showLocationHandle = useCallback(
    visibale => setShowLocation(visibale),
    [setShowLocation],
  );
  const [deviceCode, setDeviceCode] = useState('');
  const startHandle = (code: string) => {
    Taro.showLoading();
    setDeviceCode(code);
  };
  const { wsState, bluetoothState } = useWasherStart(deviceCode);

  console.log('orderDetail', orderDetail.deviceCode);
  useEffect(() => {
    console.log('orderDetail', orderDetail.deviceCode);
    if (orderDetail.deviceCode) {
      setShowAppoint(true);
    }
  }, [orderDetail.deviceCode]);

  useEffect(() => {
    console.log(wsState.socketState, bluetoothState);
    if (wsState.socketState && bluetoothState) {
      beginWasher({
        deviceCode,
        orderCode: orderDetail.orderCode,
      })
        .then(res => {
          Taro.hideLoading();
          setShowAppoint(false);
          HomeRef.current();
          Taro.showToast({
            title: res.msg || '开启成功',
            icon: 'none',
          });
        })
        .catch(err => {
          Taro.hideLoading();
          Taro.showToast({
            title: err.msg || '开启失败',
            icon: 'none',
          });
        });
    }
  }, [wsState.socketState, bluetoothState]);

  usePullDownRefresh(() => {
    if (showState === 'Home') {
      if (HomeRef.current) {
        HomeRef.current().then(() => {
          Taro.stopPullDownRefresh();
        });
      } else {
        Taro.stopPullDownRefresh();
      }
    } else if (showState === 'Location') {
      if (LocationRef.current) {
        LocationRef.current().then(() => {
          Taro.stopPullDownRefresh();
        });
      } else {
        Taro.stopPullDownRefresh();
      }
    } else if (showState === 'Appoint') {
      if (AppointRef.current) {
        AppointRef.current(0).then(() => {
          Taro.stopPullDownRefresh();
        });
      } else {
        Taro.stopPullDownRefresh();
      }
    } else {
      Taro.stopPullDownRefresh();
    }
  });

  return (
    <View className='WashingMachine'>
      <View className='WashingMachine-main'>
        {showState === 'Home' && (
          <Home getRef={getRef} showLocationHandle={showLocationHandle} />
        )}
        {showState === 'Location' && <Location getRef={getRef} />}
        {showState === 'Appoint' && (
          <Appoint getRef={getRef} startHandle={startHandle} />
        )}
      </View>
      <View className='WashingMachine-location'>
        {showLocation && (
          <View
            className='WashingMachine-mask'
            onClick={() => setShowLocation(false)}></View>
        )}
        <View
          className={`WashingMachine-locationMain ${
            showLocation ? 'visibale' : ''
          }`}>
          <Location
            getRef={getRef}
            input-bg='WashingMachine-locationMainInner'
          />
        </View>
      </View>
      {showAppoint && (
        <View className='WashingMachine-appointment'>
          <View className='WashingMachine-mask'></View>
          <View className='WashingMachine-appointmentMain'>
            <AppointmentCard data={orderDetail} startHandle={startHandle} />
            <View
              className='WashingMachine-appointmentClose'
              onClick={() => setShowAppoint(false)}>
              <Image src={CloseIcon} />
            </View>
          </View>
        </View>
      )}
      <View className='WashingMachine-footer'>
        <View
          className={`WashingMachine-footer-item ${
            showState === 'Home' ? 'actived' : ''
          }`}
          onClick={() => setShowState('Home')}>
          洗衣
        </View>
        <View
          className={`WashingMachine-footer-item ${
            showState === 'Location' ? 'actived' : ''
          }`}
          onClick={() => setShowState('Location')}>
          常用位置
        </View>
        <View
          className={`WashingMachine-footer-item ${
            showState === 'Appoint' ? 'actived' : ''
          }`}
          onClick={() => setShowState('Appoint')}>
          预约记录
        </View>
      </View>
    </View>
  );
};

WashingMachine.config = {
  navigationBarBackgroundColor: '#486dec',
  navigationBarTitleText: '洗衣',
  navigationBarTextStyle: 'white',
  backgroundColor: '#486dec',
  enablePullDownRefresh: true,
};

export default WashingMachine;
