import './AppointmentPay.scss';
import { View, Image } from '@tarojs/components';
import WasherDevice from './components/WasherDevice';
import WxIcon from '../../images/washingmachine/pay_wechat_icon@2x.png';
import Taro, { useEffect, useState } from '@tarojs/taro';
import { useSelector } from '@tarojs/redux';
import { Customer } from '@/types/Customer/Customer';
import useCountDown from '@/hooks/useCountDown';
import { WasherStoreState } from '@/store/rootReducers/washer';
import { payWasherOrder } from '@/api/washingMachine';
import { formatePayString } from '@/utils/pay';
import useWasherStart from './hooks/useWasherStart';

const AppointmentPay = () => {
  const orderData = useSelector(
    (state: { washer: WasherStoreState }) => state.washer.orderInfo
  );
  const userInfo = useSelector(
    (state: { userinfo: Customer }) => state.userinfo
  );
  const count = useCountDown(orderData.payTimeout);
  const [deviceCode, setDeviceCode] = useState('');

  const { wsState, bluetoothState } = useWasherStart(deviceCode);
  const payStartHandle = () => {
    if (orderData.orderType === 1) {
      Taro.showLoading({
        title: '开启中。。。',
        mask: true,
      });
      setDeviceCode(orderData.deviceCode);
    } else {
      payHandle();
    }
  };
  const payHandle = () => {
    console.log('in payHandle');
    Taro.showLoading();
    payWasherOrder({
      orderCode: orderData.orderCode,
    })
      .then(res => {
        console.log(res.data);
        Taro.hideLoading();
        const { payStr } = res.data;
        if (payStr) {
          let payData = formatePayString(payStr, userInfo.customerId);
          Taro.requestPayment({
            timeStamp: payData.timeStamp.toString(),
            nonceStr: payData.nonceStr,
            package: payData.package,
            signType: payData.signType,
            paySign: payData.paySign,
          })
            .then(res => {
              console.log(res);
              goBackWasherHome();
            })
            .catch(err => {
              Taro.showToast({
                title: err.errMsg || '呼起支付失败',
                icon: 'none',
              });
            });
        } else {
          goBackWasherHome();
        }
      })
      .catch(err => {
        Taro.hideLoading();
        console.log(err);
        Taro.showToast({
          title: err.msg || '请求支付失败',
          icon: 'none',
        });
      });
  };
  const goBackWasherHome = () => {
    Taro.navigateBack({
      delta: 2,
    });
  };

  useEffect(() => {
    console.log(wsState.socketState, bluetoothState);
    if (wsState.socketState && bluetoothState) {
      Taro.hideLoading();
      payHandle();
    }
  }, [wsState.socketState, bluetoothState]);

  return (
    <View className='AppointmentPay'>
      <View className='AppointmentPay-content'>
        <WasherDevice
          data={{
            deviceCode: orderData.deviceCode,
            postion: orderData.position,
          }}
        />
        <View className='AppointmentPay-contentItem'>
          <View className='AppointmentPay-contentTitle'>
            <View className='AppointmentPay-contentName'>洗衣功能</View>
            <View className='AppointmentPay-contentValue'>
              {orderData.services.map(service => (
                <View
                  key={service.id}
                  className='AppointmentPay-contentValueItem'
                >
                  {service.name}-{service.duration}分钟
                </View>
              ))}
            </View>
          </View>
          <View className='AppointmentPay-Price'>
            合计: {orderData.money.toFixed(2)}元
          </View>
        </View>
        <View className='AppointmentPay-contentItem'>
          <View className='AppointmentPay-contentTitle'>
            <View className='AppointmentPay-contentName'>支付方式</View>
            <View className='AppointmentPay-contentValue'>
              <View className='AppointmentPay-contentPayicon'>
                <Image src={WxIcon} />
              </View>
              {orderData.paymentWayId === 6 ? (
                <View>艾米支付</View>
              ) : (
                <View>豆支付</View>
              )}
            </View>
          </View>
        </View>
        {orderData.appointmentTimeout && (
          <View className='AppointmentPay-Tips'>
            注：本次支付为预约设备功能使用费用，预约时间为
            {orderData.appointmentTimeout}
            分钟，超出预约时间，费用不退还，请仔细阅读。
          </View>
        )}
        <View className='AppointmentPay-CountDown'>
          {count ? `请在${count}秒内完成支付` : '已超时，请重新下单'}
        </View>
      </View>

      {count ? (
        <View className='AppointmentPay-footer' onClick={payStartHandle}>
          {orderData.orderType === 2 ? '预约支付' : '确认支付'}
        </View>
      ) : (
        <View className='AppointmentPay-footer disabled'>
          {orderData.orderType === 2 ? '预约支付' : '确认支付'}
        </View>
      )}
    </View>
  );
};
AppointmentPay.config = {
  navigationBarBackgroundColor: '#f9faff',
  navigationBarTitleText: '洗衣预约',
};
export default AppointmentPay;
