import { StackScreenProps } from '@react-navigation/stack';
import * as React from 'react';
import { RefreshControl } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { Div, Button, Image, Text, Avatar, Icon } from 'react-native-magnus';
import { FlatList } from 'react-native-gesture-handler';
import Constants from 'expo-constants';
import TimScreen from '../notice/TimScreen';

import useModel from 'flooks';
import Map from '../map/model';
import OrderModel from './model';
import User from '../stores/User';
import { useMount, useRequest, useCreation } from 'ahooks';
import { useTranslation } from 'react-i18next';

import moment from 'moment';

import { promot, toastSuccess, alert, toastInfo } from '../utils/SystemUtils';
import { orderRiderStatus, RiderStatusMap } from '../utils/RiderInfoUtils';
import request from '../utils/RequestUtils';
import { goMap, changeCord } from '../utils/MapUtils';

import OrderCom from './OrderCom';

export default function OrderScreen({ navigation }: StackScreenProps) {
  const { t } = useTranslation();
  const { locationInfo, getNowLocation } = useModel(Map, ['locationInfo']);

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

  const { getSignInfo, sign, riderOrder } = useModel(User, [
    'getSignInfo',
    'sign',
  ]);

  const [chooseStatus, setChooseStatus] = React.useState<string>(
    'NOT_RECEIVED'
  );
  useMount(() => {
    getNowLocation();
    getSignInfo();
  });
  const chooseStatusInfo = useCreation(() => {
    return orderRiderStatus.get(chooseStatus);
  }, [chooseStatus]);

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

  const { data, loading, reload, run } = useRequest(
    () => {
      return request.get(chooseStatusInfo.requestUrl, {
        params: chooseStatusInfo.params,
      });
    },
    {
      manual: false,
      formatResult: chooseStatusInfo.formatResult,
      defaultLoading: false,
      debounceInterval: 1000,
      initialData: [],
    }
  );

  const showData = useCreation(() => {
    if (chooseStatusInfo.status) {
      return data.filter((item) => {
        return chooseStatusInfo.status.indexOf(item.riderStatus) !== -1;
      });
    } else {
      return data;
    }
  }, [data, chooseStatusInfo]);

  return (
    <Div bg="gray100" flex={1}>
      <Div
        pt={Constants.statusBarHeight + 11}
        pb={11}
        bg="yellow500"
        row
        alignItems="center"
        px={14}
        px={15}
      >
        {/* <Image w={50} h={50} source={require('../assets/images/logo.png')} /> */}
        <Button
          bg="transparent"
          onPress={() => {
            if (sign) {
              alert(navigation, {
                msg: '确定要休息吗?',
                submitEvent: riderOrder,
                hasCancel: true,
              });
            } else {
              riderOrder();
            }
          }}
        >
          <Div alignItems="center">
            <Icon
              fontSize="6xl"
              color="white"
              fontFamily="MaterialCommunityIcons"
              name={sign ? 'coffee' : 'motorbike'}
            />
            <Text fontSize="sm" color="white" fontWeight="bold">
              {sign ? '休息' : '开工'}
            </Text>
          </Div>
        </Button>
        <Text fontSize="xl" color="white" mr={50} textAlign="center" flex={1}>
          骑手客户端
        </Text>
      </Div>
      <Div row>
        {[...orderRiderStatus.keys()].map((item) => {
          const info = orderRiderStatus.get(item);
          return (
            <Button
              key={item}
              flex={1}
              bg="transparent"
              color={chooseStatus === item ? 'yellow500' : 'black'}
              fontSize="lg"
              py={15}
              onPress={() => {
                setChooseStatus(item);
                run();
              }}
            >
              {t(info.name)}
            </Button>
          );
        })}
      </Div>

      <FlatList
        renderItem={({ item }) => {
          return (
            <OrderCom
              sign={sign}
              info={item}
              type={chooseStatusInfo.type}
              goDetail={() =>
                navigation.navigate('OrderStack', {
                  screen: 'OrderDetail',
                  params: {
                    orderId: item.id,
                  },
                })
              }
              receiverOrder={() => {
                receiverOrder(item.id, (res) => {
                  toastSuccess(t('jie-dan-cheng-gong'));
                  run();
                }).catch((res) => {
                  toastInfo('该订单异常暂不能接单');
                  run();
                });
              }}
              goMap={() => {
                const orderStatusInfo = RiderStatusMap.get(item.riderStatus);
                goMap(
                  orderStatusInfo.type === 'merchant'
                    ? item.merShowName
                    : item.userAddress,
                  orderStatusInfo.type === 'merchant'
                    ? changeCord(item.merLocation)
                    : changeCord(item.location),
                  navigation
                );
              }}
              changeStatus={() => {
                const orderStatusInfo = RiderStatusMap.get(item.riderStatus);

                alert(navigation, {
                  msg: orderStatusInfo.infoText,
                  hasCancel: true,
                  dangers: true,
                  submitEvent: () => {
                    changeStatus(
                      item.id,
                      orderStatusInfo.nextStatus,
                      (res) => {
                        toastSuccess(orderStatusInfo.successText);
                      },
                      () => {
                        alert(navigation, {
                          msg: orderStatusInfo.errorText,
                          hasCancel: true,
                          dangers: true,
                          submitEvent: () => {
                            changeStatusAll(
                              item.id,
                              orderStatusInfo.nextStatus,
                              (res) => {
                                toastSuccess(orderStatusInfo.successText);
                                run();
                              }
                            );
                          },
                        });
                      }
                    );
                  },
                });
              }}
            />
          );
        }}
        data={showData}
        contentContainerStyle={{
          flexGrow: 1,
          paddingHorizontal: 15,
          backgroundColor: '#f2f2f2',
        }}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={reload} />
        }
        ListEmptyComponent={() => {
          if (!loading) {
            return (
              <Text color="gary200" fontSize="sm" textAlign="center" py={20}>
                {t('zan-wu-shu-ju')}
              </Text>
            );
          } else {
            return <></>;
          }
        }}
        extraData={sign}
      />

      <Div position="absolute" w={0} h={0} bottom={0} left={0} zIndex={0}>
        <TimScreen />
      </Div>
    </Div>
  );
}
