import { View, Image, Input, Text } from '@tarojs/components';
import './Home.scss';
import ScanIcon from '../../../images/washingmachine/ic_saoma-e@2x.png';
import NoDataIcon from '../../../images/washingmachine/img_empty@2x.png';

import Taro, {
  useState,
  useCallback,
  useDidShow,
  useEffect,
} from '@tarojs/taro';
import { FetchWasherStatus } from '@/api/washingMachine';
import useWasherList from '../hooks/useWasherList';
import WasherCard from '../components/WasherCard';
import useInputValue from '@/hooks/useInputValue';
import useWasherDevice from '../hooks/useWasherDevice';

const WashingMachineHome = (props: {
  showLocationHandle: (visibility: boolean) => void;
  getRef: (name: string, fun: Function) => void;
}) => {
  const [showState, setShowState] = useState(0); // 0：空闲；1：使用中。
  const { value, onChange } = useInputValue('');
  const [deviceList, fetchDeviceList] = useWasherList(showState);
  const [deviceCode, setDeviceCode] = useState('');

  useWasherDevice(deviceCode, () => {
    setDeviceCode('');
    Taro.navigateTo({
      url: '/pages/WashingMachine/WasherStart',
    });
  });

  const scanHandle = () => {
    console.log('scanHandle');
    Taro.scanCode()
      .then(res => {
        console.log(res);
        const result: string = res.result;

        onChange({
          type: '',
          timeStamp: 0,
          target: { id: '', tagName: '', dataset: {} },
          currentTarget: { id: '', tagName: '', dataset: {} },
          detail: { value: result, cursor: 0, keyCode: 0 },
          preventDefault: () => {},
          stopPropagation: () => {},
        });
        setDeviceCode(result);
      })
      .catch(err => {
        console.log(err);
        Taro.showToast({
          title: err.errMsg,
          icon: 'none',
        });
      });
  };
  const searchHandle = () => {
    console.log('searchHandle', value);
    if (value) {
      setDeviceCode(value);
    }
  };
  const refreshList = () => fetchDeviceList(showState);

  const goAppointmentOrder = useCallback((value: string) => {
    console.log('goAppointmentOrder', deviceCode, value);
    if (deviceCode === value) {
      Taro.navigateTo({
        url: '/pages/WashingMachine/WasherStart',
      });
    } else {
      setDeviceCode(value);
    }
  }, []);

  useEffect(() => {
    props.getRef('Home', refreshList);
  }, []);
  useDidShow(() => {
    console.log('componentDidShow');
    refreshList();
  });
  return (
    <View className='WashingMachineHome'>
      <View className='WashingMachineHome-sreach'>
        <View className='WashingMachineHome-sreach-inputbox'>
          <Input
            className='WashingMachineHome-sreach-inputbox_input'
            placeholder='输入洗衣机上的设备编码或点击扫一扫'
            value={value}
            onInput={onChange}
          />
          <View
            className='WashingMachineHome-sreach-inputbox_text'
            onClick={searchHandle}
          >
            搜索
          </View>
        </View>
        <View className='WashingMachineHome-scan' onClick={scanHandle}>
          <Image src={ScanIcon}></Image>
        </View>
      </View>
      <View className='WashingMachineHome-list'>
        <View className='WashingMachineHome-list_title'>
          <View>
            <Text
              className={`WashingMachineHome-list_titleItem ${
                showState === FetchWasherStatus.unusing ? 'actived' : ''
              }`}
              onClick={() => setShowState(0)}
            >
              空闲中
            </Text>
            <Text
              className={`WashingMachineHome-list_titleItem ${
                showState === FetchWasherStatus.using ? 'actived' : ''
              }`}
              onClick={() => setShowState(1)}
            >
              将结束
            </Text>
          </View>
          <View
            className='WashingMachineHome-list_titleLocation'
            onClick={() => props.showLocationHandle(true)}
          >
            位置筛选
          </View>
        </View>
        <View className='WashingMachineHome-list_content'>
          {deviceList && deviceList.length ? (
            deviceList.map(data => (
              <WasherCard
                key={data.deviceCode}
                data={data}
                goAppointmentOrder={goAppointmentOrder}
              />
            ))
          ) : (
            <View className='WashingMachineHome-list_nocontent'>
              <View className='WashingMachineHome-list_nocontentImg'>
                <Image src={NoDataIcon} />
              </View>
              <View className='WashingMachineHome-list_nocontentText'>
                洗衣机突然暴走了~
              </View>
              <View
                className='WashingMachineHome-list_nocontentBtn'
                onClick={refreshList}
              >
                刷新看看
              </View>
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

export default WashingMachineHome;
