import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  NativeAppEventEmitter,
  Share,
  TextInput,
  TouchableHighlight,
  RefreshControl,
  ScrollView,
  Alert,
  Linking,
} from 'react-native';
//import { NimSession, NimFriend } from "react-native-netease-im";
import ImageView from 'react-native-image-viewing';
import ImageHeader from '../../components/imageHeader';
import {
  TabView,
  SceneMap,
  TabBar,
  TabViewAnimated,
} from 'react-native-tab-view';
import ImageFooter from '../../components/imageFooter';
import moment from 'moment';
import {SearchBar} from 'react-native-elements';
import JMessage from 'jmessage-react-plugin';
import Icon from 'react-native-vector-icons/FontAwesome5';
import LoadingView from '../../common/loading';
import HomeTut from '../tutorial/homeTut';
import HomeTut2 from '../tutorial/homeTut2';
import FastImage from 'react-native-fast-image';
import Modal, {ModalContent} from 'react-native-modals';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import DeviceInfo from 'react-native-device-info';
import history from '../../common/history';
import Toast, {DURATION} from 'react-native-easy-toast';
var RNFS = require('react-native-fs');
import {withNavigation} from 'react-navigation';
import NaviBar from '../../components/navi-bar';
import building from '../../services/building.json';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Migrations from '../../services/realm/Mirgrations';
var _ = require('lodash');
import {inject, observer} from 'mobx-react';
import {queryUser} from '../../services/realm/realmManger';
import Swiper from 'react-native-swiper';
import Global from '../../services/Global';
import JPush from 'jpush-react-native';
import AddFunction from '../../common/addFunction';
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';
import {width, height} from '../../common/screen';
import Size from '../../common/size';
const size = new Size();
import Realm from 'realm';
import {observable} from 'mobx';
import {Colors} from 'react-native-paper';
import {thisExpression} from '@babel/types';

let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});
@inject('appStore')
@observer
class Home extends Component {
  @observable
  sessionId = 'dff';
  @observable
  docVisable = false;
  @observable
  index = 0;
  @observable
  shareVisable = false;
  @observable
  friendList = [];
  @observable
  refcode = '';
  @observable
  visable = false;
  @observable
  showNotAddTenantApartmentOrNot = false;
  @observable
  imageIndex = 0;
  @observable
  tabState = {
    index: 0,
    routes: [
      {key: 'first', title: '物業'},
      {key: 'second', title: '未加入租客'},
    ],
  };

  @observable
  renderScene = SceneMap({
    first: this.renderAllApartment,
    second: this.renderNoTenantApartment,
  });

  state = {
    index: 0,
    routes: [
      {key: 'first', title: '物業', show: false},
      {key: 'second', title: '未加入租客', show: true},
    ],
  };

  constructor(props) {
    super(props);
    this.store = props.appStore;
    Global.instance = this;
    this.reloadFriendList = this.reloadFriendList.bind(this);
  }
  static navigationOptions = {
    tabBarLabel: 'test',
    headerStyle: {
      shadowColor: 'transparent',
      backgroundColor: '#fff',
      borderTopWidth: 0,
      elevation: 0,
      shadowOpacity: 0,
      shadowRadius: 0,
      shadowOffset: {
        height: 0,
      },
    },
    style: {
      shadowColor: 'transparent',
      shadowRadius: 0,
      elevation: 0,
      shadowOffset: {
        height: 0,
      },
    },
  };

  oneKeyToRent(apartmentName, apartmentId) {
    var msgContent =
      '你好，我想放盤，我的單位名是' +
      apartmentName +
      '(ID: ' +
      apartmentId +
      ')';
    Alert.alert(
      '一鍵放盤',
      '一鍵放盤需由Rent Chat客服處理，請選擇與客服聯絡方法',
      [
        {
          text: '取消',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: '致電 Rent Chat',
          onPress: () => {
            Linking.openURL(`tel:${'31040558'}`);
          },
        },
        {
          text: '在線對話',
          onPress: () => this.store.gotohelperChat(this, msgContent),
        },
      ],
      {cancelable: false},
    );
  }

  refinput() {
    return (
      <View
        style={{
          backgroundColor: colors.inputBgc,
          alignItems: 'center',
          justifyContent: 'center',
          height: 40,
          borderRadius: 12,
          width: 200,
        }}>
        <TextInput
          style={{
            color: colors.mainColor,
            fontSize: 15,
            fontFamily: Fonts.ubuntuL,
            alignSelf: 'stretch',
            textAlign: 'center',
          }}
          onChangeText={text => (this.refcode = text)}
          keyboardType={'numeric'}
          underlineColorAndroid="rgba(0,0,0,0)"
          placeholder={this.store.text.sharecode}
          placeholderStyle={{
            fontWeight: 'bold',
            fontFamily: Fonts.century,
            fontSize: size.getSize(10),
          }}
          placeholderTextColor={colors.textColor}
        />
      </View>
    );
  }

  async clickAvatarAction(index) {
    await this.store.cloneApartmentDocData(index);
    var avatarIndex = await this.store.apartmentDataDoc.findIndex(
      element => element.type === 3,
    );
    // history.push(this, '/apartmentImageDetails', {
    //   imageIndex: avatarIndex,
    // });
    this.visable = true;
    this.imageIndex = avatarIndex;
    console.log(avatarIndex);
  }

  reloadFriendList() {
    JMessage.getFriends(
      result => {
        var friendArr = result.map((friend, index) => {
          var element = {};
          element.key = index;
          element.userInfo = friend;
          return element;
        });
        // this.setState( {data: friendArr} )
        console.log(friendArr);
        this.store.friendArr = friendArr;
      },
      error => {
        Alert.alert('error', JSON.stringify(error));
      },
    );
  }

  iconRander() {
    return (
      <TouchableHighlight
        style={styles.buttonView}
        onPress={() => {
          var data = {refcode: this.refcode};
          this.store.tenantCheckApartment(data, this);
        }}>
        <Text style={styles.buttonText}>Add</Text>
      </TouchableHighlight>
    );
  }

  // async _check(id) {
  //   var data = null;
  //   await NimFriend.fetchUserInfo(id).then(res => {
  //     console.log(res);
  //     data = res;
  //   });
  //   return data;
  // }

  async componentWillMount() {
    // const unsubscribe = this.props.navigation.addListener('tabPress', e => {
    //   // Prevent default behavior
    //   //e.preventDefault();
    // //  this.props.navigation.navigate('add')
    //   // Do something manually
    //   // ...
    //   this.props.navigation.navigate('signin',{icon:true})
    // });
    // if(this.store.logined){
    //   this.store.getApartmentData()
    // }

    await this.store.loadLocalData();
    // this._check();
    // NimFriend.startFriendList();
    if (this.store.logined) {
      this.reloadConversationList();
      JMessage.getAllUnreadCount(result => {
        console.log(result);
        /**
         * result {Number} 当前用户所有会话的未读消息总数
         */
      });
    }
    // var friendListData = [];
    // this.sessionListener = NativeAppEventEmitter.addListener(
    //   'observeRecentContact',
    //   data => {
    //     console.info('会话列表', data);
    //     this.store.checkUnRead(data);
    //   },
    // );
    // this.friendListener = NativeAppEventEmitter.addListener(
    //   'observeFriend',
    //   data => {
    //     console.log(data);
    //     this.store.friendList = [];

    //     if (!this.isEmpty(data)) {
    //       // (this.friendList = this.formatData(data)),

    //       Object.keys(data).map((key, index) => {
    //         //friendListData.push(_.cloneDeep(this.friendList[key]))
    //         data[key].map((value, index) => {
    //           this.store.friendList.push(_.cloneDeep(value));
    //         });
    //         // console.log(this.friendList[key])
    //       });
    //       this.store.friendList.map((data, index) => {
    //         console.log(data.name);
    //       });

    //       console.log(
    //         this.store.friendList.find(element => element.name === 'Helper'),
    //       );

    //       //  this._check(this.friendList.H[0].contactId);
    //     }
    //   },
    // );

    // this.backgroundNotificationListener = NativeAppEventEmitter.addListener(
    //   'observeLaunchPushEvent',
    //   data => {
    //     console.log(data);
    //     // this.sessionId = data.sessionBody.sessionId;
    //   },
    // );
  }

  componentWillUnmount() {
    this.focusListener.remove();
  }

  queryUser = () => {
    return realm.objects('User');
  };
  componentDidMount() {
    const {navigation} = this.props;
    this.focusListener = navigation.addListener('didFocus', () => {
      console.log('home focus');
      this.store.startTut();
    });
    JMessage.setDebugMode({
      enable: false,
    });
    if (this.store.logined) {
      JMessage.addReceiveMessageListener(message => {
        this.reloadConversationList();
      });
      JMessage.addSyncRoamingMessageListener(result => {
        var conv = result.conversation;
        console.log('Receive roaming conversation: ' + JSON.stringify(conv));
        this.store.insertConversation(conv);
      });
      this.store.reloadFriendList();
    }

    // var friendListData = [];
    // this.sessionListener = NativeAppEventEmitter.addListener(
    //   "observeRecentContact",
    //   data => {
    //     // this.setState({
    //     //   data: data.recents,
    //     // })
    //     console.info("会话列表", data);
    //   }
    // );
    // this.friendListener = NativeAppEventEmitter.addListener(
    //   "observeFriend",
    //   data => {
    //     console.log(data);
    //     this.store.friendList = []
    //     if (!this.isEmpty(data)) {
    //       // (this.friendList = this.formatData(data)),
    //       Object.keys(data).map((key, index) => {
    //         //friendListData.push(_.cloneDeep(this.friendList[key]))
    //         data[key].map((value, index) => {
    //           this.store.friendList.push(_.cloneDeep(value));
    //         });
    //         // console.log(this.friendList[key])
    //       });
    //       this.store.friendList.map((data, index) => {
    //         console.log(data.name);
    //       });
    //       console.log(
    //         this.store.friendList.find(element => element.name === "Helper")
    //       );
    //       //  this._check(this.friendList.H[0].contactId);
    //     }
    //   }
    // );
    // this.backgroundNotificationListener = NativeAppEventEmitter.addListener(
    //   "observeLaunchPushEvent",
    //   data => {
    //     console.log(data);
    //    // this.sessionId = data.sessionBody.sessionId;
    //   }
    // );
  }

  reloadConversationList() {
    JMessage.getConversations(
      result => {
        this.store.convertToConvList(result);
      },
      error => {
        // Alert.alert(JSON.stringify(error))
        console.log(JSON.stringify(error));
      },
    );
  }
  isEmpty(obj) {
    for (var x in obj) {
      if (obj.hasOwnProperty(x)) return false;
    }
    return true;
  }

  list(title, contents, color) {
    return (
      <View
        style={{
          flexDirection: 'row',
          marginRight: 5,
          marginLeft: 5,
          marginTop: 10,
          width: scale(265),
        }}>
        <View style={{}}>
          <Text
            style={{
              fontFamily: Fonts.ubuntuTh,
              color: colors.textColor,
              fontSize: 20,
            }}>
            {title + ':    '}
          </Text>
        </View>
        <View style={{}}>
          <Text
            style={{fontFamily: Fonts.ubuntuTh, color: 'black', fontSize: 20}}>
            {contents.length < 20
              ? `${contents}`
              : `${contents.substring(0, 40)}...`}
          </Text>
        </View>
      </View>
    );
  }

  isValidDate(date) {
    return (
      date &&
      Object.prototype.toString.call(date) === '[object Date]' &&
      !isNaN(date)
    );
  }

  ownerSignReturn(items) {
    if (items.owner.hasOwnProperty('sign')) {
      console.log(items.owner.sign);
      return items.owner.sign;
    } else {
      return '';
    }
  }

  signImageReturn(items, apartmentdata) {
    console.log(apartmentdata);
    if (apartmentdata.signed) {
      return apartmentdata.tenantSign;
    } else {
      return '';
    }
  }

  async contractClickAction(items, state) {
    console.log(state);
    console.log(items);
    if (items.contracts.length > 0) {
      var contractindex = await items.contracts.findIndex(
        element => element.tenant.id === items.tenant.id,
      );

      if (contractindex !== -1) {
        var apartmentdata = items.contracts[contractindex];

        console.log(apartmentdata);
        console.log(items);
        var data = {
          apartment: apartmentdata.id,
          appliances: apartmentdata.appliances,
          key: apartmentdata.key,
          atleastRentOfmonth: apartmentdata.atleastRentOfmonth,
          leaseMonth: apartmentdata.leaseMonth,
          monthOfpaymentInLieuOfNotice:
            apartmentdata.monthOfpaymentInLieuOfNotice,
          noteLeasebackMonth: apartmentdata.noteLeasebackMonth,
          numberOfkey: apartmentdata.numberOfkey,
          ownerPaymentAc: apartmentdata.ownerPaymentAc,
          payRentDate: apartmentdata.payRentDate,
          rentFreePeriod: apartmentdata.rentFreePeriod,
          servicePaymentAmount: apartmentdata.servicePaymentAmount,
          servicePaymentStatus: apartmentdata.servicePaymentStatus,
          whoPayGovernemtRate: apartmentdata.whoPayGovernemtRate,
          whoPayGovernmentRent: apartmentdata.whoPayGovernmentRent,
          whoPayManagementFee: apartmentdata.whoPayManagementFee,
          apartmentName: items.name,
          apartmentAddress: apartmentdata.apartmentAddress,
          services: apartmentdata.services,
          ownerId: apartmentdata.owner.id,
          ownerName: apartmentdata.ownerName,
          ownerPhone: apartmentdata.ownerPhone,
          tenantName: apartmentdata.tenantName,
          tenantPhone: apartmentdata.tenantPhone,
          tenantContactAddress: apartmentdata.tenantContractAddress,
          signContractDate: moment(
            apartmentdata.signContractDate,
            'YYYY-MM-DD',
          ).toDate(),
          endContractDate: moment(
            apartmentdata.endContractDate,
            'YYYY-MM-DD',
          ).toDate(),
          rent: apartmentdata.rent,
          rates: apartmentdata.rates,
          deposit: apartmentdata.deposit,
          managementFee: apartmentdata.managementFee,
          id: apartmentdata.id,
          signed: apartmentdata.signed,
          remark: apartmentdata.remark,
          stamp: apartmentdata.ownerStamp,
          ownerSignUri: this.ownerSignReturn(items),
          tenantSignUri: this.signImageReturn(items, apartmentdata),
        };
        console.log(data);
        if (state == 'e') {
          history.push(this, '/newLease', {
            contractData: data,
            showSign: false,
          });
        } else if (state == 'p') {
          history.push(this, '/newLease', {
            contractData: data,
            showSign: false,
          });
        } else if (state === 's') {
          console.log('tenant not sign');
          if (this.store.loginUserData.data.member.hasOwnProperty('sign')) {
            history.push(this, '/newLease', {
              contractData: data,
              showSign: false,
            });
          } else {
            this.goToSignature();
          }
        }
      } else {
        if (state == 'c') {
          if (this.store.loginUserData.data.member.hasOwnProperty('sign')) {
            //  history.push(this, '/newContractData', {apartmentData: items});
            this.store.getService(this, items);
          } else {
            this.goToSignature();
          }
        }
      }
    } else {
      if (state === 'c') {
        console.log('go new contract');
        if (this.store.loginUserData.data.member.hasOwnProperty('sign')) {
          //   history.push(this, '/newContractData', {apartmentData: items});
          this.store.getService(this, items);
        } else {
          this.goToSignature();
        }
      }
    }
  }

  goToSignature() {
    Alert.alert('', this.store.text.puts, [
      {text: this.store.text.cancel, onPress: () => history.goBack(this)},
      {
        text: this.store.text.sure,
        onPress: async () => {
          history.push(this, '/signatureView', {
            imageUri: this.store.loginUserData.data.member.sign,
          });
        },
      },
    ]);
  }

  renderContractButton(items, index) {
    console.log(this.store.apartmentsData[index].state);
    console.log(this.store.apartmentsData[index].contractClickState);
    if (this.store.logined) {
      if (this.store.loginUserData.data.member.chara == 'owner') {
        if (items.hasOwnProperty('tenant')) {
          return (
            <View
              style={{
                flexDirection: 'row',
                marginRight: 5,
                marginLeft: 5,
                marginTop: 10,
                width: scale(265),
              }}>
              <View>
                <Text style={styles.apartmentText}>
                  {this.store.text.leaseContract + ':    '}
                </Text>
              </View>
              <TouchableOpacity
                onPress={() => {
                  this.contractClickAction(
                    items,
                    this.store.apartmentsData[index].contractClickState,
                  );
                }}>
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    color: colors.mainColor,
                    fontSize: 20,
                  }}>
                  {this.store.apartmentsData[index].state}
                </Text>
              </TouchableOpacity>
            </View>
          );
        } else {
          return <View></View>;
        }
      } else {
        if (items.hasOwnProperty('contracts')) {
          if (items.contracts.length > 0) {
            return (
              <View
                style={{
                  flexDirection: 'row',
                  marginRight: 5,
                  marginLeft: 5,
                  marginTop: 10,
                  width: scale(265),
                }}>
                <View>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntu,
                      color: colors.textColor,
                      fontSize: 20,
                    }}>
                    {this.store.text.leaseContract + ':    '}
                  </Text>
                </View>
                <TouchableOpacity
                  onPress={() => {
                    this.contractClickAction(
                      items,
                      this.store.apartmentsData[index].contractClickState,
                    );
                  }}>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntu,
                      color: colors.mainColor,
                      fontSize: 20,
                    }}>
                    {this.store.apartmentsData[index].state}
                  </Text>
                </TouchableOpacity>
              </View>
            );
          } else {
            return <View></View>;
          }
        }
      }
    } else {
      return <View></View>;
    }
  }

  contractStatesReturn(items) {
    if (items.hasOwnProperty('contracts')) {
      if (items.contracts.length > 0) {
        if (this.store.loginUserData.data.member.chara == 'owner') {
          if (
            items.contracts.findIndex(
              element => element.tenant.id == items.tenant,
            ) != -1
          ) {
            var index = items.contracts.findIndex(
              element => element.tenant.id == items.tenant,
            );
            if (items.contracts[index].signed) {
              return items.contracts[index].endContractDate;
            } else {
              return this.store.text.processing;
            }
          } else {
            return this.store.text.createContract;
          }
        } else {
          return this.store.text.pleaseSign;
        }
      } else {
        return this.store.text.createContract;
      }
    }
  }

  dateStringHandler(date) {
    console.log(this.isValidDate(date));
    if (date === null) {
      return '';
    } else {
      if (this.isValidDate(date)) {
        return (
          date.getDate() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getFullYear()
        );
      } else {
        return date;
      }
    }
  }

  share(refCode) {
    Share.share({
      message:
        `您的業主邀請你下載免費的租賃管理平台Rent Chat:\nRent Chat功能：\n-永久寄存租約-電子租金收據\n-單位及電器維修通知業主\n-電子租約續租\n\n分享碼：` +
        refCode,
      title: 'Ref Code',
      url: 'http://onelink.to/rentchat',
    });
  }

  renderShare() {
    if (this.store.refData == undefined || this.store.refData == null) {
      return null;
    } else {
      return (
        <View
          style={{
            alignItems: 'center',
            justifyContent: 'center',
            marginTop: 20,
          }}>
          <Text
            style={{
              fontFamily: Fonts.ubuntu,
              color: colors.textColor,
              fontSize: 22,
            }}>
            {'Refcode: '}
            <Text
              style={{
                fontFamily: Fonts.ubuntu,
                color: colors.mainColor,
                fontSize: 22,
              }}>
              {this.store.refData.refcode}
            </Text>
          </Text>

          <TouchableOpacity
            onPress={() => this.share(this.store.refData.refcode)}
            style={{
              backgroundColor: colors.mainColor,
              flexDirection: 'row',
              marginRight: 20,
              marginLeft: 20,
              marginTop: 20,
              alignItems: 'center',
              justifyContent: 'center',
              height: 40,
              width: 200,
              borderColor: colors.mainColor,
              borderRadius: 10,
            }}>
            <Icon
              name={'share-alt'}
              style={{color: 'white', position: 'absolute', left: 10}}
              size={22}
              solid
            />

            <Text
              style={{
                fontSize: 15,
                fontFamily: Fonts.ubuntu,
                color: 'white',
                alignItems: 'center',
              }}>
              Share
            </Text>
          </TouchableOpacity>
        </View>
      );
    }
  }

  tenantServiceAction(id) {
    if (this.store.logined) {
      if (this.store.loginUserData.data.member.phone == null) {
        Alert.alert('', this.store.text.papnf, [
          {text: '取消', onPress: () => history.goBack(this)},
          {
            text: '加入',
            onPress: async () => {
              await history.goBack(this);
              var data = {
                vercode: '',
                fullname: '',
                thirdParty: true,
                email: '',
                gender: 'na',
                countryCode: '852',
                chara: 'owner',
                age: 'na',
                pwd: '',
                phone: '',
                refcode: '',
                ownerPhone: '', // 如果char係租客就會有，OWNER就NULL
              };
              history.push(this, '/signUpVerify', {
                signupData: data,
                addphone: true,
              });
            },
          },
        ]);
      } else {
        this.store.createApartmentRefCode(id, this);
      }
    } else {
      history.push(this, '/signin', {icon: true});
    }
  }

  renderOwnerOrTenant(items) {
    if (this.store.user.memberType == 1) {
      return (
        <View>
          <Text style={styles.apartmentText}>
            {this.store.text.owner + ':    '}
          </Text>
        </View>
      );
    } else {
      return (
        <View>
          <Text style={styles.apartmentText}>
            {this.store.text.tenant + ':    '}
          </Text>
        </View>
      );
    }
  }

  renderGoToUserChatButton(items) {
    if (this.store.loginUserData.data.member.chara == 'tenant') {
      return (
        <TouchableOpacity
          onPress={() => {
            this.apartmentGoToChat(items);
            // this.store.goToChat(items.owner.email, this);
          }}>
          <Text
            style={{
              fontFamily: Fonts.ubuntu,
              color: colors.mainColor,
              fontSize: 20,
            }}>
            {items.owner.fullname}
          </Text>
        </TouchableOpacity>
      );
    } else {
      return (
        <TouchableOpacity
          onPress={() => {
            this.apartmentGoToChat(items);
            //   this.store.goToChat(items.tenant.email, this);
          }}>
          <Text
            style={{
              fontFamily: Fonts.ubuntu,
              color: colors.mainColor,
              fontSize: 20,
            }}>
            {items.tenant.fullname}
          </Text>
        </TouchableOpacity>
      );
    }
  }

  notificationStringReturn(day) {
    if (day === 0) {
      return this.store.text.nonotice;
    } else {
      return this.store.text.notice + day + this.store.text.before;
    }
  }

  endNotificationStringReturn(month) {
    if (month === 0) {
      return this.store.text.nonotice;
    } else {
      return this.store.text.notice + month + this.store.text.endBefore;
    }
  }

  floorStringReturn() {
    switch (this.store.apartmentData.floor) {
      case 'low':
        return this.store.text.low + this.store.text.floor;
        break;
      case 'middle':
        return this.store.text.middle + this.store.text.floor;
        break;
      case 'high':
        return this.store.text.high + this.store.text.floor;
        break;
    }
  }

  async checkUserChat(id) {
    console.log(id);
    if (this.store.friendArr.length > 0) {
      const user = await this.store.friendArr.find(
        element => element.userInfo.username === id,
      );
      console.log(user);
      if (user != undefined) {
        var data = {
          username: id,
          type: 'single',
          nickname: user.userInfo.nickname,
        };
        this.store.goToChat(data, this);
      }
    }
  }

  handleIndexChange = index => {
    console.log('testing: ' + index);
    this.setState({
      index,
    });
  };

  async gotohelperChat(id) {
    var data = {
      id: id,
      type: 'group',
      nickname: 'helper',
    };
    this.store.goToChat(data, this);
  }

  apartmentGoToChat(items) {
    //console.log(items.owner.email);
    if (this.store.logined) {
      if (this.store.loginUserData.data.member.chara == 'owner') {
        if (items.hasOwnProperty('tenant')) {
          this.checkUserChat(items.tenant.id);
          //this.store.goToChat(items.tenant.email, this,'single');
        } else {
          this.refs.toast.show('Please add tenant');
        }
      } else {
        if (items.hasOwnProperty('owner')) {
          // this.store.goToChat(items.owner.email, this,'single');
          this.checkUserChat(items.owner.id);
        } else {
        }
      }
    } else {
      this.refs.toast.show('Please login');
      history.push(this, '/signin', {icon: true, backToHome: this.backToHome});
    }
  }

  backToHome = back => {
    if (back) {
      this.props.navigation.navigate('home');
    }
  };

  formatData = data => {
    const newObj = {};
    const h = this.transform(data).sort();
    h.map(res => {
      newObj[res] = data[res];
    });
    return newObj;
  };
  transform(obj) {
    const arr = [];
    for (const item in obj) {
      arr.push(item);
    }
    //arr.sort(this.mySorter())
    return arr;
  }
  mySorter(a, b) {
    if (/^\d/.test(a) !== /^\D/.test(b)) return a > b ? 1 : (a = b ? 0 : -1);
    return a > b ? -1 : a == b ? 0 : 1;
  }

  renderRemindTenantPayTheRent(items) {
    if (this.store.logined) {
      if (this.store.loginUserData.data.member.chara == 'owner') {
        console.log(items.hasOwnProperty('tenant'));
        if (items.hasOwnProperty('tenant')) {
          return (
            <TouchableOpacity
              style={{marginLeft: 10}}
              onPress={() => {
                this.store.remindTenantPayTheRent(this, items);
              }}>
              <Text
                style={{
                  fontFamily: Fonts.ubuntu,
                  color: colors.mainColor,
                  fontSize: 20,
                }}>
                {'提醒租客交租'}
              </Text>
            </TouchableOpacity>
          );
        }
      }
    } else {
    }
  }

  rentdayreturn() {
    if (this.store.logined) {
      if (this.store.loginUserData.data.member.chara == 'owner') {
        return this.store.text.rentDay;
      } else {
        return this.store.text.payrentDay;
      }
    } else {
      return this.store.text.rentDay;
    }
  }

  renderavatar(items) {
    var data = _.cloneDeep(items);
    console.log(data);
    var avatarUriIndex = items.doc.findIndex(element => element.type === 1);
    if (avatarUriIndex !== -1) {
      return (
        <Image
          style={[
            {
              backgroundColor: '#F0F3F4',
              borderTopRightRadius: 15,
              borderTopLeftRadius: 15,
            },
            DeviceInfo.isTablet()
              ? {width: scale(275), height: verticalScale(320)}
              : {width: width - 20, height: verticalScale(150)},
          ]}
          //resizeMode={'contain'}
          source={{
            uri: items.doc[avatarUriIndex].uri,
          }}
        />
      );
    } else {
      return (
        <Image
          style={[
            {
              marginTop: 2,
              //width: scale(275),
              // height: verticalScale(200),
              borderTopRightRadius: 15,
              borderTopLeftRadius: 15,
              backgroundColor: '#F0F3F4',
            },
            DeviceInfo.isTablet()
              ? {width: scale(275), height: verticalScale(320)}
              : {width: width - 20, height: verticalScale(200)},
          ]}
          resizeMode={'cover'}
          source={require('../../assets/images/demohouse.png')}
        />
      );
    }
  }

  renderApartmentData(items, index) {
    return (
      <View key={index} style={styles.slide1}>
        <View
          style={[
            styles.shadowView,
            DeviceInfo.isTablet() ? {width: scale(280)} : {width: width - 20},
          ]}>
          {items.id === 'demo' ? (
            <Image
              style={[
                {
                  marginTop: 2,
                  //width: scale(275),
                  // height: verticalScale(200),

                  borderTopLeftRadius: 15,
                  borderTopRightRadius: 15,
                  backgroundColor: '#F0F3F4',
                },
                DeviceInfo.isTablet()
                  ? {width: scale(275), height: verticalScale(320)}
                  : {width: width - 20, height: verticalScale(200)},
              ]}
              resizeMode="cover"
              source={require('../../assets/images/demohouse.png')}
            />
          ) : (
            <TouchableOpacity
              onPress={() => {
                this.clickAvatarAction(index);
              }}>
              {this.renderavatar(items)}

              {!items.hasOwnProperty('tenant') ? (
                <View
                  style={{
                    flex: 1,
                    width: width - 20,
                    height: 60,
                    backgroundColor: '#F2F2F2',
                    position: 'absolute',
                    bottom: 0,
                    alignItems: 'center',
                    flexDirection: 'row',
                  }}>
                  <Icon name="user" size={30} style={{marginLeft: 20}} />
                  <View style={{marginLeft: 5}}>
                    <Text
                      style={{
                        fontFamily: Fonts.ubuntu,
                        fontSize: 17,
                        marginLeft: 3,
                      }}>
                      {'此物業尚未更新'}
                    </Text>
                    <Text style={{fontFamily: Fonts.ubuntuTh, fontSize: 16}}>
                      {' '}
                      {'請在租戶欄按下「新增租戶」'}
                    </Text>
                  </View>
                </View>
              ) : (
                <View />
              )}
            </TouchableOpacity>
          )}

          <View style={{marginLeft: 20, marginRight: 20}}>
            <Text style={[styles.text, {color: 'black'}]}>{items.name}</Text>
            {/* {this.list(
              this.store.text.address,
              items.address,
              colors.textColor,
            )} */}
            <Text
              style={[styles.text, {fontSize: 17, fontFamily: Fonts.ubuntuTh}]}>
              {items.address}
            </Text>

            <View
              style={{
                flexDirection: 'row',
                flex: 1,
                height: 40,
                marginLeft: 5,
              }}>
              <View style={styles.subAddress}>
                <Text
                  style={{
                    fontSize: 17,
                    color: colors.textColor,
                    fontFamily: Fonts.ubuntuTh,
                  }}>
                  {this.store.text.seats}
                </Text>
                <Text
                  style={{
                    fontSize: 17,
                    fontFamily: Fonts.ubuntuTh,
                    marginLeft: 5,
                  }}>
                  {items.seats == '' ? '--' : items.seats}
                </Text>
              </View>
              <View style={styles.subAddress}>
                <Text
                  style={{
                    fontSize: 17,
                    color: colors.textColor,
                    fontFamily: Fonts.ubuntuTh,
                  }}>
                  {this.store.text.floor}
                </Text>
                <Text
                  style={{
                    fontSize: 17,
                    fontFamily: Fonts.ubuntuTh,
                    marginLeft: 5,
                  }}>
                  {items.floor == '' ? '--' : items.floor}
                </Text>
              </View>
              <View style={styles.subAddress}>
                <Text
                  style={{
                    fontSize: 17,
                    color: colors.textColor,
                    fontFamily: Fonts.ubuntuTh,
                  }}>
                  {this.store.text.unit}
                </Text>
                <Text
                  style={{
                    fontSize: 17,
                    fontFamily: Fonts.ubuntuTh,
                    marginLeft: 5,
                  }}>
                  {items.seats == '' ? '--' : items.unit}
                </Text>
              </View>
            </View>
            <View
              style={{backgroundColor: '#EDEFF0', width: width - 40, height: 1}}
            />
            {this.list(
              this.store.text.rent,
              'HKD ' + items.rent,
              colors.textColor,
            )}

            {items.hasOwnProperty('deposit') ? (
              this.list(
                this.store.text.deposit,
                'HKD' + items.deposit,
                //items.signContractDate,
                colors.textColor,
              )
            ) : (
              <View />
            )}
            {/* {this.list(
        this.rentdayreturn(),
        this.dateStringHandler(items.signContractDate),
        //items.signContractDate,
        colors.textColor,
      )} */}
            <View
              style={{
                flexDirection: 'row',
                marginRight: 5,
                marginLeft: 5,
                marginTop: 10,
                width: scale(265),
                alignItems: 'center',
              }}>
              <View style={{}}>
                <Text style={styles.apartmentText}>
                  {this.rentdayreturn() + ':    '}
                </Text>
              </View>
              <View style={{}}>
                <Text style={[styles.apartmentText, {color: 'black'}]}>
                  {this.dateStringHandler(items.signContractDate)}
                </Text>
              </View>
              {this.renderRemindTenantPayTheRent(items)}
            </View>
            {this.list(
              this.store.text.contractExpiry,
              this.dateStringHandler(items.endContractDate),
              // items.endContractDate,
              colors.textColor,
            )}

            {this.list(
              this.store.text.maintainService,
              this.store.text.free,
              colors.mainColor,
            )}

            {this.list(
              this.store.text.notificationOfCollectRents,
              this.notificationStringReturn(items.rentNotification),
              colors.textColor,
            )}

            {this.list(
              this.store.text.notificationOfcontractExpiry,
              this.endNotificationStringReturn(
                this.store.apartmentData.endContractNotification,
              ),
              colors.textColor,
            )}

            {items.hasOwnProperty('leaseMonth') ? (
              this.list(
                this.store.text.lease,
                '' + items.leaseMonth + this.store.text.months,
                colors.textColor,
              )
            ) : (
              <View />
            )}

            <View
              style={{
                flexDirection: 'row',
                marginRight: 5,
                marginLeft: 5,
                marginTop: 10,
                width: scale(265),
              }}>
              <View style={{}}>{this.renderOwnerOrTenant()}</View>
              {items.hasOwnProperty('tenant') ? (
                this.renderGoToUserChatButton(items)
              ) : (
                <TouchableOpacity
                  onPress={() => {
                    this.tenantServiceAction(items.id);
                  }}>
                  <Text
                    style={{
                      fontFamily: Fonts.ubuntu,
                      color: colors.mainColor,
                      fontSize: 20,
                    }}>
                    {this.store.text.addTenantService}
                  </Text>
                </TouchableOpacity>
              )}
            </View>

            {this.renderContractButton(items, index)}
          </View>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              flex: 1,
              height: 50,
              marginTop: 20,
              alignItems: 'center',
              borderTopWidth: 1,
              borderTopColor: '#EDEFF0',
            }}>
            <TouchableOpacity
              style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'row',
              }}
              onPress={() => {
                this.editAction(index);
              }}>
              <Icon name="edit" size={15} solid color={colors.textColor} />
              <Text
                style={{
                  fontFamily: Fonts.ubuntu,
                  color: colors.textColor,
                  marginLeft: 5,
                  fontSize: 14,
                }}>
                {this.store.text.edit}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'row',
              }}
              onPress={() => {
                this.apartmentGoToChat(items);
              }}>
              <Icon name="comment" size={15} solid color={colors.textColor} />
              <Text
                style={{
                  fontFamily: Fonts.ubuntu,
                  color: colors.textColor,
                  marginLeft: 5,
                  fontSize: 14,
                }}>
                {this.store.user.memberType == 0
                  ? this.store.text.chatWithTenant
                  : this.store.text.chatWithOwner}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'row',
              }}
              onPress={() => {
                this.editDocAction(index);
              }}>
              <Icon
                name="folder-open"
                size={15}
                solid
                color={colors.textColor}
              />
              <Text
                style={{
                  fontFamily: Fonts.ubuntu,
                  fontSize: 14,
                  color: colors.textColor,
                  marginLeft: 5,
                }}>
                {this.store.text.Doc}
              </Text>
              {/* {this.renderAlert()} */}
            </TouchableOpacity>
            {this.store.user.memberType == 0 && this.store.logined ? (
              <TouchableOpacity
                style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'row',
                }}
                onPress={() => {
                  this.oneKeyToRent(items.name, items.id);
                }}>
                <Icon
                  name="building"
                  size={15}
                  solid
                  color={colors.textColor}
                />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    fontSize: 14,
                    color: colors.textColor,
                    marginLeft: 5,
                  }}>
                  {'一鍵放盤'}
                </Text>
                {/* {this.renderAlert()} */}
              </TouchableOpacity>
            ) : (
              <View />
            )}
          </View>
        </View>
        <View style={{width: width, height: 7, backgroundColor: '#EDEFF0'}} />
      </View>
    );
  }

  apartmentRender(noTenant) {
    return this.store.apartmentsData.map((items, index) => {
      console.log(items.id);
      var id = items.id;
      if (noTenant && !items.hasOwnProperty('tenant')) {
        return this.renderApartmentData(items, index);
      } else if (!noTenant) {
        return this.renderApartmentData(items, index);
      }
    });
  }

  renderAlert() {
    return (
      <Icon
        name="exclamation-circle"
        style={{position: 'absolute', right: 0, top: -5}}
        size={15}
        solid
        color={'red'}
      />
    );
  }

  renderReceiptAlert() {
    return (
      <Icon
        name="exclamation-circle"
        style={{position: 'absolute', right: 0, top: -5}}
        size={15}
        solid
        color={'red'}
      />
    );
  }

  editAction(index) {
    history.push(this, '/apartmentDetails', {index, create: false});
  }

  editDocAction(index) {
    // history.push(this, '/uploadImage', { index, create: false })
    this.docVisable = true;
    this.index = index;
  }

  renderMain(noTenant) {
    if (this.store.user != null) {
      if (this.store.apartmentsData.length > 0) {
        return (
          <View
            style={{
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            {this.apartmentRender(noTenant)}
          </View>
        );
      } else {
        if (this.store.user.memberType == 0) {
          return (
            <Icon
              name={'plus-circle'}
              style={{position: 'absolute', left: 20, top: 20}}
              size={40}
              color={colors.mainColor}
              onPress={() => {
                // history.push(this, '/apartmentDetails', {create: true});
                if (this.store.logined) {
                  if (this.store.loginUserData.data.member.phone == null) {
                    Alert.alert('', this.store.text.papnf, [
                      {text: '取消', onPress: () => history.goBack(this)},
                      {
                        text: '加入',
                        onPress: async () => {
                          // await history.goBack(this);
                          var data = {
                            vercode: '',
                            fullname: '',
                            thirdParty: true,
                            email: '',
                            gender: 'na',
                            countryCode: '852',
                            chara: 'owner',
                            age: 'na',
                            pwd: '',
                            phone: '',
                            refcode: '',
                            ownerPhone: '', // 如果char係租客就會有，OWNER就NULL
                          };
                          history.push(this, '/signUpVerify', {
                            signupData: data,
                            addphone: true,
                          });
                        },
                      },
                    ]);
                  } else {
                    history.push(this, '/apartmentDetails', {create: true});
                  }
                } else {
                  history.push(this, '/apartmentDetails', {create: true});
                }
              }}
            />
          );
        } else {
          return (
            <View
              style={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <View
                style={{
                  //borderBottomColor: colors.textColor,
                  // borderBottomWidth: 1,
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginTop: 10,
                  height: verticalScale(400),
                  width: width - 100,
                }}>
                {this.refinput()}

                {this.iconRander()}
              </View>
            </View>
          );
        }
      }
    } else {
      return (
        <Icon
          name={'plus-circle'}
          style={{position: 'absolute', left: 20, top: 60}}
          size={40}
          onPress={() => {
            history.push(this, '/apartmentDetails', {create: true});
          }}
        />
      );
    }
  }

  async goToChat(email, self) {
    if (!this.logined) {
      history.push(self, '/signin', {icon: true});
    } else {
      JMessage.getGroupInfo(
        {id: this.store.loginUserData.data.member.gid},
        group => {
          var item = {};

          item = {key: group.id};
          item.conversationType = 'group';

          this.props.navigation.navigate('chat', {conversation: item});
        },
        error => {
          Alert.alert('error', JSON.stringify(error));
        },
      );
      // const user = await this.friendList.find(
      //   element => element.name === email,
      // );
      // console.log(user);
      // const userdata = await this._check(user.contactId);
      // const session = {
      //   ...userdata,
      //   sessionType: '0',
      // };
      // console.log(session);
      // history.push(self, '/chat', {
      //   title: session.alias || session.name,
      //   session,
      // });
    }
  }

  renderTabAlert(index) {
    if (index == 1) {
      return <View style={{height: 20, width: 20, backgroundColor: 'red'}} />;
    } else {
      return <View />;
    }
  }

  // _renderIcon = ({route}: any) => {
  //   if (route.show && this.store.noTenantApartmentValue > 0) {
  //     return (
  //       <View
  //         style={{
  //           height: 20,
  //           width: 20,
  //           backgroundColor: 'red',
  //           position: 'absolute',
  //           right: -70,
  //           top: -5,
  //           borderRadius: 20,
  //           justifyContent: 'center',
  //           alignItems: 'center',
  //         }}>
  //         <Text style={{fontSize: 12, color: 'white'}}>
  //           {this.store.noTenantApartmentValue}
  //         </Text>
  //       </View>
  //     );
  //   } else {
  //     return <View />;
  //   }
  // };
  _renderIcon() {
    if (this.store.noTenantApartmentValue > 0) {
      return (
        <View
          style={{
            height: 20,
            width: 20,
            backgroundColor: 'red',
            position: 'absolute',
            right: 20,
            top: 5,
            borderRadius: 20,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text style={{fontSize: 12, color: 'white'}}>
            {this.store.noTenantApartmentValue}
          </Text>
        </View>
      );
    } else {
      return <View />;
    }
  }

  _renderHeader = props => {
    return (
      <TabBar
        {...props}
        style={{backgroundColor: 'white'}}
        labelStyle={{color: 'black', fontSize: 16, fontFamily: Fonts.ubuntuTh}}
        activeColor={{color: colors.mainColor}}
        indicatorStyle={{backgroundColor: colors.mainColor, height: 4}}
        renderIcon={this._renderIcon}
      />
    );
  };

  _configureTransition(transitionProps, prevTransitionProps) {
    return {
      // duration in milliseconds, default: 250
      duration: 500,
      // An easing function from `Easing`, default: Easing.inOut(Easing.ease)
      easing: Easing.bounce,
    };
  }

  onRefreshToGetApartment() {
    if (this.store.logined) {
      this.store.getApartmentData();
    } else {
    }
  }

  renderAllApartment = ({route}) => {
    return (
      <View style={{flex: 1}}>
        <ScrollView
          // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
          refreshControl={
            <RefreshControl
              refreshing={this.store.loading}
              onRefresh={() => this.onRefreshToGetApartment()}
            />
          }>
          {this.renderMain(false)}
        </ScrollView>
      </View>
    );
  };

  _renderScene = ({route}) => {
    switch (route.key) {
      case 'first':
        return (
          <View style={{flex: 1}}>
            <ScrollView
              // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
              refreshControl={
                <RefreshControl
                  refreshing={this.store.loading}
                  onRefresh={() => this.onRefreshToGetApartment()}
                />
              }>
              {this.renderMain(false)}
            </ScrollView>
          </View>
        );
      case 'seconds':
        return (
          <View style={{flex: 1}}>
            <ScrollView
              // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
              refreshControl={
                <RefreshControl
                  refreshing={this.store.loading}
                  onRefresh={() => this.onRefreshToGetApartment()}
                />
              }>
              {this.renderMain(true)}
            </ScrollView>
          </View>
        );
      default:
        return null;
    }
  };

  renderNoTenantApartment = ({route}) => {
    return (
      <View style={{flex: 1}}>
        <ScrollView
          // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
          refreshControl={
            <RefreshControl
              refreshing={this.store.loading}
              onRefresh={() => this.onRefreshToGetApartment()}
            />
          }>
          {this.renderMain(true)}
        </ScrollView>
      </View>
    );
  };

  changeShowNoAddTenantApartmentAction(which) {
    this.showNotAddTenantApartmentOrNot = which;
  }

  render() {
    var data = [];
    const onRequestClose = () => (this.visable = false);
    this.store.apartmentDataDoc.map((items, index) => {
      var image = {uri: items.uri};
      data.push(image);
    });
    return (
      <View style={{flex: 1}}>
        <LoadingView visible={this.store.loading} />
        <HomeTut2 />
        <NaviBar
          title={'Home'}
          self={this}
          onPress={() => {
            if (this.store.logined) {
              this.store.gotohelperChat(this);
            }
            JPush.getRegistrationID(result =>
              console.log('registerID:' + result.registerID),
            );
          }}
        />

        {this.store.user.memberType != 1 ? (
          <View style={{flexDirection: 'row', width: width}}>
            <TouchableOpacity
              onPress={() => {
                this.changeShowNoAddTenantApartmentAction(false);
              }}
              style={{
                height: 50,
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                borderBottomColor: this.showNotAddTenantApartmentOrNot
                  ? '#F2F2F2'
                  : colors.mainColor,
                borderBottomWidth: 5,
              }}>
              <Text style={{fontSize: 21, fontFamily: Fonts.ubuntu}}>
                {'物業'}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                this.changeShowNoAddTenantApartmentAction(true);
              }}
              style={{
                height: 50,
                flex: 1,
                flexDirection: 'row',
                justifyContent: 'center',
                alignItems: 'center',
                borderBottomColor: !this.showNotAddTenantApartmentOrNot
                  ? '#F2F2F2'
                  : colors.mainColor,
                borderBottomWidth: 5,
              }}>
              <Text style={{fontSize: 21, fontFamily: Fonts.ubuntu}}>
                {'未加入租客'}
              </Text>
              {this._renderIcon()}
            </TouchableOpacity>
          </View>
        ) : (
          <View />
        )}

        <View style={{flex: 1, marginTop: 10}}>
          <ScrollView
            // contentContainerStyle={{flex: 1, justifyContent: 'center'}}
            refreshControl={
              <RefreshControl
                refreshing={this.store.loading}
                onRefresh={() => this.onRefreshToGetApartment()}
              />
            }>
            {this.renderMain(this.showNotAddTenantApartmentOrNot)}
          </ScrollView>
        </View>
        <ImageView
          HeaderComponent={imageIndex => {
            return (
              <ImageHeader
                onRequestClose={onRequestClose}
                onPress={() => {
                  this.store.saveImage(imageIndex);
                }}
              />
            );
          }}
          FooterComponent={({imageIndex}) => (
            <ImageFooter imageIndex={imageIndex} imagesCount={data.length} />
          )}
          visible={this.visable}
          onRequestClose={onRequestClose}
          images={data}
          presentationStyle={'overFullScreen'}
          imageIndex={this.imageIndex}
        />
        <Modal
          visible={this.docVisable}
          width={0.7}
          height={0.2}
          onTouchOutside={() => {
            this.docVisable = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.docVisable = false;
          }}>
          <ModalContent>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <TouchableOpacity
                style={{alignItems: 'center'}}
                onPress={() => {
                  history.push(this, '/receipt', {index: this.index});
                  this.docVisable = false;
                }}>
                <Icon
                  name="file-invoice-dollar"
                  sholid
                  color={colors.mainColor}
                  size={40}
                />
                {/* {this.renderReceiptAlert()} */}
                <Text
                  style={{fontFamily: Fonts.ubuntu, color: colors.mainColor}}>
                  {this.store.text.receipt}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{alignItems: 'center', marginLeft: 30}}
                onPress={() => {
                  history.push(this, '/uploadImage', {
                    index: this.index,
                    create: false,
                  });
                  this.docVisable = false;
                }}>
                <Icon
                  name="file-image"
                  sholid
                  color={colors.mainColor}
                  size={40}
                />
                <Text
                  style={{fontFamily: Fonts.ubuntu, color: colors.mainColor}}>
                  {this.store.text.photoAndDoc}
                </Text>
              </TouchableOpacity>
            </View>
          </ModalContent>
        </Modal>

        <Modal
          visible={this.shareVisable}
          width={0.7}
          height={0.3}
          onTouchOutside={() => {
            this.shareVisable = false;
          }}
          swipeDirection={['up', 'down']} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.shareVisable = false;
          }}>
          <ModalContent>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              {this.renderShare()}
            </View>
          </ModalContent>
        </Modal>
        {/* <Modal
        useNativeDriver = {false}
         hasOverlay = {false}
        backdropOpacity = {0}
        visible={this.store.hometutVisable}
          width={1}
          height={1}
          modalStyle = {{ backgroundColor: 'rgba(0, 0, 0, 0.2)',}}
          overlayOpacity = {0.2}
          style={{
            backgroundColor: 'rgba(0, 0, 0, 0.2)',
        }}>
          <ModalContent  style = {{backgroundColor : 'rgba(0, 0, 0, 0.2)',flex:1}}>
          <HomeTut appStore = {this.store}/>
          </ModalContent>
        </Modal>  */}
        <Toast
          ref="toast"
          style={{backgroundColor: colors.mainColor}}
          position="center"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{color: 'white'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  button: {
    marginTop: 20,
    width: 100,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.statusBarColor,
  },
  buttonText: {
    fontSize: 15,
    fontFamily: Fonts.ubuntu,
    color: 'white',
  },
  slide1: {
    justifyContent: 'center',
    alignItems: 'center',
  },

  shadowView: {backgroundColor: 'white', borderRadius: 15},
  buttonView: {
    backgroundColor: colors.mainColor,
    marginRight: 30,
    marginLeft: 30,
    marginTop: 30,
    marginBottom: 30,
    height: 40,
    width: 200,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },

  apartmentText: {
    fontFamily: Fonts.ubuntuTh,
    color: colors.textColor,
    fontSize: 20,
  },
  text: {
    marginTop: 7,
    marginLeft: 5,
    color: colors.textColor,
    fontSize: 22,
    fontFamily: Fonts.ubuntu,
  },
  subAddress: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'row',
  },
});
export default withNavigation(Home);
