import { StandardProps } from '@tarojs/components/types/common';
import { View, Image, Text } from '@tarojs/components';
import './charging.scss';
// import chargingImage from '@/assets/images/charging/charging.gif'
import { AtButton } from 'taro-ui';
import { RzIcon } from '@/components/RzIcon/RzIcon';
import {
  useEffect,
  useRouter,
  useState,
  useCallback,
  useDidShow,
} from '@tarojs/taro';
import {
  queryEquipmentStatus,
  QueryEquipmentStatusRes,
  stopCharge,
  getDefaultCar,
  isThirdPartyStation,
} from '@/services/charging';
import { showModal, showModalOnlyWithConfirmBtn } from '@/utils/wechat-ui';
import classNames from 'classnames';
import {
  contact,
  getUserInfoFromStorage,
  scanCodeAndNavToConfirmFee,
} from '@/utils/utils';
import { events } from '@/utils/event-bus';
import imgCharging from '@/assets/images/charging/img_charging.gif';

type ChargingProps = {} & StandardProps;
export const Charging: Taro.FC<ChargingProps> = () => {
  const router = useRouter();
  const [defaultCar, setDefaultCar] = useState('');
  const [userType, setUserType] = useState('1');
  const [selectedCar, setSelectedCar] = useState('');
  const [getTicketMsg, setGetTicketMsg] = useState('');

  const [realTimeInfo, setRealTimeInfo] = useState<QueryEquipmentStatusRes>({
    chargeCurSoc: 0,
    chargeDuration: 0,
    chargeDegree: 0,
    chargeBalance: 0,
    chargePower: 0,
    chargeCurr: 0,
    chargeVolt: 0,
    equipmentSn: '--',
    connectorSn: '--',
    connectorNo: 1,
    equipmentName: '--',
    equipmentNo: 1,
    equipmentType: 1,
    chargeOrderNo: '--',
    orderState: 2,
    continueChargeFlag: false,
    equipmentId: 1,
    isBarrierFlag: 0,
    stationName: '',
  });

  const getRealtimeInfo = useCallback(async () => {
    const res = await queryEquipmentStatus({
      orderNo: router.params.orderNo,
      connectorSn: router.params.connectorSn,
    });
    if (res) {
      setRealTimeInfo(res);
      if (res.orderState !== 2) {
        Taro.redirectTo({
          url: `/pages/order-detail/order-detail?isFromCharging=${true}&orderNo=${router.params.orderNo
            }`,
        });
      }
    }
  }, [router]);

  events.on('onSelectedCar', (plateNo) => {
    setSelectedCar(plateNo);
  });

  //TODO: 需要判断这笔订单是否领取领取停车券的接口
  //TODO: selectedCar 变化就去调用领券方法
  useEffect(() => {
    console.log('selectedCar', selectedCar);
  }, [selectedCar]);

  useEffect(() => {
    getRealtimeInfo();
    const id = setInterval(async () => {
      getRealtimeInfo();
    }, 5000);
    return () => clearInterval(id);
  }, [getRealtimeInfo]);

  useDidShow(() => {
    getUserInfoFromStorage().then((res) => {
      setUserType(res.userType);
      if (res.userType === '1' && realTimeInfo.isBarrierFlag === 1) {
        getDefaultCar().then((res) => {
          if (res) {
            setDefaultCar(res.plateNo);
          }
        });
      }
    });
  });

  const handleStop = async () => {
    const res = await showModal(
      '提示',
      '确定要停止充电吗？请停止充电后将充电枪放回原位。'
    );
    if (res.confirm) {
      const { equipmentSn, connectorNo, equipmentId } = realTimeInfo;
      const stopRes = await stopCharge({
        equipmentSn,
        connectorNo,
        equipmentId,
        orderNo: router.params.orderNo,
      });
      if (stopRes) {
        //是否为合作道闸车场，如果是有免费停车时长，跳转到选车界面
        const freeTimeRes = await isThirdPartyStation({
          order_no: router.params.orderNo,
        });

        if (freeTimeRes.success) {
          const freeRes = await showModalOnlyWithConfirmBtn(
            '提示',
            '请输入车辆信息领取免费停车时长！'
          );
          if (freeRes.confirm) {
            Taro.redirectTo({
              url: `/pages/select-free-plate/select-free-plate?order_no=${router.params.orderNo}`,
            });
          }
        } else {
          Taro.redirectTo({
            url: `/pages/order-detail/order-detail?isFromCharging=${true}&orderNo=${router.params.orderNo}`,
          });
        }
      }
    }
  };

  const handleContinueCharge = () => {
    scanCodeAndNavToConfirmFee();
  };

  const handleNavToMyCar = () => {
    Taro.navigateTo({ url: `/pages/my-car/my-car` });
  };

  const handleNavToMyCarToSelectCar = () => {
    Taro.navigateTo({ url: `/pages/my-car/my-car?isSelectCar=${true}` });
  };

  return (
    <View className="charging">
      {getTicketMsg && (
        <View className="charging__tip">
          <RzIcon value="warning" color="#FF6584" size="17"></RzIcon>
          {userType === '1' ? (
            <Text className="charging__tip-text">
              {defaultCar + getTicketMsg}
            </Text>
          ) : (
            <Text className="charging__tip-text">
              {selectedCar + getTicketMsg}
            </Text>
          )}
        </View>
      )}
      <View className="charging__title1">
        <Text className="charging__title-text">
          站点名称：{realTimeInfo.stationName}
        </Text>
      </View>
      <View className="charging__title">
        <Text className="charging__title-text">
          枪号：{realTimeInfo.equipmentNo}号桩 {realTimeInfo.connectorNo}号枪
        </Text>
        <Text className="charging__title-text">
          桩号：{realTimeInfo.equipmentSn}
        </Text>
      </View>
      <View className="charging__title2">
        <Text className="charging__title-text">
          订单号：{realTimeInfo.chargeOrderNo}
        </Text>
      </View>

      {realTimeInfo.equipmentType === 1 ? (
        <View className="charging__soc">
          <Text className="charging__soc-text">
            {realTimeInfo.chargeCurSoc}
          </Text>
          <Text className="charging__unit">%</Text>
        </View>
      ) : (
        <View className="charging__slow">
          <Text className="charging__slow-text">充电中</Text>
        </View>
      )}
      <Image
        className="charging__animation"
        src={imgCharging}
        mode="widthFix"></Image>
      {realTimeInfo.isBarrierFlag === 1 &&
        (userType === '1' ? (
          <View>
            <View className="charging__plate" onClick={handleNavToMyCar}>
              <Text className="charging__plate-text">
                {defaultCar ? defaultCar : '设置车牌'}
              </Text>
            </View>
            {/* <View className="charging__plate">
              <Text className="charging__plate-tip">
                {defaultCar
                  ? '充电结束将自动获得停车券'
                  : '设置车牌，充电结束将自动获得停车券'}
              </Text>
            </View> */}
          </View>
        ) : (
          <View>
            <View
              className="charging__plate"
              onClick={handleNavToMyCarToSelectCar}>
              <Text className="charging__plate-text">
                {selectedCar ? selectedCar : '选择车辆领取停车券'}
              </Text>
            </View>
            {/* <View className="charging__plate">
              <Text className="charging__plate-tip">
                {selectedCar
                  ? '充电结束将自动获得停车券'
                  : '选择车牌，充电结束将自动获得停车券'}
              </Text>
            </View> */}
          </View>
        ))}

      <View className="realtime-info">
        <View className="grid">
          {[
            { name: '时长/分', value: realTimeInfo.chargeDuration },
            { name: '度数/度', value: realTimeInfo.chargeDegree },
            { name: '费用/元', value: realTimeInfo.chargeBalance },
            { name: '功率/千瓦', value: realTimeInfo.chargePower },
            { name: '电流/安', value: realTimeInfo.chargeCurr },
            { name: '电压/伏', value: realTimeInfo.chargeVolt },
          ].map((item) => {
            return (
              <View className="grid__item" key={item.name}>
                <Text className="grid__item-value">{item.value}</Text>
                <Text className="grid__item-unit">{item.name}</Text>
              </View>
            );
          })}
        </View>
        <View className="feedback" onClick={() => contact()}>
          联系客服
        </View>
        <View className="btn-box">
          {realTimeInfo.continueChargeFlag && (
            <AtButton
              className="btn"
              type="primary"
              circle
              onClick={handleContinueCharge}>
              继续充电
            </AtButton>
          )}
          <AtButton
            className={classNames(
              { btn: realTimeInfo.continueChargeFlag },
              'btn--wide'
            )}
            type={realTimeInfo.continueChargeFlag ? 'secondary' : 'primary'}
            circle
            onClick={handleStop}>
            结束充电
          </AtButton>
        </View>
      </View>
    </View>
  );
};

Charging.config = {
  navigationBarTitleText: '充电中',
};
