import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { StyleSheet, View, Clipboard, RefreshControl } from 'react-native';
import { Div, Button, Image, Text } from 'react-native-magnus';

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

import { useRequest, useCreation } from '@umijs/hooks';
import { useRoute } from '@react-navigation/native';
import useModel from 'flooks';
import Toast from '../../flooks/Toast';

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

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

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

  const { success, warnning } = 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(() => {
    const statusList = [];

    if (orderInfo.status) {
      statusList.push(orderStatusMap.get(orderInfo.status));
    }
    if (orderInfo.merchantStatus) {
      statusList.push(merchantStatusMap.get(orderInfo.merchantStatus));
    }
    if (orderInfo.riderStatus) {
      statusList.push(RiderStatusMap.get(orderInfo.riderStatus));
    }

    if (statusList.length > 0) {
      return statusList.sort((a, b) => {
        return b.sort - a.sort;
      })[0];
    } else {
      return {
        name: '订单详情',
      };
    }
  }, [orderInfo]);

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

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

  return (
    <>
      <Header title={statusInfo.name} />
      <ScrollView
        contentContainerStyle={styles.scroll}
        refreshControl={
          <RefreshControl
            refreshing={orderRequest.loading}
            onRefresh={orderRequest.run}
          />
        }
      >
        <View style={[styles.card]}>
          {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')}
              送达
            </Text>
          ) : (
            <Text fontSize="xl">
              <Text fontSize="xl" color="brand500" mr={10} fontWeight="bold">
                {statusInfo.name}
              </Text>
              预计
              {new Time(
                orderInfo.timeOfArrival,
                'yyyy-MM-DD HH:mm:ss'
              ).getFormat('HH:mm')}
              送达
            </Text>
          )}
          <Div row mt={10}>
            <Button
              fontSize="xs"
              flex={1}
              mx={5}
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              onPress={() => connectKefu(orderId)}
            >
              联系客服
            </Button>
            {!finish && (
              <Button
                fontSize="xs"
                flex={1}
                mx={5}
                bg="white"
                color="gray600"
                borderColor="brand500"
                borderWidth={1}
                rounded={3}
                onPress={() => {
                  warnning('正在帮您联系骑手');
                }}
              >
                联系骑手
              </Button>
            )}
            {!finish && (
              <Button
                fontSize="xs"
                flex={1}
                mx={5}
                bg="white"
                color="gray600"
                borderColor="brand500"
                borderWidth={1}
                rounded={3}
                onPress={() => {
                  warnning('正在帮您催单');
                }}
              >
                催单
              </Button>
            )}
            {finish && !Allfinish && (
              <Button
                fontSize="xs"
                flex={1}
                mx={5}
                bg="white"
                color="gray600"
                borderColor="brand500"
                borderWidth={1}
                rounded={3}
                onPress={() => {
                  navigation.navigate('Evaluate', {
                    orderId,
                  });
                }}
              >
                立即评价
              </Button>
            )}
            {finish && (
              <Button
                fontSize="xs"
                flex={1}
                mx={5}
                bg="white"
                color="gray600"
                borderColor="brand500"
                borderWidth={1}
                rounded={3}
                onPress={() => {
                  navigation.navigate('MerchantDetail', {
                    merchantId: orderInfo.merchantId,
                  });
                }}
              >
                再来一单
              </Button>
            )}
          </Div>
        </View>

        <View style={[styles.card]}>
          <Div row pb={10}>
            <Text fontSize="xl" fontWeight="bold">
              {merchant.showName}
            </Text>
            <Button
              fontSize="xs"
              w={100}
              bg="white"
              color="gray600"
              borderColor="brand500"
              borderWidth={1}
              rounded={3}
              ml={14}
              onPress={() => {
                warnning('正在帮您联系商家');
              }}
            >
              联系商家
            </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">
                  包装费
                </Text>
                <Text fontSize="xs" color="gray300" textAlign="left">
                  餐盒
                </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">
                配送费（叮咚专送）
              </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">
                满减
              </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">
                  首单
                </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">
                红包
              </Text>
            </Flex.Item>
            <Text fontSize="xs" color="red500" textAlign="left">
              -¥{orderInfo.redBag || 0}
            </Text>
          </Flex>
          <Flex style={styles.total} justify="end">
            <Text size="s1">小计 ¥{orderInfo.realAmount}</Text>
          </Flex>
        </View>

        <View style={[styles.card]}>
          <Text size="c1">订单信息</Text>
          <View style={styles.main}>
            <Flex style={styles.info2}>
              <Flex.Item>
                <Text fontSize="xs" textAlign="left">
                  下单时间
                </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">
                    送达时间
                  </Text>
                </Flex.Item>
                <Text fontSize="xs" textAlign="left">
                  {orderInfo.userReceivedTime}
                </Text>
              </Flex>
            ) : (
              <Flex style={styles.info2}>
                <Flex.Item>
                  <Text fontSize="xs" textAlign="left">
                    预计送达时间
                  </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">
                  收货地址
                </Text>
              </Flex.Item>
              <Text fontSize="xs" textAlign="left">
                {orderInfo.userAddress}
              </Text>
            </Flex>
            <Flex style={styles.info2}>
              <Flex.Item>
                <Text fontSize="xs" textAlign="left">
                  配送骑手
                </Text>
              </Flex.Item>
              <Flex>
                <Button
                  fontSize="xs"
                  w={100}
                  bg="white"
                  color="gray600"
                  borderColor="brand500"
                  borderWidth={1}
                  rounded={3}
                  onPress={() => {
                    warnning('正在帮您联系骑手');
                  }}
                >
                  联系骑手
                </Button>
                <Text fontSize="xs" ml={20} textAlign="left">
                  周猩猩
                </Text>
              </Flex>
            </Flex>
            <Flex style={styles.info2}>
              <Text fontSize="xs" textAlign="left">
                订 单 号
              </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('复制成功');
                }}
                ml={5}
              >
                复制
              </Button>
            </Flex>
            {payMap.has(orderInfo.payMethod) && (
              <Flex style={styles.info2}>
                <Text fontSize="xs" flex={1}>
                  支付方式
                </Text>
                <Text fontSize="xs" textAlign="left">
                  {payMap.get(orderInfo.payMethod).name}
                </Text>
              </Flex>
            )}
          </View>
        </View>
      </ScrollView>
    </>
  );
}

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,
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: '#eee',
  },
  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,
  },
});
