import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { StyleSheet, View, FlatList } from 'react-native';
import { Div, Button, Text, Avatar, Image } from 'react-native-magnus';
import { Flex } from '@ant-design/react-native';
import { TouchableRipple } from 'react-native-paper';
import { useTranslation } from 'react-i18next';
import { useCreation, useRequest } from '@umijs/hooks';
import { useFocusEffect } from '@react-navigation/native';
import useModel from 'flooks';
import Toast from '../../flooks/Toast';
import Order from './model';

import Header from './Header'; // 头部
import Time from '../../Utils/TimeUtils';
import MapMarkImg from '../Map/MapMarkImg';
import { getStatusInfo, getGoodsInfo } from '../../Utils/OrderUtils';

export default function OrderScreen({ navigation }) {
  const { t } = useTranslation();
  const [orderList, setorderList] = React.useState();

  const { success, warnning } = useModel(Toast, []);
  const { again } = useModel(Order, []);
  const orderRequest = useRequest('/orderInfo/my?sort=id,desc', {
    manual: true,
    onSuccess: (result) => {
      setorderList(result.content);
    },
  });

  useFocusEffect(
    React.useCallback(() => {
      orderRequest.run();
    }, [])
  );

  return (
    <>
      <Header noBack />

      <FlatList
        onRefresh={() => orderRequest.run()}
        refreshing={orderRequest.loading}
        contentContainerStyle={styles.list}
        data={orderList}
        renderItem={({ item, index }) => (
          <Item
            merchant={item.merchant}
            info={item}
            orderGoodsSpecs={item.orderGoodsSpecs}
            goNext={(name) => {
              navigation.navigate(name || 'OrderDetail', {
                orderId: item.id,
              });
            }}
            goMerchant={() => {
              again(item.id).then(() => {
                navigation.navigate('MerchantDetail', {
                  merchantId: item.merchantId,
                });
              });
            }}
            index={index}
            connect={(type) => {
              if (type === 'merchant') {
                if (!item.muserId) {
                  warnning('商家信息有误请联系客服帮你催单');
                } else {
                  navigation.navigate('Chat', {
                    toUserId: item.muserId,
                    toUserName: item.merShowName,
                  });
                }
              }
            }}
          />
        )}
        keyExtractor={(item) => item.id.toString()}
      />
    </>
  );
}

// 订单组件
function Item({
  merchant = {},
  info,
  goNext,
  orderGoodsSpecs,
  goMerchant,
  connect,
}) {
  const { t } = useTranslation();
  const orderGoodsInfo = getGoodsInfo(orderGoodsSpecs);

  const statusInfo = getStatusInfo(info);

  const finish = info.riderStatus === 'CARRY_OUT';

  const Allfinish = info.status === 'COMPLETED';
  return (
    <Button bg="hide" block p={0} mt={10} onPress={() => goNext()}>
      <View style={styles.item}>
        <Div row>
          <Button bg="hide" p={0} onPress={() => goMerchant()}>
            <Image w={53} h={53} source={{ uri: info.merLogo }} />
          </Button>
          <Div flex={1} ml={10}>
            <Div row>
              <Text fontSize="xl" flex={1} fontWeight="bold">
                {info.merShowName}
              </Text>
              {finish || Allfinish || statusInfo.isRefund ? (
                <Text fontSize="xs">{t('yi-song-da')}</Text>
              ) : (
                <Text fontSize="xs">
                  {t('yu-ji')}
                  <Text color="red500">
                    {new Time(
                      info.timeOfArrival,
                      'yyyy-MM-DD HH:mm:ss'
                    ).getFormat('HH:mm')}
                  </Text>
                  {t('song-da')}
                </Text>
              )}
            </Div>
            <Text fontSize="xs" my={10}>
              {t('ding-dan-shi-jian')}: {info.orderTime}
            </Text>
            <Div h={1} bg="gray200" />
            <Div row py={10} alignItems="center">
              <Text fontSize="sm">{t('ding-dan-shang-pin')}</Text>
              <Text fontSize="xs" ml={5} flex={1}>
                {orderGoodsInfo.name}
                {t('deng')}
                {orderGoodsInfo.num}
                {t('jian2')}
              </Text>
              <Text size="sm">¥{info.realAmount}</Text>
            </Div>
          </Div>
        </Div>
        {!statusInfo.isRefund && (
          <MapMarkImg
            imgType={statusInfo.nowImgType}
            label={statusInfo.name}
            info={info}
          />
        )}

        <Flex justify="end" style={styles.btns}>
          {info.status === 'UNPAID' && (
            <Button
              w={100}
              fontSize="xs"
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              onPress={() => goNext('PayOrder')}
            >
              去支付
            </Button>
          )}
          {!statusInfo.isRefund &&
            (finish && !Allfinish ? (
              <Button
                w={100}
                fontSize="xs"
                bg="white"
                color="gray600"
                borderColor="brand500"
                borderWidth={1}
                rounded={3}
                onPress={() => goNext('Evaluate')}
              >
                {t('li-ji-ping-jia')}
              </Button>
            ) : (
              <Button
                w={100}
                fontSize="xs"
                bg="white"
                color="gray600"
                borderColor="brand500"
                borderWidth={1}
                rounded={3}
                onPress={() => connect('merchant')}
              >
                {t('lian-xi-shang-jia')}
              </Button>
            ))}

          {finish && !statusInfo.isRefund && (
            <Button
              w={100}
              fontSize="xs"
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              ml={10}
              onPress={goMerchant}
            >
              {t('zai-lai-yi-dan')}
            </Button>
          )}
        </Flex>
      </View>
    </Button>
  );
}

const styles = StyleSheet.create({
  item: {
    paddingVertical: 20,
    paddingHorizontal: 10,
    backgroundColor: '#fff',
    borderRadius: 3,
    flex: 1,
  },
  list: {
    padding: 15,
  },
  icon: {
    width: 53,
    height: 53,
    borderRadius: 3,
    backgroundColor: '#eee',
  },
  main: {
    marginLeft: 5,
  },
  orderDetail: {
    paddingVertical: 10,
    borderTopWidth: 1,
    borderColor: '#E5E5E5',
    marginTop: 10,
  },
  btns: {
    paddingTop: 15,
  },
});
