import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { StyleSheet, View } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import { Modal, Portal } from 'react-native-paper';
import { Div, Image, Text, Button } from 'react-native-magnus';
import { Flex } from '@ant-design/react-native';
import { useCreation, useMap } from '@umijs/hooks';

import useModel from 'flooks';
import Detail from './model';

import Plus from '../../components/Plus';

export default function SelectSpecification() {
  const { showSelect, selectInfo, addCart, changeSelect } = useModel(Detail, [
    'showSelect',
    'selectInfo',
  ]);
  const {
    id,
    img,
    name,
    discountAmount,
    amount,
    specifications,
  } = selectInfo || { specifications: [] };

  // 全部的分类 一级包含二级形式 list
  const selectspecifications = useCreation(() => {
    return specifications.filter((item) => {
      return !item.parent && item.children.length > 0;
    });
  }, [specifications]);

  // 全部的一级分类的 Map
  const classify1Map = useCreation(() => {
    const map = new Map();
    selectspecifications.forEach((item) => {
      map.set(item.id, item);
    });
    return map;
  }, [selectspecifications]);

  // 选择模块
  const [selectMap, selectMapEvent] = useMap([]);

  React.useEffect(() => {
    selectMapEvent.reset();
  }, [id]);

  // 全部选中的二级分类 list
  const selectClassify2 = useCreation(() => {
    let list = [];
    [...selectMap.values()].forEach((item) => {
      list = list.concat([...item.values()]);
    });

    return list;
  }, [selectMap]);

  // 全部选中的二级分类id list
  const selectClassifyIds = useCreation(() => {
    return selectClassify2.map((item) => {
      return item.id;
    });
  }, [selectClassify2]);

  // 未被选的一级分类
  const notSelectClassify1 = useCreation(() => {
    return [...classify1Map.values()].filter((item) => {
      return !selectMap.get(item.id) || selectMap.get(item.id).size === 0;
    });
  }, [selectMap, classify1Map]);

  // 总价
  const totalAmount = useCreation(() => {
    let money = discountAmount || amount;
    selectClassify2.forEach((item) => {
      money += item.amount || 0;
    });
    return money;
  }, [discountAmount, amount, selectClassify2]);

  return (
    <Portal>
      <Modal
        animationType="slide"
        visible={showSelect}
        onDismiss={() => changeSelect(false)}
        contentContainerStyle={styles.contentContainerStyle}
      >
        <Flex align="stretch">
          <Image
            w={80}
            h={80}
            style={styles.icon}
            resizeMode="cover"
            source={{ uri: img }}
          />
          <Flex.Item style={styles.info}>
            <Text size="s1" bold>
              {name}
            </Text>
            {selectClassify2.length !== 0 && (
              <Text fontSize="sm" color="gray300">
                已选择{' '}
                {selectClassify2
                  .map((item) => {
                    return item.name;
                  })
                  .join('/')}
              </Text>
            )}

            <Flex.Item />
            <Text fontSize="sm" color="red500">
              ¥{totalAmount}
              {discountAmount !== null && (
                <Text
                  textdecorationline="line-through"
                  fontSize="sm"
                  color="gray300"
                  ml={10}
                >
                  ¥{amount}
                </Text>
              )}
            </Text>
          </Flex.Item>
          {/* <Plus
            plusEvent={() => {
              addCart(id);
            }}
          /> */}
        </Flex>

        <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
          {selectspecifications.map((item) => {
            return (
              <Div key={item.id} py={20}>
                <Text>{item.name}</Text>
                <Div row flexWrap="wrap">
                  {item.children.map((child) => {
                    const choosed = selectClassifyIds.indexOf(child.id) !== -1;

                    return (
                      <Div key={child.id} w="33.33%" px={5} mt={5}>
                        <Button
                          rounded="xs"
                          bg={choosed ? 'brand200' : 'gray200'}
                          color={choosed ? 'brand500' : 'gray600'}
                          fontSize="xs"
                          block
                          onPress={() => {
                            if (choosed) {
                              const selects = selectMapEvent.get(child.parent);
                              selects.delete(child.id);
                              selectMapEvent.set(child.parent, selects);
                            } else if (
                              classify1Map.get(child.parent).multiple &&
                              selectMapEvent.get(child.parent)
                            ) {
                              const selects = selectMapEvent.get(child.parent);
                              selects.set(child.id, child);
                              selectMapEvent.set(child.parent, selects);
                            } else {
                              selectMapEvent.set(
                                child.parent,
                                new Map([[child.id, child]])
                              );
                            }
                          }}
                        >
                          {child.name}
                        </Button>
                      </Div>
                    );
                  })}
                </Div>
              </Div>
            );
          })}
        </ScrollView>

        <Button
          disabled={notSelectClassify1.length}
          block
          bg="brand500"
          fontSize="xl"
          onPress={() => addCart(id, selectClassifyIds.join(','), 1)}
        >
          选好了
        </Button>
      </Modal>
    </Portal>
  );
}

const styles = StyleSheet.create({
  contentContainerStyle: {
    backgroundColor: '#fff',
    height: '70%',
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 20,
    justifyContent: 'flex-start',
    zIndex: 3,
  },
  icon: {
    width: 80,
    height: 80,
    borderRadius: 3,
  },
  info: {
    marginLeft: 8,
  },
  list: {
    paddingTop: 15,
  },
});
