import { StackScreenProps } from '@react-navigation/stack';
import * as React from 'react';
import { Div, Button, Image, Text, Avatar, Icon } from 'react-native-magnus';
import { Menu } from 'teaset';
import { ScrollView } from 'react-native-gesture-handler';
import { useRequest, useCreation, useMount } from 'ahooks';
import { RefreshControl, Dimensions } from 'react-native';
import { toastInfo, toastSuccess, alert } from '../utils/SystemUtils';

import { RiderStatusMap } from '../utils/RiderInfoUtils';
import ImagePicker from '../components/ImagePicker';
import { useTranslation } from 'react-i18next';

import useModel from 'flooks';
import OrderModel from './model';
import { useSafeArea } from 'react-native-safe-area-context';

import { changeCord, goMap } from '../utils/MapUtils';

import { connect } from '../utils/SystemUtils';

import Request from '../utils/RequestUtils';

function RightMenuItem({ text = '' }) {
  return (
    <Text fontSize="sm" color="black">
      {text}
    </Text>
  );
}
export default function OrderDetailScreen({
  navigation,
  route,
}: StackScreenProps) {
  const { t } = useTranslation();
  const { params } = route;
  const { orderId } = params;

  const [pickImg, setpickImg] = React.useState<string>('');

  const { receiverOrder, changeStatus, changeStatusAll } = useModel(
    OrderModel,
    []
  );

  navigation.setOptions({
    headerRight: (props) => (
      <Button
        bg="none"
        px={15}
        py={0}
        w={50}
        h={50}
        onPress={() => {
          const x = Dimensions.get('window').width - 80,
            y = 0,
            width = 50,
            height = 50;
          let items = [
            {
              title: '联系客服',
              onPress: () => connect(navigation),
            },
          ];
          if (!isRefund && statusInfo.type && statusInfo.type !== 'order') {
            items.splice(0, 0, {
              title: '取消订单申请',
              onPress: () => {
                navigation.navigate('Modal', {
                  screen: 'Applay',
                  params: {
                    orderId,
                  },
                });
              },
            });
          }
          Menu.show({ x, y, width, height }, items, {
            popoverStyle: {
              backgroundColor: '#fff',
            },
          });
        }}
      >
        <Icon
          name="more-horizontal"
          color="white"
          fontFamily="Feather"
          fontSize="lg"
        ></Icon>
      </Button>
    ),
  });

  const { data, loading, reload, run } = useRequest(
    `/orderInfo/get/${orderId}`,
    {
      manual: true,
      defaultLoading: false,
      debounceInterval: 1000,
      initialData: {},
    }
  );

  useMount(() => {
    run();
  });

  const orderGoodsSpecs = useCreation(() => {
    return data.orderGoodsSpecs || [];
  }, [data]);

  const statusInfo = useCreation(() => {
    if (data.riderStatus) {
      return RiderStatusMap.get(data.riderStatus);
    } else {
      return {};
    }
  }, [data]);

  const totalNum = useCreation(() => {
    return orderGoodsSpecs.reduce((total, currentValue) => {
      return total + currentValue.num;
    }, 0);
  }, [orderGoodsSpecs]);

  const isRefund = useCreation(() => {
    if (data.status === 'REFUNDED_PENDING') {
      return true;
    } else {
      return false;
    }
  }, [data]);

  function orderChange() {
    alert(navigation, {
      msg: statusInfo.infoText,
      hasCancel: true,
      dangers: true,
      submitEvent: () => {
        changeStatus(
          data.id,
          statusInfo.nextStatus,
          (res) => {
            toastSuccess(statusInfo.successText);
          },
          () => {
            alert(navigation, {
              msg: statusInfo.errorText,
              hasCancel: true,
              dangers: true,
              submitEvent: () => {
                changeStatusAll(data.id, statusInfo.nextStatus, (res) => {
                  toastSuccess(statusInfo.successText);
                  run();
                });
              },
            });
          },
          pickImg
        );
      },
    });
  }

  return (
    <Div bg="gray100" flex={1}>
      {/* <ModalDropdown ref={menu} options={['option 1', 'option 2']} /> */}
      {statusInfo.type && statusInfo.type !== 'order' && (
        <Div row bg="white" py={12}>
          {__DEV__ &&
            !isRefund &&
            statusInfo.type &&
            statusInfo.type !== 'order' && (
              <Button
                onPress={() => {
                  navigation.navigate('Modal', {
                    screen: 'Applay',
                    params: {
                      orderId,
                    },
                  });
                }}
              >
                取消订单
              </Button>
            )}
          <Div flex={1} alignItems="center">
            <Text fontSize="xl" color="red500">
              {data.deliveryAmount}
            </Text>
            <Text fontSize="sm" color="gray600">
              {t('ben-dan-pai-song-shou-ru')}
            </Text>
          </Div>
          <Div w={1} bg="gray100" />
          {statusInfo.type === 'finish' ? (
            <Div flex={1} alignItems="center">
              <Text fontSize="xl" color="red500">
                {data.userReceivedTime}
              </Text>
              <Text fontSize="sm" color="gray600">
                {t('yong-hu-shou-dao-shi-jian')}
              </Text>
            </Div>
          ) : (
            <Div flex={1} alignItems="center">
              <Text fontSize="xl" color="red500">
                {data.timeOfArrival}
              </Text>
              <Text fontSize="sm" color="gray600">
                {t('yu-ji-song-da-shi-jian')}
              </Text>
            </Div>
          )}
        </Div>
      )}

      <ScrollView
        contentContainerStyle={{
          flexGrow: 1,
          backgroundColor: '#f2f2f2',
          paddingHorizontal: 15,
          paddingVertical: 10,
        }}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={reload} />
        }
      >
        {statusInfo.type && (
          <>
            <Div bg="white" rounded="xs" px={15} py={10}>
              {statusInfo.type == 'user' && (
                <Div row py={10}>
                  <Div flex={1}>
                    <Text fontSize="xl" fontWeight="bold" color="yellow500">
                      {statusInfo.name}
                    </Text>
                    <Text fontSize="sm" color="gray600" mt={2}>
                      {t('liu-shui-hao')}：{data.id}
                    </Text>
                  </Div>
                  <Button bg="yellow500" w={112} onPress={orderChange}>
                    {t('que-ren-song-da')}
                  </Button>
                </Div>
              )}
              {statusInfo.type === 'merchant' && (
                <>
                  <Div row py={10}>
                    <Div flex={1}>
                      <Text>{t('wo-yi-dao-dian')}</Text>
                      <Text fontSize="sm" color="gray600" mt={2}>
                        {t('liu-shui-hao')}：{data.id}
                      </Text>
                    </Div>
                    <Button
                      bg="yellow500"
                      w={112}
                      disabled={statusInfo.status != 0}
                      onPress={orderChange}
                    >
                      {t('wo-yi-dao-dian')}
                    </Button>
                  </Div>

                  {statusInfo.status === 1 && (
                    <>
                      <Div row py={10}>
                        <Div flex={1}>
                          <Text>{t('wo-yi-qu-huo')}</Text>
                          <Text fontSize="sm" color="gray600" mt={2} pr={48}>
                            {t('ordertips')}
                          </Text>
                        </Div>
                        <Button bg="yellow500" w={112} onPress={orderChange}>
                          {t('pai-zhao-qu-huo')}
                        </Button>
                      </Div>
                      <ImagePicker
                        img={pickImg}
                        setImg={(img) => setpickImg(img)}
                      />
                    </>
                  )}
                </>
              )}
              {(statusInfo.type === 'user' || statusInfo.type === 'finish') && (
                <Div py={10}>
                  <Text fontSize="sm">{t('yong-hu-xin-xi')}</Text>
                  <Div px={10} mt={10}>
                    <Text fontSize="xl" fontWeight="bold">
                      {data.nickname}
                    </Text>
                    <Text fontSize="sm" mt={5}>
                      {data.userAddress}
                    </Text>
                  </Div>
                  <Button
                    block
                    bg="yellow500"
                    mt={15}
                    onPress={() => {
                      if (!data.userId) {
                        toastInfo('该订单缺少用户id,请重新下单');
                        return;
                      }
                      navigation.navigate('NoticeStack', {
                        screen: 'Chat',
                        params: {
                          toUserId: data.userId,
                          toUserName: data.nickname,
                        },
                      });
                    }}
                  >
                    {t('lian-xi-ke-hu')}
                  </Button>
                </Div>
              )}

              {(statusInfo.type === 'merchant' ||
                statusInfo.type === 'finish') && (
                <Div borderTopColor="gray100" borderTopWidth={1} py={10}>
                  <Text fontSize="sm">{t('shang-jia-xin-xi')}</Text>
                  <Div px={10} mt={10}>
                    <Text fontSize="xl" fontWeight="bold">
                      {data.merShowName}
                    </Text>
                    <Text fontSize="sm" mt={5}>
                      {data.merAddress}
                    </Text>
                  </Div>
                  <Button
                    block
                    bg="yellow500"
                    mt={15}
                    onPress={() => {
                      if (!data.muserId) {
                        toastInfo('该订单缺少商家id,请重新下单');
                        return;
                      }
                      navigation.navigate('NoticeStack', {
                        screen: 'Chat',
                        params: {
                          toUserId: data.muserId,
                          toUserName: data.merShowName,
                        },
                      });
                    }}
                  >
                    {t('lian-xi-shang-jia')}
                  </Button>
                </Div>
              )}
              {statusInfo.type === 'order' && (
                <Div py={15}>
                  <Div row mt={10}>
                    <Text fontSize="sm" color="gray600">
                      1.5Km
                    </Text>
                    <Div flex={1} ml={12}>
                      <Text fontSize="md" pb={3}>
                        {data.merShowName}
                      </Text>
                      <Text fontSize="sm">{data.merAddress}</Text>
                    </Div>
                  </Div>
                  <Div row mt={10}>
                    <Text fontSize="sm" color="gray600">
                      1.5Km
                    </Text>
                    <Div flex={1} ml={12}>
                      {data.nickName && (
                        <Text fontSize="md" pb={5}>
                          {data.nickName}
                        </Text>
                      )}
                      <Text fontSize="sm">{data.userAddress}</Text>
                    </Div>
                  </Div>
                </Div>
              )}

              <Div borderTopColor="gray100" borderTopWidth={1} py={10}>
                <Div row>
                  <Text fontSize="sm" flex={2}>
                    {t('shang-pin-xin-xi')}
                  </Text>
                  <Text fontSize="sm" flex={1} textAlign="right">
                    {totalNum}
                    {t('fen')}
                  </Text>
                  <Text fontSize="sm" flex={1} color="red500" textAlign="right">
                    ¥{data.realAmount || 0}
                  </Text>
                </Div>

                <Div p={15}>
                  {orderGoodsSpecs.map((item) => {
                    const goods = item.goods;
                    return (
                      <Div row key={item.id} mt={5}>
                        <Text fontSize="sm"> {goods.name}</Text>
                        <Text fontSize="sm" color="gray500" ml={5}>
                          {item.specification}
                        </Text>
                        <Text fontSize="sm" flex={1} textAlign="right">
                          X {item.num}
                        </Text>
                      </Div>
                    );
                  })}
                </Div>
              </Div>

              {statusInfo.type === 'order' && (
                <Button
                  bg="yellow500"
                  w={112}
                  alignSelf="flex-end"
                  my={10}
                  onPress={() => {
                    receiverOrder(data.id, (res) => {
                      toastSuccess(t('jie-dan-cheng-gong'));
                    });
                  }}
                >
                  {t('jie-dan')}
                </Button>
              )}
            </Div>

            <Div h={35} w="100%" />

            {(statusInfo.type === 'merchant' || statusInfo.type === 'user') &&
              !isRefund && (
                <Div position="absolute" bottom={0} left={0} right={0}>
                  <Button
                    block
                    mx={15}
                    my={10}
                    bg="yellow500"
                    onPress={() => {
                      goMap(
                        statusInfo.type === 'merchant'
                          ? data.merShowName
                          : data.userAddress,
                        statusInfo.type === 'merchant'
                          ? changeCord(data.merLocation)
                          : changeCord(data.location),
                        navigation
                      );
                    }}
                  >
                    {t('cha-kan-dao-hang')}
                  </Button>
                </Div>
              )}

            {isRefund && (
              <Div
                row
                position="absolute"
                bottom={0}
                left={0}
                right={0}
                px={15}
                py={10}
              >
                <Button flex={1} bg="gray300" disabled>
                  订单申请取消中
                </Button>
                <Button
                  w={105}
                  ml={5}
                  bg="yellow500"
                  onPress={() => {
                    Request.get('/orderRefundApply/cancel', {
                      params: {
                        orderId,
                      },
                    })
                      .then((res) => {
                        toastSuccess('取消成功');
                      })
                      .catch((e) => {
                        toastInfo(e.error);
                      })
                      .finally(() => {
                        run();
                      });
                  }}
                >
                  撤销申请
                </Button>
              </Div>
            )}
          </>
        )}
      </ScrollView>
    </Div>
  );
}
