import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { Div, Button, Image, Text, Avatar, Icon } from 'react-native-magnus';
import { ScrollView } from 'react-native-gesture-handler';
import { Picker } from '@ant-design/react-native';
import Constants from 'expo-constants';

import { useCreation, useRequest } from '@umijs/hooks';
import { useRoute, useNavigation } from '@react-navigation/native';
import useModel from 'flooks';
import Detail from './model';
import AddressModel from '../Address/model';
import Order from '../Order/model';

import Header from './DetailHeader';
import TablewareCom from './TablewareCom'; //餐具
import AddressCom from '../Address/AddressCom';
import PayCom from '../Pay/PayCom';
import Time from '../../Utils/TimeUtils';
import { accAdd, accMul } from '../../Utils/NumberUtils';

const Cart = ({ info }) => {
  const { goods } = info;
  return (
    <Div row py={5}>
      <Image w={40} h={40} source={{ uri: goods.img }} />
      <Div flex={1} ml={10}>
        <Div row>
          <Text>{goods.name}</Text>
          <Div flex={1} />
          <Text>X{info.num}</Text>
          <Text ml={10}>{info.goodsRealPrice}</Text>
        </Div>
        <Text fontSize="xs" color="gray300" textAlign="left">
          {info.specification}
        </Text>
      </Div>
    </Div>
  );
};

export default function SubmitScreen() {
  const {
    merchantInfo,
    getCart,
    remark,
    payMethod,
    cartRefreash,
    cartMoneyInfo,
  } = useModel(Detail, [
    'merchantInfo',
    'remark',
    'payMethod',
    'cartMoneyInfo',
  ]);
  const { chooseAddressId } = useModel(AddressModel, ['chooseAddressId']);
  const { submitOrder, payOrder } = useModel(Order, []);
  const route = useRoute();
  const navigation = useNavigation();
  const { params } = route;

  const {
    deliveryAmount,
    fullReduction,
    packingPrice,
    firstBuy,
    realAmount,
  } = cartMoneyInfo;

  const { banner, preparationTime, showName } = merchantInfo;

  const [cartList, setcartList] = React.useState([]);

  const [chooseTime, setChooseTime] = React.useState([]);

  const pickerRef = React.createRef();

  const cartRequest = useRequest(getCart, {
    refreshDeps: [params],
    onSuccess: (result) => {
      const value = result || [];
      setcartList(value);
    },
  });

  const time = useCreation(() => {
    return new Time().addTime(preparationTime / 60, 'HH:mm');
  }, [preparationTime]);

  const timeList = useCreation(() => {
    return [
      {
        label: `立即送出约(${time})`,
        value: time,
      },
    ].concat(
      new Time().nextList().map((item) => {
        return { value: item, label: item };
      })
    );
  }, [preparationTime, time]);

  const canSub = useCreation(() => {
    if (chooseAddressId && cartList.length > 0) {
      return true;
    } else {
      return false;
    }
  }, [cartList, chooseAddressId]);

  return (
    <>
      <Header noRight noTab />
      <ScrollView
        contentContainerStyle={{ flexGrow: 1, backgroundColor: '#eee' }}
      >
        <Image
          position="absolute"
          left={0}
          top={0}
          right={0}
          h={118 + Constants.statusBarHeight}
          source={{ uri: banner }}
        />

        <Div mx={15} mt={90} px={10} bg="white" rounded="sm">
          <AddressCom />
          <Div row alignItems="center" h={35}>
            <Text fontSize="xl" textAlign="left">
              {chooseTime.length > 0 && chooseTime[0] !== time
                ? '指定时间'
                : '立即送出'}
            </Text>
            <Div flex={1} />
            <Picker
              ref={pickerRef}
              data={timeList}
              cols={1}
              value={chooseTime}
              onChange={setChooseTime}
              itemStyle={{ paddingVertical: 10 }}
            >
              <Button bg="white" color="brand500" fontSize="xl" mr={5}>
                {chooseTime.length > 0 && chooseTime[0] !== time
                  ? `${chooseTime[0]}送达`
                  : `约${time}到达`}
              </Button>
            </Picker>

            <Icon name="right" color="#000" />
          </Div>
          <Div h={1} bg="gray200" />
          <PayCom />
        </Div>

        <Div mx={15} my={10} px={10} bg="white" rounded="sm">
          <Div row alignItems="center" h={46}>
            <Text fontSize="xl" fontWeight="bold" textAlign="left">
              {showName}
            </Text>
          </Div>
          <Div h={1} bg="gray200" mb={5} />
          {cartList.map((item) => {
            return <Cart key={item.id} info={item} />;
          })}

          <Div row mt={10}>
            <Text fontSize="xs" color="gray300" textAlign="left">
              包装费 餐盒
            </Text>
            <Div flex={1} />
            <Text fontSize="xs" color="gray300" textAlign="left">
              ¥{packingPrice}
            </Text>
          </Div>
          <Div row mt={10}>
            <Text fontSize="xs" color="gray300" textAlign="left">
              配送费
            </Text>
            <Div flex={1} />
            <Text fontSize="xs" color="gray300" textAlign="left">
              ¥{deliveryAmount}
            </Text>
          </Div>
          <Div row mt={10}>
            <Text fontSize="xs" color="gray300" textAlign="left">
              满减
            </Text>
            <Div flex={1} />
            <Text fontSize="xs" color="red500" textAlign="left">
              -¥{fullReduction}
            </Text>
          </Div>
          {firstBuy !== 0 && (
            <Div row mt={10}>
              <Text fontSize="xs" color="gray300" textAlign="left">
                首单
              </Text>
              <Div flex={1} />
              <Text fontSize="xs" color="red500" textAlign="left">
                -¥{firstBuy}
              </Text>
            </Div>
          )}

          <Div h={1} bg="gray200" mt={5} />
          <Button
            block
            p="none"
            bg="hide"
            onPress={() => navigation.navigate('OrderCoupon')}
          >
            <Div flex={1} row py={10} alignItems="center">
              <Text color="gray500" fontSize="xl" textAlign="left">
                红包
              </Text>
              <Div flex={1} />
              <Text fontSize="xs" color="gray300" mr={15} textAlign="left">
                暂无可用
              </Text>
              <Icon name="right" color="#000" />
            </Div>
          </Button>

          <Div h={1} bg="gray200" />

          <Div row pt={10} pb={20}>
            <Div flex={1} />
            <Text fontSize="xl" textAlign="left">
              小计
            </Text>
            <Text fontSize="xl" ml={20} textAlign="left">
              ¥{realAmount}
            </Text>
          </Div>
        </Div>

        <Div bg="white" mx={15} my={10} px={10} rounded="sm">
          <Button
            bg="hide"
            block
            p="none"
            onPress={() => navigation.navigate('OrderMessage')}
          >
            <Div row flex={1} py={10} alignItems="center">
              <Text fontSize="xl">订单备注</Text>
              <Text
                fontSize="sm"
                ml={10}
                color="gray300"
                textAlign="right"
                flex={1}
                numberOfLines={1}
                ellipsizeMode="tail"
              >
                {remark}
              </Text>
              <Icon name="right" />
            </Div>
          </Button>
          <TablewareCom />
        </Div>

        <Button
          disabled={!canSub}
          bg="brand500"
          color="white"
          block
          mx={15}
          mt={10}
          my={20}
          onPress={() => {
            const ids = cartList.map((item) => {
              return item.shoppingCartId;
            });
            submitOrder(ids[0], chooseAddressId, payMethod, remark)
              .then((res) => {
                cartRefreash();
                return payOrder(res.id).then(() => {
                  return Promise.resolve(res.id);
                });
              })
              .then((id) => {
                navigation.replace('OrderDetail', { orderId: id });
              });
          }}
        >
          支付
        </Button>
      </ScrollView>
    </>
  );
}
