import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  FlatList,
  ScrollView,
} from 'react-native';
import FastImage from 'react-native-fast-image';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Icon2 from 'react-native-vector-icons/MaterialCommunityIcons';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import history from '../../common/history';
import LoadingView from '../../common/loading';

import NaviBar from '../../components/navi-bar';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Migrations from '../../services/realm/Mirgrations';
import RepairList from './repairList';
import {inject, observer} from 'mobx-react';
import {queryUser} from '../../services/realm/realmManger';
import BackHeader from '../../components/backHeader';
//import Swiper from 'react-native-swiper'
import Swiper from 'react-native-swiper';
import Global from '../../services/Global';
import {width, height} from '../../common/screen';
import AddFunction from '../../common/addFunction';
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const {SlideInMenu} = renderers;
import * as rssParser from 'react-native-rss-parser';
import Realm from 'realm';
import {observable, set} from 'mobx';
import {func} from 'prop-types';
let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});
const selectItems = [
  [
    {name: '室內設計', icon: 'pencil-ruler', color: '#FFAB46'},
    {name: '清潔服務', icon: 'broom', color: '#485FC8'},
  ],

  [
    {name: '搬屋運輸', icon: 'shipping-fast', color: '#D6147A'},
    {name: '開鎖配匙', icon: 'pencil-ruler', color: '#4E96D4'},
  ],

  [
    {name: '水電維修', icon: 'tools', color: '#E8D238'},
    {name: '油漆牆紙', icon: 'paint-roller', color: '#64B1B6'},
  ],

  [
    {name: '鋁窗鋼閘', icon: 'warehouse', color: '#454F9B'},
    {name: '雲石磁磚', icon: 'clone', color: '#5667EF'},
  ],

  [
    {name: '地板工程', icon: 'shoe-prints', color: '#519CAB'},
    {name: '電器燈飾', icon: 'lightbulb', color: '#35466B'},
  ],
];
@inject('appStore')
@observer
export default class Repair extends Component<Props> {
  @observable
  news = [];
  @observable
  areaA = ['全部'];
  @observable
  areaB = ['全部'];
  @observable
  dropdownListDisable = true;
  @observable
  repairData = null;
  @observable
  areaAData = null;
  @observable
  areaAValue = '';
  @observable
  areaBValue = '';
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }
  static navigationOptions = ({navigation}) => {
    const {params = {}} = navigation.state;
    return {
      tabBarLabel: params.handleThis,
    };
  };

  async componentWillMount() {
    //this.loadNews()
    this.props.navigation.setParams({
      handleThis: this.store.text.maintenance,
    });
    await this.store.getRepairInfo();
   // this.store.getbanner();
    this.repairData = [...this.store.repairData];
    await this.getAreaA();
  }

  async getAreaA() {
    this.dropdownListDisable = true;
    this.repairData = [...this.store.repairData];
    this.areaAData = [...this.store.repairData];
    this.areaB = ['全部'];
    this.areaAValue = '全部';
    this.areaBValue = '全部';
    var array = ['全部'];
    await this.store.repairData.map((items, index) => {
      array.push(items.loc1);
    });

    const uniqueSet = new Set(array);
    const backToArray = [...uniqueSet];
    this.areaA = backToArray;

    //Array.from(new Set(array))
    console.log(backToArray);
  }

  async areaADropDownListOnSelect(value) {
    console.log(index);
    this.areaAValue = value;
    var index = this.areaA.findIndex(element => element == value);
    if (index == 0) {
      this.dropdownListDisable = true;
      this.repairData = [...this.store.repairData];
      this.areaAData = [...this.store.repairData];
      this.areaB = ['全部'];
      this.areaBValue = '全部';
      // this.repairData = repairData.filter(item => item.loc1 === value);
    } else {
      this.dropdownListDisable = false;
      var newData = await this.store.repairData.filter(function(item) {
        return item.loc1 == value;
      });
      this.repairData = [...newData];
      this.areaAData = [...newData];
      var array = ['全部'];
      await this.repairData.map((items, index) => {
        array.push(items.loc2);
      });
      const uniqueSet = new Set(array);
      const backToArray = [...uniqueSet];
      this.areaB = backToArray;
    }
  }

  async areaBDropDownListOnSelect(value) {
    this.areaBValue = value;
    var index = this.areaB.findIndex(element => element == value);
    if (index == 0) {
      this.repairData = [...this.areaAData];
      // this.repairData = repairData.filter(item => item.loc1 === value);
    } else {
      var newData = await this.areaAData.filter(function(item) {
        return item.loc2 == value;
      });
      this.repairData = [...newData];
    }
  }

  async serviceFilterAction(service) {
    this.areaAValue = '全部';
    this.areaBValue = '全部';

    var newData = await this.store.repairData.filter(function(item) {
      return item.project == service;
    });
    this.repairData = [...newData];
    this.flatListRef.scrollToOffset({animated: true, offset: 0});
  }

  render() {
    return (
      <MenuProvider style={styles.container}>
        <LoadingView visible={this.store.loading} />
        <BackHeader
          title={this.store.text.homeservice}
          back={true}
          instance={this}
        />
        <ScrollView>
          <View
            style={{
              height: scale(198),
              width: width,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Swiper
              removeClippedSubviews={false}
              style={{
                height: scale(198),
                justifyContent: 'center',
                alignItems: 'center',
              }}
              activeDotColor={colors.mainColor}>
              {this.store.banner.map((items, index) => {
                console.log(items);
                return (
                  <TouchableOpacity
                    onPress={() => {
                      if (items.hasOwnProperty('link')) {
                        history.push(this, '/bannerDetails', {data: items});
                      }
                    }}
                    style={{
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}>
                    <Image
                      source={{uri: items.image}}
                      style={{width: width, height: scale(198)}}
                      resizeMode="contain"
                    />
                  </TouchableOpacity>
                );
              })}
            </Swiper>
          </View>
          <View style={{margin: 10}}>
            <Text style={{fontSize: 22, fontFamily: Fonts.ubuntu}}>
              {'服務分類'}
            </Text>
            <ScrollView horizontal={true}>
              {selectItems.map((items, index) => {
                return (
                  <View
                    style={{
                      flexDirection: 'column',
                      marginRight: 25,
                    }}>
                    <View>
                      {items.map((selectObj, objIndex) => {
                        return (
                          <TouchableOpacity
                            style={{
                              marginTop: 20,
                              justifyContent: 'center',
                              alignItems: 'center',
                            }}
                            onPress={() => {
                              this.serviceFilterAction(selectObj.name);
                            }}>
                            <View
                              style={{
                                justifyContent: 'center',
                                alignItems: 'center',
                                width: 50,
                                height: 50,
                                borderRadius: 50,
                                backgroundColor: selectObj.color,
                              }}>
                              <Icon
                                name={selectObj.icon}
                                color="white"
                                size={25}
                              />
                            </View>
                            <Text
                              style={{fontFamily: Fonts.ubuntu, marginTop: 10}}>
                              {selectObj.name}
                            </Text>
                          </TouchableOpacity>
                        );
                      })}
                    </View>
                  </View>
                );
              })}
            </ScrollView>
          </View>

          <View
            style={{
              width: width,
              height: 50,
              flexDirection: 'row',
              alignItems: 'center',
            }}>
            <View
              style={{
                flex: 0.5,
                marginLeft: 10,
                flexDirection: 'row',
                alignItems: 'center',
              }}>
              <View
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'row',
                }}>
                <Icon
                  name="map-marker-alt"
                  color={colors.mainColor}
                  size={17}
                />
                <Text
                  style={{
                    color: colors.mainColor,
                    marginLeft: 5,
                    fontFamily: Fonts.ubuntu,
                  }}>
                  {this.store.text.region}
                </Text>
              </View>
              <View>
                <Menu
                  name="area1"
                  renderer={SlideInMenu}
                  onSelect={value => {
                    this.areaADropDownListOnSelect(value);
                    //this.flatListRef.scrollToOffset({animated: true, offset: 0});
                  }}>
                  <MenuTrigger style={{flexDirection: 'row'}}>
                    <Text
                      style={{
                        fontFamily: Fonts.ubuntu,
                        color: colors.mainColor,
                        marginLeft:5,
                      }}>
                      {this.areaAValue}
                    </Text>
                  </MenuTrigger>
                  <MenuOptions
                    customStyles={{
                      optionText: {
                        margin: 5,
                        fontFamily: Fonts.ubuntu,
                        color: 'white',
                        fontSize: 20,
                      },
                      optionWrapper: {
                        backgroundColor: colors.mainColor,
                        alignItems: 'center',
                      },
                    }}>
                    {this.areaA.map((obj, i) => {
                      console.log(obj);
                      return <MenuOption value={obj} text={obj} />;
                    })}
                  </MenuOptions>
                </Menu>
              </View>
            </View>
            <View
              style={{
                flex: 0.5,
                flexDirection: 'row',
                alignItems: 'center',
              }}>
              <View
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'row',
                }}>
                <Icon
                  name="map-marker-alt"
                  color={colors.mainColor}
                  size={17}
                />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    color: colors.mainColor,
                    marginLeft: 5,
                  }}>
                 {this.store.text.district}
                </Text>
              </View>

              <Menu
                name="area2"
                renderer={SlideInMenu}
                onSelect={value => {
                  this.areaBDropDownListOnSelect(value);
                  this.flatListRef.scrollToOffset({animated: true, offset: 0});
                }}>
                <MenuTrigger
                  disabled={this.dropdownListDisable}
                  style={{flexDirection: 'row'}}>
                  <Text
                    style={{fontFamily: Fonts.ubuntu, color: colors.mainColor,marginLeft:5}}>
                    {this.areaBValue}
                  </Text>
                </MenuTrigger>
                <MenuOptions
                  customStyles={{
                    optionText: {
                      margin: 5,
                      fontFamily: Fonts.ubuntu,
                      color: 'white',
                      fontSize: 20,
                    },
                    optionWrapper: {
                      backgroundColor: colors.mainColor,
                      alignItems: 'center',
                    },
                  }}>
                  <ScrollView style={{maxHeight: 300}}>
                    {this.areaB.map((obj, i) => {
                      return <MenuOption value={obj} text={obj} />;
                    })}
                  </ScrollView>
                </MenuOptions>
              </Menu>
            </View>
          </View>

          <FlatList
            ref={ref => {
              this.flatListRef = ref;
            }}
            data={this.repairData}
            renderItem={({item}) => (
              <RepairList
                items={item}
                onPress={() => {
                  history.push(this, '/repairDetails', {repairData: item});
                }}
              />
            )}
            keyExtractor={item => item.id}
          />
        </ScrollView>
      </MenuProvider>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button: {
    borderWidth: 1,
    borderColor: '#000000',
    margin: 5,
    padding: 5,
    width: '70%',
    backgroundColor: '#DDDDDD',
    borderRadius: 5,
  },
  textField: {
    borderWidth: 1,
    borderColor: '#AAAAAA',
    margin: 5,
    padding: 5,
    width: '70%',
  },
  spacer: {
    height: 10,
  },
  title: {
    fontWeight: 'bold',
    fontSize: 20,
    textAlign: 'center',
  },
});
