import './AppLaunch.scss';
import { View, Button } from '@tarojs/components';
import Taro, { useEffect, useState } from '@tarojs/taro';
import { fetchAppLaunchCustomer } from '@/api/customer';
import { LogoutCode } from '@/constants';
import { useDispatch } from '@tarojs/redux';
import { updateUserInfo } from '@/store/rootReducers/userinfo';
import AppBackButton from '@/components/AppBackButton/AppBackButton';
import useShowerController from '@/hooks/useShowerController';

function AppLaunch() {
  const dispatch = useDispatch();
  const setGoMethod = useShowerController();
  const goNextPage = (serviceId: string) => {
    let url = '';
    switch (serviceId) {
      case '9':
        url = '/pages/WaterDispenser/WaterDispenser';
        break;
      case '10':
        setGoMethod('redirectTo');
        return;
      case '11':
      case '12':
        url = `/pages/BarCode/BarCode?serviceId=${serviceId}`;
        break;
      default:
        console.log('goNextPage serviceId: ' + serviceId);
        Taro.showToast({
          title: '无法识别的服务',
          icon: 'none',
        });
        break;
    }
    if (url) {
      Taro.redirectTo({ url });
    }
  };
  const [showBackButtonState, setShowBackButtonState] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');

  useEffect(() => {
    console.log('AppLaunch', this.$router.params);
    let entity = this.$router.params;
    Taro.showLoading();
    const { uuId, serviceId } = entity;
    if (uuId && serviceId) {
      Taro.login()
        .then(res => fetchAppLaunchCustomer({ ...entity, code: res.code }))
        .then(res => {
          console.log(res);
          Taro.hideLoading();
          dispatch(updateUserInfo(res.data));
          goNextPage(serviceId);
        })
        .catch(err => {
          Taro.hideLoading();
          let msg = err.msg || '请求失败';
          Taro.showToast({
            title: msg,
            icon: 'none',
          });
          if (err.code !== LogoutCode) {
            setErrorMsg(msg);
            setShowBackButtonState(true);
          }
        });
    } else {
      Taro.hideLoading();
      console.log('no uuid');
      setErrorMsg('进入小程序参数错误');
      setShowBackButtonState(true);
    }
  }, []);

  const goBackAppError = e => {
    console.log(e);
    Taro.showModal({
      title: '提示',
      content: '呼起APP失败,请手动回到APP',
    });
  };

  return (
    <View className='AppLaunch'>
      <View className='AppLaunch-Message'>{errorMsg}</View>
      {showBackButtonState && (
        <Button
          open-type='launchApp'
          app-parameter='wechat'
          onError={goBackAppError}>
          返回APP
        </Button>
      )}
    </View>
  );
}

export default AppLaunch;
