import { View, Input, Image } from '@tarojs/components';
import './Location.scss';
import CloseIcon from '../../../images/washingmachine/ic_guanbi@2x.png';
import usePositionList from '../hooks/usePositionList';
import { useState, useCallback, useEffect } from '@tarojs/taro';
import useInputValue from '@/hooks/useInputValue';

const WashingMachineLocation = (props: {
  getRef: (name: string, fun: Function) => void;
}) => {
  const { value, onChange, setValue } = useInputValue('');
  const [positionInput, setPositionInput] = useState('');
  const inputHandle = e => {
    console.log('in inputHandle', e);
    setPositionInput(value);
    setValue('');
  };
  const {
    list,
    usedList,
    fetchList,
    addPositionHandle,
    delPositionHandle,
  } = usePositionList(positionInput);

  useEffect(() => {
    props.getRef('Location', fetchList);
  }, []);

  return (
    <View className='WashingMachineLocation'>
      <View className='WashingMachineLocation-search input-bg'>
        <Input
          placeholder='输入要搜索的位置'
          value={value}
          onInput={onChange}
          onConfirm={inputHandle}
        />
      </View>
      <View className='WashingMachineLocation-PostionList'>
        {usedList && usedList.length && (
          <View className='WashingMachineLocation-usually'>
            <View className='WashingMachineLocation-title'>已选择常用位置</View>
            {usedList.map(position => (
              <View
                key={position.id}
                className='WashingMachineLocation-usuallyItem'>
                <View
                  key={position.id}
                  className='WashingMachineLocation-usuallyItem_postion'>
                  {position.name}
                </View>
                <View
                  className='WashingMachineLocation-usuallyItem_closeIcon'
                  onClick={() => delPositionHandle(position.id)}>
                  <Image src={CloseIcon} />
                </View>
              </View>
            ))}
          </View>
        )}

        <View className='WashingMachineLocation-list'>
          <View className='WashingMachineLocation-title'>全部位置</View>
          {list.map(position => (
            <View
              key={position.id}
              className='WashingMachineLocation-listItem'
              onClick={() => addPositionHandle(position.id)}>
              {position.name}
            </View>
          ))}
        </View>
      </View>
    </View>
  );
};

WashingMachineLocation.externalClasses = ['input-bg'];

export default WashingMachineLocation;
