import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { StyleSheet, View } from 'react-native';
import { Div, Button, Image, Text, Tag } from 'react-native-magnus';
import { TextareaItem } from '@ant-design/react-native';
import { ScrollView } from 'react-native-gesture-handler';

import { useRoute } from '@react-navigation/native';
import { useCreation, useRequest, useSet } from '@umijs/hooks';
import { useTranslation } from 'react-i18next';

import useModel from 'flooks';
import Order from './model'; // Order模块通用方法

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

import ImagePicker from '../../components/ImagePicker';
import Choose from '../../components/Choose';
import ChooseMerchant from '../../components/ChooseMerchant';

const map = new Map([
  [
    'bad',
    [
      '不送上楼',
      '着装脏乱',
      '服务态度差',
      '未带保温箱',
      '食品凉了',
      '额外索取费用',
      '配送慢',
      '提前点送达',
    ],
  ],
  ['normal', ['味道一般', '速度很慢']],
  ['good', ['超好吃', '超级慢']],
]);

export default function EvaluateScreen({ navigation }) {
  const { t } = useTranslation();
  const { userAppraisal } = useModel(Order, []);

  const route = useRoute();
  const { params } = route;
  const { orderId } = params || {};

  const [orderInfo, setorderInfo] = React.useState({ merchant: {} });
  const [choose, setchoose] = React.useState('');
  const [chooseMer, setchooseMer] = React.useState('');
  const [content, setcontent] = React.useState('');

  const [imgList, setimgList] = React.useState(['']);
  const [content2, setcontent2] = React.useState('');

  function changeImg(img, index) {
    const list = [...imgList];
    if (!img) {
      list.splice(index, 1);
    } else {
      list.splice(index, 1, img);
    }
    if (index === list.length - 1 && list.length < 4) {
      list.push('');
    }
    setimgList(list);
  }

  function deleteImg(index) {
    const list = [...imgList];
    if (!list[index]) {
      return null;
    } else {
      return () => changeImg('', index);
    }
  }

  const [tags, tagEvent] = useSet([]);
  React.useEffect(() => {
    tagEvent.reset();
  }, [choose]);

  const { merShowName, merchantId, riderId, merLogo } = orderInfo;

  useRequest(() => `/orderInfo/get/${orderId}`, {
    refreshDeps: [orderId],
    onSuccess: (result) => {
      setorderInfo(result);
    },
  });

  function submit() {
    const img = [...imgList].filter((item) => {
      return item;
    });
    const riderScore = [...map.keys()].indexOf(choose);
    userAppraisal(
      orderId,
      merchantId,
      riderId,
      img,
      chooseMer === 'good',
      content2,
      riderScore,
      content + [...Array.from(tags)].join(',')
    ).then(() => {
      navigation.goBack();
    });
  }

  const canSubmit = useCreation(() => {
    if (orderId && choose && chooseMer) {
      return true;
    } else {
      return false;
    }
  }, [orderId, choose, chooseMer, content, imgList, content2]);

  return (
    <>
      <Header title={t('tip3')} />
      <ScrollView contentContainerStyle={styles.scroll}>
        <View style={styles.card}>
          <Div row alignItems="center">
            <Image
              h={40}
              w={40}
              rounded="sm"
              source={{
                uri: 'https://picsum.photos/700',
              }}
            />
            <Text
              fontSize="xl"
              fontWeight="bold"
              textAlign="left"
              flex={1}
              mx={8}
            >
              猪猪费
            </Text>
            <Text fontSize="xs" color="gray300" textAlign="left">
              {t('tipss4')}
            </Text>
          </Div>
          <Choose chooseValue={choose} changeValue={setchoose} />

          {!!choose && (
            <Div row flexWrap="wrap" py={14}>
              {map.get(choose).map((item, index) => {
                const isChoose = tagEvent.has(item);
                return (
                  <Tag
                    key={index}
                    ml="sm"
                    mb="sm"
                    fontSize="xs"
                    borderColor={isChoose ? 'white' : 'gray300'}
                    borderWidth={1}
                    color={isChoose ? 'white' : 'gray400'}
                    bg={isChoose ? 'brand500' : 'hide'}
                    onPress={() => {
                      if (isChoose) {
                        tagEvent.remove(item);
                      } else {
                        tagEvent.add(item);
                      }
                    }}
                  >
                    {item}
                  </Tag>
                );
              })}
            </Div>
          )}

          <TextareaItem
            rows={4}
            placeholder={t('content2')}
            style={styles.text}
            count={100}
            onChange={setcontent}
          />
        </View>
        <View style={styles.card}>
          <Div row alignItems="center">
            <Image
              h={40}
              w={40}
              rounded="sm"
              source={{
                uri: merLogo,
              }}
            />
            <Text fontSize="xl" fontWeight="bold" flex={1} mx={8}>
              {merShowName || ' '}
            </Text>
            <Text fontSize="xs" color="gray300" textAlign="left">
              {t('yi-dui-shang-jia-ni-ming')}
            </Text>
          </Div>
          <ChooseMerchant chooseValue={chooseMer} changeValue={setchooseMer} />

          <Div pt={10} />

          <TextareaItem
            rows={4}
            placeholder={t('content2')}
            style={styles.text}
            count={100}
            onChange={setcontent2}
          />

          <Div row mt={10}>
            {imgList.map((item, index) => {
              return (
                <ImagePicker
                  key={index}
                  img={item}
                  setImg={(img) => changeImg(img, index)}
                  cancelEvent={deleteImg(index)}
                />
              );
            })}
          </Div>
        </View>

        <Button
          block
          bg="brand500"
          color="white"
          my={5}
          mx={10}
          onPress={submit}
          disabled={!canSubmit}
        >
          {t('ti-jiao')}
        </Button>
      </ScrollView>
    </>
  );
}

const styles = StyleSheet.create({
  scroll: {
    paddingVertical: 10,
  },
  card: {
    paddingHorizontal: 15,
    paddingVertical: 20,
    backgroundColor: '#fff',
    marginBottom: 10,
  },
  item: {
    paddingVertical: 5,
  },
  main: {
    paddingVertical: 5,
  },
  bottom: {
    paddingVertical: 10,
  },
  textarea: {
    marginVertical: 10,
  },
  text: {
    backgroundColor: '#eeeeee',
    paddingVertical: 10,
    fontSize: 10,
    borderBottomWidth: 0,
  },
});
