/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable no-underscore-dangle */
import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import {
  StyleSheet,
  View,
  Clipboard,
  Dimensions,
  Animated,
  PanResponder,
  findNodeHandle,
  UIManager,
  TouchableOpacity,
} from 'react-native';
import { Div, Button, Image, Text } from 'react-native-magnus';
import { Appbar, Menu } from 'react-native-paper';
import Constants from 'expo-constants';

import { Flex } from '@ant-design/react-native';
import { ScrollView } from 'react-native-gesture-handler';

import { useRequest, useCreation, useMount } from '@umijs/hooks';
import { useTranslation } from 'react-i18next';

import { useRoute } from '@react-navigation/native';
import { useAnimation } from 'react-native-animation-hooks';
import useModel from 'flooks';
import Toast from '../../flooks/Toast';

import Header from './Header'; // 头部

import { connectKefu } from '../../Utils/TotastUtils';
import {
  merchantStatusMap,
  orderStatusMap,
  RiderStatusMap,
  payMap,
  reasonMap,
  getStatusInfo,
} from '../../Utils/OrderUtils';
import Time from '../../Utils/TimeUtils';

import MapScreen from '../Map/MapScreen';

export default function OrderScreen({ navigation }) {
  const { t } = useTranslation();
  const [orderInfo, setorderInfo] = React.useState({
    merchant: {},
    orderGoodsSpecs: [],
  });

  const { loading, success, warnning, clearLoading } = useModel(Toast, []);

  const route = useRoute();
  const { params } = route;
  const { orderId } = params || 0;

  const orderRequest = useRequest(`/orderInfo/get/${orderId}`, {
    refreshDeps: [orderId],
    onSuccess: (result) => {
      setorderInfo(result);
    },
  });

  const { merchant, orderGoodsSpecs } = orderInfo;

  const statusInfo = useCreation(() => {
    return getStatusInfo(orderInfo);
  }, [orderInfo]);

  const finish = useCreation(() => {
    if (
      orderInfo.riderStatus === 'CARRY_OUT' ||
      orderInfo.status === 'CANCELLED'
    ) {
      return true;
    } else {
      return false;
    }
  }, [orderInfo]);

  const cancelOrder = useCreation(() => {
    if (orderInfo.status === 'CANCELLED') {
      return true;
    } else {
      return false;
    }
  }, [orderInfo, statusInfo]);

  const Allfinish = useCreation(() => {
    if (orderInfo.status === 'COMPLETED') {
      return true;
    } else {
      return false;
    }
  }, [orderInfo]);

  const isPay = useCreation(() => {
    if (orderInfo.status === 'UNPAID') {
      return false;
    } else {
      return true;
    }
  }, [orderInfo]);

  const hasRider = useCreation(() => {
    if (orderInfo.riderStatus !== 'NOT_RECEIVED' && orderInfo.riderStatus) {
      return true;
    } else {
      return false;
    }
  });

  const detailRef = React.useRef();
  const pan = React.useRef(new Animated.ValueXY()).current;
  const minMove = React.useRef(new Animated.Value(0)).current;
  const maxMove = React.useRef(
    new Animated.Value(Dimensions.get('window').height * 0.6)
  ).current;
  const panResponder = React.useRef(
    PanResponder.create({
      onMoveShouldSetPanResponder: () => {
        console.log('a2');
        return false;
      },
      onMoveShouldSetPanResponderCapture: () => false,
      onStartShouldSetPanResponder: () => {
        console.log('a1');
        return true;
      },
      onStartShouldSetPanResponderCapture: () => false,
      onResponderTerminationRequest: () => true,
      onPanResponderGrant: () => {
        pan.setOffset({
          y: pan.y._value,
        });
      },
      onPanResponderMove: (e, ges) => {
        const y = ges.dy + pan.y._offset;
        if (y >= minMove._value && y <= maxMove._value) {
          pan.setValue({
            y: ges.dy,
          });
        } else if (y < minMove._value) {
          pan.setValue({
            y: minMove._value - pan.y._offset,
          });
        } else {
          pan.setValue({
            y: maxMove._value - pan.y._offset,
          });

          if (ges.moveY > 500) {
            orderRequest.run();
          }
        }

        if (maxMove._value !== 0) {
          if (maxMove._value - y < 200) {
            setbackgorundColor(
              `rgba(255, 194, 28,${Math.ceil(
                (1 / 200) * (maxMove._value - y)
              )})`
            );
            setshowDetail(false);
          } else {
            setbackgorundColor('#FFC21C');
            setshowDetail(true);
          }
        }
      },
      onPanResponderRelease: () => {
        pan.flattenOffset();
      },
    })
  ).current;

  React.useEffect(() => {
    if (finish || statusInfo.isRefund) {
      maxMove.setValue(0);
      pan.setValue({
        y: 0,
      });
      setshowDetail(true);
      setbackgorundColor('#FFC21C');
    } else {
      maxMove.setValue(Dimensions.get('window').height * 0.6);
      pan.setValue({
        y: Dimensions.get('window').height * 0.6,
      });
      setshowDetail(false);
    }
  }, [finish, statusInfo]);

  const [backgorundColor, setbackgorundColor] = React.useState(
    'rgba(255, 194, 28,0)'
  );

  const [showDetail, setshowDetail] = React.useState(false);

  React.useEffect(() => {
    if (orderRequest.loading) {
      loading();
    } else {
      clearLoading();
    }
  }, [orderRequest.loading]);

  return (
    <Div bg="gray200" w="100%" flex={1}>
      <Header
        title={showDetail ? statusInfo.name : ' '}
        bg={backgorundColor}
        orderId={orderId}
        hasRight={!finish && !Allfinish && !cancelOrder && !statusInfo.isRefund}
      />

      {/* <RefreshControl
        refreshing={orderRequest.loading}
        onRefresh={orderRequest.run}
      > */}
      {!finish && !statusInfo.isRefund && (
        <Div
          w={Dimensions.get('window').width}
          h={Dimensions.get('window').height + Constants.statusBarHeight}
          position="absolute"
          top={0}
          left={0}
          zIndex={1}
        >
          <MapScreen orderInfo={orderInfo} />
        </Div>
      )}

      <Animated.View
        ref={detailRef}
        style={{
          zIndex: 2,
          backgroundColor: 'rgba(0,0,0,0)',
          transform: [{ translateY: pan.y }],
        }}
        onLayout={({ nativeEvent }) => {
          minMove.setValue(
            Dimensions.get('window').height -
              nativeEvent.layout.height -
              nativeEvent.layout.y -
              Constants.statusBarHeight
          );
        }}
      >
        <View {...panResponder.panHandlers}>
          <Div pt={10} pb={10} px={15}>
            {/* <Text>{statusInfo.name}</Text> */}
            <Button
              block
              bg="hide"
              p={0}
              onPress={() =>
                navigation.navigate('OrderDetailList', {
                  orderId,
                })
              }
            >
              <Div flex={1}>
                <View style={[styles.card]}>
                  {!cancelOrder &&
                    !statusInfo.isRefund &&
                    (finish ? (
                      <Text fontSize="xl">
                        <Text
                          fontSize="xl"
                          color="brand500"
                          mr={10}
                          fontWeight="bold"
                        >
                          {statusInfo.name}
                        </Text>
                        {new Time(
                          orderInfo.userReceivedTime,
                          'yyyy-MM-DD HH:mm:ss'
                        ).getFormat('HH:mm')}
                        {t('song-da')}
                      </Text>
                    ) : (
                      <Text fontSize="xl">
                        <Text
                          fontSize="xl"
                          color="brand500"
                          mr={10}
                          fontWeight="bold"
                        >
                          {statusInfo.name}
                        </Text>
                        {t('yu-ji')}
                        {new Time(
                          orderInfo.timeOfArrival,
                          'yyyy-MM-DD HH:mm:ss'
                        ).getFormat('HH:mm')}
                        {t('song-da')}
                      </Text>
                    ))}
                  {cancelOrder && (
                    <Div row>
                      <Text
                        fontSize="xl"
                        color="brand500"
                        mr={10}
                        fontWeight="bold"
                      >
                        {statusInfo.name}
                      </Text>
                      {!!orderInfo.reason && (
                        <Text fontSize="xl" color="red500">
                          ({reasonMap.get(orderInfo.reason).name})
                        </Text>
                      )}
                    </Div>
                  )}
                  <Div row mt={10}>
                    <Button
                      fontSize="xs"
                      flex={1}
                      mx={5}
                      bg="white"
                      color="gray600"
                      borderColor="brand500"
                      borderWidth={1}
                      rounded={3}
                      onPress={() => connectKefu(orderId)}
                    >
                      {t('lian-xi-ke-fu')}
                    </Button>

                    {/* <Button
                      fontSize="xs"
                      flex={1}
                      mx={5}
                      bg="white"
                      color="gray600"
                      borderColor="brand500"
                      borderWidth={1}
                      rounded={3}
                      onPress={() => connectKefu(orderId)}
                    >
                      立即支付
                    </Button> */}

                    {!finish && hasRider && (
                      <Button
                        fontSize="xs"
                        flex={1}
                        mx={5}
                        bg="white"
                        color="gray600"
                        borderColor="brand500"
                        borderWidth={1}
                        rounded={3}
                        onPress={(e) => {
                          if (!orderInfo.ruserId) {
                            warnning('骑手信息有误请联系客服');
                          } else {
                            navigation.navigate('Chat', {
                              toUserId: orderInfo.ruserId,
                              toUserName: orderInfo.riderName,
                            });
                          }
                          console.log(e);
                        }}
                      >
                        {t('lian-xi-qi-shou')}
                      </Button>
                    )}
                    {!finish && isPay && !statusInfo.isRefund && !cancelOrder && (
                      <Button
                        fontSize="xs"
                        flex={1}
                        mx={5}
                        bg="white"
                        color="gray600"
                        borderColor="brand500"
                        borderWidth={1}
                        rounded={3}
                        onPress={() => {
                          if (!orderInfo.muserId) {
                            warnning('商家信息有误请联系客服帮你催单');
                          } else {
                            navigation.navigate('Chat', {
                              toUserId: orderInfo.muserId,
                              toUserName: orderInfo.merShowName,
                              type: 'Reminder',
                            });
                          }
                        }}
                      >
                        {t('cui-dan')}
                      </Button>
                    )}
                    {finish && !cancelOrder && !statusInfo.isRefund && (
                      <Button
                        fontSize="xs"
                        flex={1}
                        mx={5}
                        bg="white"
                        color="gray600"
                        borderColor="brand500"
                        borderWidth={1}
                        rounded={3}
                        onPress={() => {
                          navigation.navigate('RewardRider', {
                            orderId,
                          });
                        }}
                      >
                        {t('da-shang-qi-shou')}
                      </Button>
                    )}
                    {finish &&
                      !Allfinish &&
                      !cancelOrder &&
                      !statusInfo.isRefund && (
                        <Button
                          fontSize="xs"
                          flex={1}
                          mx={5}
                          bg="white"
                          color="gray600"
                          borderColor="brand500"
                          borderWidth={1}
                          rounded={3}
                          onPress={() => {
                            navigation.navigate('Evaluate', {
                              orderId,
                            });
                          }}
                        >
                          {t('li-ji-ping-jia')}
                        </Button>
                      )}
                  </Div>
                </View>
              </Div>
            </Button>

            <View style={styles.card}>
              <Div row pb={10}>
                <Text fontSize="xl" fontWeight="bold">
                  {orderInfo.merShowName}
                </Text>
                <Button
                  fontSize="xs"
                  w={100}
                  bg="white"
                  color="gray600"
                  borderColor="brand500"
                  borderWidth={1}
                  rounded={3}
                  ml={14}
                  onPress={() => {
                    if (!orderInfo.muserId) {
                      warnning('商家信息有误请联系客服帮你催单');
                    } else {
                      navigation.navigate('Chat', {
                        toUserId: orderInfo.muserId,
                        toUserName: orderInfo.merShowName,
                      });
                    }
                  }}
                >
                  {t('lian-xi-shang-jia')}
                </Button>
              </Div>
              <Div>
                {orderGoodsSpecs.map((item) => {
                  return (
                    <GoodsItem info={item} goods={item.goods} key={item.id} />
                  );
                })}
              </Div>
              <Flex style={styles.info}>
                <Flex.Item>
                  <Flex>
                    <Text fontSize="xs" color="gray300" textAlign="left">
                      {t('bao-zhuang-fei')}
                    </Text>
                    <Text fontSize="xs" color="gray300" textAlign="left">
                      {t('can-he')}
                    </Text>
                  </Flex>
                </Flex.Item>
                <Text fontSize="xs" color="gray300" textAlign="left">
                  ¥{orderInfo.packingPrice}
                </Text>
              </Flex>
              <Flex style={styles.info}>
                <Flex.Item>
                  <Text fontSize="xs" color="gray300" textAlign="left">
                    {t('pei-song-fei-ding-dong-zhuan-song')}
                  </Text>
                </Flex.Item>
                <Text fontSize="xs" color="gray300" textAlign="left">
                  ¥{orderInfo.deliveryAmount}
                </Text>
              </Flex>
              <Flex style={styles.info}>
                <Flex.Item>
                  <Text fontSize="xs" color="gray300" textAlign="left">
                    {t('man-jian')}
                  </Text>
                </Flex.Item>
                <Text fontSize="xs" color="red500" textAlign="left">
                  -¥{orderInfo.fullReduction}
                </Text>
              </Flex>
              {!!orderInfo.firstBuy && (
                <Flex style={styles.info}>
                  <Flex.Item>
                    <Text fontSize="xs" color="gray300" textAlign="left">
                      {t('shou-dan')}
                    </Text>
                  </Flex.Item>
                  <Text fontSize="xs" color="red500" textAlign="left">
                    ¥{orderInfo.firstBuy}
                  </Text>
                </Flex>
              )}

              <Flex style={styles.info}>
                <Flex.Item>
                  <Text fontSize="xs" color="gray300" textAlign="left">
                    {t('hong-bao')}
                  </Text>
                </Flex.Item>
                <Text fontSize="xs" color="red500" textAlign="left">
                  -¥{orderInfo.redBag || 0}
                </Text>
              </Flex>
              <Flex style={styles.total} justify="end">
                <Text size="s1">
                  {t('xiao-ji')} ¥{orderInfo.realAmount}
                </Text>
              </Flex>
            </View>

            <View style={[styles.card]}>
              <Text size="c1">{t('ding-dan-xin-xi')}</Text>
              <View style={styles.main}>
                <Flex style={styles.info2}>
                  <Flex.Item>
                    <Text fontSize="xs" textAlign="left">
                      {t('xia-dan-shi-jian')}
                    </Text>
                  </Flex.Item>
                  <Text fontSize="xs" textAlign="left">
                    {orderInfo.orderTime}
                  </Text>
                </Flex>
                {orderInfo.userReceivedTime ? (
                  <Flex style={styles.info2}>
                    <Flex.Item>
                      <Text fontSize="xs" textAlign="left">
                        {t('song-da-shi-jian')}
                      </Text>
                    </Flex.Item>
                    <Text fontSize="xs" textAlign="left">
                      {orderInfo.userReceivedTime}
                    </Text>
                  </Flex>
                ) : (
                  <Flex style={styles.info2}>
                    <Flex.Item>
                      <Text fontSize="xs" textAlign="left">
                        {t('yu-ji-song-da-shi-jian')}
                      </Text>
                    </Flex.Item>
                    <Text fontSize="xs" textAlign="left">
                      {orderInfo.timeOfArrival}
                    </Text>
                  </Flex>
                )}

                <Flex style={styles.info2}>
                  <Flex.Item style={styles.address}>
                    <Text fontSize="xs" textAlign="left">
                      {t('shou-huo-di-zhi')}
                    </Text>
                  </Flex.Item>
                  <Text fontSize="xs" textAlign="left">
                    {orderInfo.userAddress}
                  </Text>
                </Flex>
                {hasRider && (
                  <Flex style={styles.info2}>
                    <Flex.Item>
                      <Text fontSize="xs" textAlign="left">
                        {t('pei-song-qi-shou')}
                      </Text>
                    </Flex.Item>
                    <Flex>
                      <Button
                        fontSize="xs"
                        w={100}
                        bg="white"
                        color="gray600"
                        borderColor="brand500"
                        borderWidth={1}
                        rounded={3}
                        onPress={() => {
                          if (!orderInfo.muserId) {
                            warnning('骑手信息有误请联系客服');
                          } else {
                            navigation.navigate('Chat', {
                              toUserId: orderInfo.muserId,
                              toUserName: orderInfo.merShowName,
                            });
                          }
                        }}
                      >
                        {t('lian-xi-qi-shou')}
                      </Button>
                      <Text fontSize="xs" ml={20} textAlign="left">
                        {orderInfo.riderName}
                      </Text>
                    </Flex>
                  </Flex>
                )}

                <Flex style={styles.info2}>
                  <Text fontSize="xs" textAlign="left">
                    {t('ding-dan-hao')}
                  </Text>
                  <Text fontSize="xs" textAlign="right" ml={10} flex={1}>
                    {orderInfo.id}
                  </Text>
                  <Button
                    fontSize="xs"
                    w={62}
                    bg="white"
                    color="gray600"
                    borderColor="brand500"
                    borderWidth={1}
                    rounded={3}
                    onPress={() => {
                      Clipboard.setString(orderInfo.id.toString());
                      success(t('fu-zhi-cheng-gong'));
                    }}
                    ml={5}
                  >
                    {t('fu-zhi')}
                  </Button>
                </Flex>
                {payMap.has(orderInfo.payMethod) && (
                  <Flex style={styles.info2}>
                    <Text fontSize="xs" flex={1}>
                      {t('zhi-fu-fang-shi')}
                    </Text>
                    <Text fontSize="xs" textAlign="left">
                      {payMap.get(orderInfo.payMethod).name}
                    </Text>
                  </Flex>
                )}
              </View>
            </View>
          </Div>
        </View>
      </Animated.View>
      {/* </RefreshControl> */}
    </Div>
  );
}

const GoodsItem = ({ info, goods }) => {
  return (
    <Div row>
      <Image w={33} h={33} rounded={3} source={{ uri: goods.img }} />
      <Div flex={1} ml={10}>
        <Div row>
          <Text fontSize="sm" flex={1}>
            {goods.name}
          </Text>
          <Text fontSize="sm">X {info.num}</Text>
          <Text ml={10}>¥{info.goodsRealPrice}</Text>
        </Div>
        <Text fontSize="xs" color="gray400">
          {info.specification}
        </Text>
      </Div>
    </Div>
  );
};

const styles = StyleSheet.create({
  scroll: {
    flexGrow: 1,
  },
  card: {
    borderRadius: 3,
    backgroundColor: '#fff',
    marginBottom: 5,
    padding: 15,
  },
  item: {
    paddingVertical: 5,
  },
  icon: {
    width: 33,
    height: 33,
    borderRadius: 3,
  },
  goodsMain: {
    marginLeft: 10,
  },
  type: {
    // marginTop:3,
  },
  main: {
    marginTop: 10,
    paddingVertical: 5,
    borderColor: '#E5E5E5',
    borderTopWidth: 1,
  },
  info: {
    marginTop: 10,
  },
  total: {
    paddingTop: 10,
    marginTop: 10,
    borderColor: '#E5E5E5',
    borderTopWidth: 1,
  },
  address: {
    minWidth: 50,
    marginRight: 30,
  },
  info2: {
    marginTop: 10,
  },
});
