import './ShowerAppointment.scss';
import { View, Input, Text, ScrollView, Image } from '@tarojs/components';
import Taro, { useState, useEffect } from '@tarojs/taro';
import AppointermentCard from './components/AppointermentCard/AppointermentCard';
import useInputValue from '@/hooks/useInputValue';
import {
  appointingEquipment,
  ShowerUseType,
  OperationMode,
  fetchAppointResult,
  AppointResultRes,
} from '@/api/shower';
import { useSelector } from '@tarojs/redux';
import { Customer } from '@/types/Customer/Customer';
import useDeviceList from './hooks/useDeviceList';
import AppointermentEquipment from './components/AppointermentEquipment/AppointermentEquipment';
import useAppointRecordsList from './hooks/useAppointRecordsList';
import useCheckAppointable from './hooks/useCheckAppointable';
import { ShowerState } from '@/store/rootReducers/shower';
import AppBackButton from '@/components/AppBackButton/AppBackButton';
import WaitPayOrderComponent from '@/components/WaitPayOrder/WaitPayOrder';
import EmptyIcon from '../../images/shower/empty_yuyue@2x.png';

function ShowerAppointment() {
  const userInfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo,
  );
  const showerControlConfig = useSelector(
    (state: { showerState: ShowerState }) =>
      state.showerState.controllerConfigs,
  );
  const [showState, setShowState] = useState(1);
  const [recordId, setRecordId] = useState(0);
  const [loopResultState, setLoopResultState] = useState(false);
  const search = useInputValue('');
  const [searchString, setSearchString] = useState('');

  const appointableData = useCheckAppointable(
    userInfo.customerId,
    userInfo.areaId,
  );

  const list = useDeviceList(
    userInfo.areaId,
    userInfo.customerId,
    searchString,
  );
  const [records, resetRecordList, fetchMoreRecordList] = useAppointRecordsList(
    userInfo.customerId,
  );

  const searchEquipment = () => {
    setSearchString(search.value);
  };
  const appointingEquipmentHandle = (deviceCode: string) => {
    Taro.showLoading({
      title: '',
      mask: true,
    });
    return appointingEquipment({
      account: userInfo.hardwareAccount,
      phone: userInfo.customerPhone,
      userId: userInfo.customerId,
      userName: userInfo.customerName,
      deviceCode: deviceCode,
    })
      .then(res => {
        setRecordId(res.data);
      })
      .catch(err => {
        Taro.hideLoading();
        Taro.showToast({
          title: err.msg || '网络错误',
          icon: 'none',
          duration: 2000,
        });
        console.log(err);
      });
  };
  const startLoopFetchResult = () => {
    if (loopResultState) {
      let intervalTime = 1000;
      fetchAppointResult({
        userId: userInfo.customerId,
        recordId,
      })
        .then(res => {
          if (res.data === AppointResultRes.appointting) {
            setTimeout(() => {
              startLoopFetchResult();
            }, intervalTime);
          } else {
            setLoopResultState(false);
            if (res.data === AppointResultRes.appointFail) {
              Taro.showToast({
                title: res.msg || '预约失败',
                icon: 'none',
                duration: 2000,
              });
            } else if (res.data === AppointResultRes.appointSuccess) {
              Taro.showToast({
                title: res.msg || '预约成功',
                duration: 2000,
              });
            }
          }
        })
        .catch(err => {
          console.log(err);
          setTimeout(() => {
            startLoopFetchResult();
          }, intervalTime);
        });
    } else {
      Taro.showToast({
        title: '请求超时',
        icon: 'none',
        duration: 2000,
      });
    }
  };

  useEffect(() => {
    if (recordId && showState === 2) {
      resetRecordList();
      setRecordId(0);
    }
  }, [recordId, showState]);
  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;
    if (recordId) {
      setLoopResultState(true);
      timer = setTimeout(() => {
        setLoopResultState(false);
      }, 30000);
    }
    return () => {
      timer && clearTimeout(timer);
    };
  }, [recordId]);
  useEffect(() => {
    if (loopResultState) {
      startLoopFetchResult();
    }
  }, [loopResultState]);

  const appointingStart = (
    deviceCode: string,
    operationMode: number,
    location: string,
  ) => {
    const thresholdValue = showerControlConfig.thresholdValue;
    if (showerControlConfig.balances.length) {
      let aimiItem = showerControlConfig.balances.find(
        item => item.serviceId === '0',
      );
      let aimi = aimiItem ? aimiItem.amount : 0;
      let beanItem = showerControlConfig.balances.find(
        item => item.serviceId === '1',
      );
      let bean = beanItem ? beanItem.amount : 0;
      let money = operationMode === OperationMode.onlyAimi ? aimi : aimi + bean;

      if (money < thresholdValue) {
        let i = 0;
        let text = showerControlConfig.appointmentThresholdPrompt.replace(
          /\{\}/g,
          () => {
            return i++ == 0 ? aimi.toFixed(2) : bean.toFixed(2);
          },
        );
        Taro.showModal({
          title: '提示',
          content: text,
        }).then(res => {
          if (res.confirm) {
            beforeStartCheckHandle(deviceCode, location);
          }
        });
        return;
      }
    }
    beforeStartCheckHandle(deviceCode, location);
  };
  const goBluetoothShower = () => {
    Taro.redirectTo({
      url: '/pages/Shower/Shower',
    });
  };
  const beforeStartCheckHandle = (deviceCode: string, location: string) => {
    let minData = appointableData.duration / 60;
    let hourData = appointableData.punishment / 3600;
    Taro.showModal({
      title: '提示',
      content: `确认是否预约${deviceCode}(${location})预约后请在${minData}分钟内激活设备使用,否则将会在${hourData}小时内无法预约设备,`,
    }).then(res => {
      if (res.confirm) {
        appointingEquipmentHandle(deviceCode);
      }
    });
  };

  return (
    <View className='ShowerAppointment'>
      <AppBackButton />
      <WaitPayOrderComponent />
      {showState == 1 && (
        <View className='ShowerAppointment-Searchbox'>
          <Input
            placeholder='请输入要筛选的设备位置'
            value={search.value}
            onInput={e => search.onChange(e)}
          />
          <Text
            className='ShowerAppointment-Searchbox-btn'
            onClick={searchEquipment}>
            开始筛选
          </Text>
        </View>
      )}
      {showState == 1 && showerControlConfig.balances.length && (
        <View className='ShowerAppointment-Account'>
          {showerControlConfig.balances.map(item => (
            <View
              key={item.serviceId}
              className='ShowerAppointment-Account-item'>
              <Text className='name'>{item.serviceName}</Text>
              <Text>{item.amount.toFixed(2)}</Text>
            </View>
          ))}
        </View>
      )}
      {showState == 1 && (
        <View className='ShowerAppointment-Content'>
          <View className='ShowerAppointment-Equipment-title'>设备列表</View>
          <View className='ShowerAppointment-Equipment-info'>
            {appointableData.message}
          </View>
          {list.map(item => (
            <AppointermentEquipment
              key={item.code}
              data={item}
              disabled={appointableData.appointMode === 3}
              appointingStart={appointingStart}
            />
          ))}
        </View>
      )}
      {showState == 1 && showerControlConfig.useType === ShowerUseType.mix && (
        <View
          className='ShowerAppointment-ToggleBtn'
          onClick={goBluetoothShower}>
          自助洗浴
        </View>
      )}
      {showState == 2 && (
        <ScrollView
          className='ShowerAppointment-AppointmentList'
          scrollY
          scrollWithAnimation
          lowerThreshold={50}
          onScrollToLower={fetchMoreRecordList}>
          {records.length ? (
            records.map(item => (
              <AppointermentCard key={item.deviceCode} data={item} />
            ))
          ) : (
            <View className='ShowerAppointment-EmptyBox'>
              <Image className='ShowerAppointment-EmptyIcon' src={EmptyIcon} />
              暂无预约记录~
            </View>
          )}
        </ScrollView>
      )}

      <View className='ShowerAppointment-Footer'>
        <View
          className={`ShowerAppointment-Footer-item ${
            showState == 1 ? 'actived' : ''
          }`}
          onClick={() => setShowState(1)}>
          洗浴预约
        </View>
        <View
          className={`ShowerAppointment-Footer-item ${
            showState == 2 ? 'actived' : ''
          }`}
          onClick={() => setShowState(2)}>
          预约记录
        </View>
      </View>
    </View>
  );
}
ShowerAppointment.onPullDownRefresh = () => {
  console.log('in onPullDownRefresh');
};

ShowerAppointment.config = {
  navigationBarBackgroundColor: '#486dec',
  navigationBarTitleText: '',
  backgroundColor: '#486dec',
};
export default ShowerAppointment;
