import Taro, {
  useState,
  useShareAppMessage,
  useDidHide,
  useCallback,
  useReachBottom,
  useDidShow,
  useEffect,
  useRouter,
} from '@tarojs/taro';
import { ScrollView, View, Text, Button } from '@tarojs/components';
import './index.scss';
import { AtTabBar } from 'taro-ui';
import chargeUnselect from '@/assets/images/icon/charge_unselect.png';
import chargeSelected from '@/assets/images/icon/charge_selected.png';
import mineUnselect from '@/assets/images/icon/mine_unselect.png';
import mineSelected from '@/assets/images/icon/mine_selected.png';
import { RzScanBtn } from '@/components/RzScanBtn/RzScanBtn';
import { Charge } from './components/Charge/Charge';
import { Mine } from './components/Mine/Mine';
import { queryUserOrder, OrderItemType } from '@/services/order-list';
import { huangHaiTest } from '@/services/common';

import {
  queryEquipmentStatus,
  QueryEquipmentStatusRes,
} from '@/services/charging';
import { checkIsLogin, scanCodeAndNavToConfirmFee } from '@/utils/utils';
import { addFeedback } from '@/services/feedback';
import { showSuccessToast } from '@/utils/wechat-ui';
// import { events } from '@/utils/event-bus';
// import { showToast } from '@/utils/wechat-ui';

let timer: NodeJS.Timeout;
export default function Index() {
  const [currentOrder, setCurrentOrder] = useState<OrderItemType | null>(null);
  const [
    realTimeInfo,
    setRealTimeInfo,
  ] = useState<QueryEquipmentStatusRes | null>(null);
  const [orderNum, setOrderNum] = useState(0);

  const [tapState, setTtapState] = useState<string>('');
  const [SwitchState, setSwitchState] = useState<boolean>(false);

  const getRealtimeInfo = async (currentOrder: OrderItemType) => {
    console.log('getRealtimeInfo -> currentOrder', currentOrder);
    const res = await queryEquipmentStatus({
      orderNo: currentOrder.orderNo,
      connectorSn: currentOrder.connectorSn,
    });

    if (res) {
      setRealTimeInfo(res);
      if (res.orderState !== 2) {
        clearInterval(timer);
        setRealTimeInfo(null);
      }
    }
  };

  const handleHuanghai = async () => {
    // const res = await huangHaiTest();
    // console.log(res.data[0].columns.dictValue);

    Taro.navigateTo({ url: `/pages/test/test` });

    // Taro.navigateTo({
    //   url: `/pages/labor-union/labor-union`,
    // });
  };



  const router = useRouter();
  useEffect(() => {

    let tabs = router.params.tab_active;
    setTtapState(tabs);
    if (tabs == '1') {
      console.log('setCurrent', tabs);
      handleTabBarChange(1);
      setSwitchState(true);
      setTtapState('3');
    }
  }, []);

  const [tab_active, settab_active] = useState(false);
  const handleCloseSwitchState = () => {
    setSwitchState(false);
  };
  useDidShow(async () => {
    if (checkIsLogin()) {

      const userOrderRes = await queryUserOrder({
        pageNum: 1,
        pageSize: 100,
        type: 2,
      });
      if (userOrderRes) {
        if (userOrderRes.list.length > 0) {
          setCurrentOrder(userOrderRes.list[0]);
          getRealtimeInfo(userOrderRes.list[0]);
          setOrderNum(userOrderRes.list.length);
          timer = setInterval(async () => {
            getRealtimeInfo(userOrderRes.list[0]);
          }, 5000);
        } else {
          setCurrentOrder(null);
          setRealTimeInfo(null);
          setOrderNum(0);
        }
      }
    }
  });

  const handleNavToCharging = () => {
    if (currentOrder) {
      Taro.navigateTo({
        url: `/pages/charging/charging?orderNo=${currentOrder.orderNo}&connectorSn=${currentOrder.connectorSn}`,
      });
    }
  };

  // const [scrollIntoView, setScrollIntoView] = useState(0);
  // events.on('navFromMap', () => {
  //   setScrollIntoView(217);
  // });
  useShareAppMessage(() => {
    return {
      title: '驿来特PLUS',
      path: '/pages/index/index',
      imageUrl: 'https://i100c.oss-cn-beijing.aliyuncs.com/ylt/ylt_share.png',
    };
  });
  useDidHide(() => {
    // setScrollIntoView(0);
    clearInterval(timer);
  });
  const [current, setCurrent] = useState(0); //当前tab
  const [isReachBottom, setIsReachBottom] = useState(false);
  // const [isPulling, setIsPulling] = useState(false);
  const handleScanBtnClick = () => {
    scanCodeAndNavToConfirmFee();
  };
  const handleScrollToLower = () => {
    console.log('handleScrollToLower');
    setIsReachBottom(true);
  };

  useReachBottom(() => {
    console.log('object');
    handleScrollToLower();
  });

  // const handlePulling = () => {
  //   setIsPulling(true);
  // };

  const handleTabBarChange = (value: number) => {
    setCurrent(value);
    if (value === 1) {
      Taro.setNavigationBarTitle({ title: '我的' });
    } else {
      Taro.setNavigationBarTitle({ title: '首页' });
    }
  };

  const handleComplete = useCallback(() => setIsReachBottom(false), []);
  // const handlePullingComplete = useCallback(() => {
  //   setTimeout(() => {
  //     setIsPulling(false);
  //   }, 1500);
  // }, []);

  const currentTabElement = current ? (
    // <Mine isPulling={isPulling} onPullingComplete={handlePullingComplete} />
    <Mine
      orderNum={orderNum}
      getSwitchState={SwitchState}
      checkState={handleCloseSwitchState}
    />
  ) : (
    <Charge isReachBottom={isReachBottom} onComplete={handleComplete} />
  );

  return (
    <View>
      {/* <ScrollView
        scrollY
        className="index"
        scrollTop={scrollIntoView}
        onRefresherPulling={handlePulling}
        refresherTriggered={isPulling}
        refresherEnabled
        refresherThreshold={90}
        onScrollToLower={handleScrollToLower}>
        {currentTabElement}
      </ScrollView> */}
      {/* <Button size='mini' onClick={handleHuanghai}>按钮</Button> */}
      <View className="index">{currentTabElement}</View>
      <AtTabBar
        fixed
        tabList={[
          {
            title: '首页',
            image: chargeUnselect,
            selectedImage: chargeSelected,
          },
          { title: '我的', image: mineUnselect, selectedImage: mineSelected },
        ]}
        iconSize={22}
        color="#333"
        selectedColor="#333"
        onClick={(value) => handleTabBarChange(value)}
        current={current}
      />
      {realTimeInfo ? (
        <View className="current-order" onClick={handleNavToCharging}>
          <Text className="current-order__txt">
            {realTimeInfo.equipmentType === 1
              ? realTimeInfo.chargeCurSoc + '%'
              : '充电中'}
          </Text>
        </View>
      ) : (
        <RzScanBtn className="scan-btn" onClick={handleScanBtnClick} />
      )}
    </View>
  );
}
Index.config = {
  navigationBarTitleText: '首页',
};
