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 { useCreation, useRequest } from '@umijs/hooks';
import { useFocusEffect } from '@react-navigation/native';
import useModel from 'flooks';
import Toast from '../../flooks/Toast';

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

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

  const { success, warnning } = useModel(Toast, []);
  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={() => {
              navigation.navigate('MerchantDetail', {
                merchantId: item.merchantId,
              });
            }}
            index={index}
            connect={(type) => {
              if (type === 'merchant') {
                warnning('正在帮您联系商家');
              }
            }}
          />
        )}
        keyExtractor={(item) => item.id.toString()}
      />
    </>
  );
}

// 订单组件
function Item({
  merchant,
  info,
  goNext,
  orderGoodsSpecs,
  goMerchant,
  connect,
}) {
  const orderInfo =
    orderGoodsSpecs.length > 0 ? orderGoodsSpecs[0].goods.name : '';

  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: merchant.logo }} />
          </Button>
          <Div flex={1} ml={10}>
            <Div row>
              <Text fontSize="xl" flex={1} fontWeight="bold">
                {merchant.name}
              </Text>
              {finish || Allfinish ? (
                <Text fontSize="xs">已送达</Text>
              ) : (
                <Text fontSize="xs">
                  预计
                  <Text color="red500">
                    {new Time(
                      info.timeOfArrival,
                      'yyyy-MM-DD HH:mm:ss'
                    ).getFormat('HH:mm')}
                  </Text>
                  送达
                </Text>
              )}
            </Div>
            <Text fontSize="xs" my={10}>
              订单时间: {info.orderTime}
            </Text>
            <Div h={1} bg="gray200" />
            <Div row py={10} alignItems="center">
              <Text fontSize="sm">订单商品</Text>
              <Text fontSize="xs" ml={5} flex={1}>
                {orderInfo}等{info.num}件
              </Text>
              <Text size="sm">¥{info.realAmount}</Text>
            </Div>
          </Div>
        </Div>
        <MapMarkImg
          imgType={statusInfo.nowImgType}
          label={statusInfo.name}
          info={info}
        />
        <Flex justify="end" style={styles.btns}>
          {finish && !Allfinish ? (
            <Button
              w={100}
              fontSize="xs"
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              onPress={() => goNext('Evaluate')}
            >
              立即评价
            </Button>
          ) : (
            <Button
              w={100}
              fontSize="xs"
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              onPress={() => connect('merchant')}
            >
              联系商家
            </Button>
          )}

          {finish && (
            <Button
              w={100}
              fontSize="xs"
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              ml={10}
              onPress={goMerchant}
            >
              再来一单
            </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,
  },
});
