import {observable, action, transaction} from 'mobx';
import {Alert, Platform, Animated, Easing, Linking} from 'react-native';
import ConversationListItem from './ConversationListItem';
import JMessage from 'jmessage-react-plugin';
import axios from 'axios';
var _ = require('lodash');
import EventEmitter from 'react-native-md5';
import NavigationService from '../../services/NavigationService';
//import {NavigationActions} from 'react-navigation';
import language from '../../services/language';
import AsyncStorageHelper from '../../common/asyncStorageHelper';
import uuid from 'react-native-uuid';
import moment from 'moment';
import CameraRoll from '@react-native-community/cameraroll';
import PushNotification from 'react-native-push-notification';
//import {NimSession, NimFriend} from 'react-native-netease-im';
import Realm from 'realm';
import history from '../../common/history';
import api from '../../services/api';
import JPush from 'jpush-react-native';
import RNFetchBlob from 'rn-fetch-blob';
import Md5 from '../../util/md5';
var _ = require('lodash');
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';
import Global from '../../services/Global';
import Signature from '../../pages/signature/signature';
const asyncStorageHelper = new AsyncStorageHelper();
let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});
class Stores {
  @observable
  convList = [];
  key;

  @observable
  displayName;

  @observable
  avatarThumbPath;

  appKey;

  groupId;

  username;

  roomId;

  @observable
  latestMessageString;
  @observable
  hometutVisable = false;

  @observable
  addtutVisable = false;

  @observable
  conversation;

  @observable
  wechatQRCode = '';

  type;
  @observable
  friendArr = [];
  @observable
  splash = false;
  @observable
  tutorial = false;
  @observable
  selectChar = false;
  @observable
  home = false;
  @observable
  gosignin = false;
  @observable
  testingChat = null;
  @observable
  text = language.en;
  @observable
  languageSelection = 'english';

  @observable
  helperUnRead = 0;

  @observable
  friendList = [];
  @observable
  animateStatus = {
    progress: new Animated.Value(0),
    show: false,
  };

  @observable
  oneClickApartment = [];

  @observable
  oldAvatarId = '';

  @observable
  contractState = [];

  @observable
  banner = [];

  @observable
  apartmentDataWhichNeedToSync = [];

  @observable
  signUri = '';
  @observable
  stampUri = '';

  @observable
  repairData = null;

  @observable
  rentApartmentData = null;

  @observable
  noTenantApartmentValue = 1;

  @observable
  loginUserData = {
    data: {
      member: {},
      token: '',
    },
  };

  @observable
  logined = false;

  @observable
  receiptData = [];

  @observable
  addFunctionVisable = false;

  @observable
  loading = false;

  @observable
  list = [];

  @observable
  addedCard = false;

  @observable
  creditCardinfo = {};

  @observable
  refData = null;

  apartment = null;

  @observable
  apartmentsData = [];

  @observable
  case = [];

  @observable
  getNowDate = '';

  @observable
  countdown = 10;

  @observable
  registerID = '';

  @observable
  serviceContent = [];

  @observable
  apartmentData = {
    id: null,
    floor: 'G',
    unit: '',
    seats: '',
    createDate: null,
    modifyDate: null,
    avatar: null,
    name: null,
    address: null,
    signContractDate: null,
    endContractDate: null,
    rent: null,
    country: 'hk',
    callingCode: '+852',
    rentNotification: 1,
    leaseMonth: 12,
    deposit: null,
    endContractNotification: 1,
    rentNotificationId: [],
    endContractNotificationId: null,
    remark: [],
    doc: [],
  };
  @observable
  apartmentDataRemark = [];
  @observable
  apartmentDataDoc = [];
  @observable
  avatar = null;
  @observable
  user = null;

  @observable
  image = null;

  @observable
  timer = 60;

  @action
  convertLocalIdentifierToAssetLibrary(localIdentifier, ext) {
    const hash = localIdentifier.split('/')[0];
    return `assets-library://asset/asset.${ext}?id=${hash}&ext=${ext}`;
    //return 'photos://asset/' + localIdentifier;
  }

  @action
  getCountryLabel(value) {
    return this.text.CountryList[
      this.text.CountryList.findIndex(x => x.value == value)
    ].label;
  }

  @action
  setList(data) {
    this.list = data;
  }

  @action
  resetTimer() {
    this.timer = 0;
  }

  @action
  tick() {
    this.timer += 1;
  }
  @action
  idGenerator() {
    return uuid.v4();
  }

  @action
  async deleteDemo() {
    var index = await this.user.apartment.findIndex(
      element => element.id === 'demo',
    );
    if (index >= 0) {
      this.deleteApartment(index);
      await this.getUser();
    }
  }

  @action
  async goToChat(data, self) {
    if (!this.logined) {
      history.push(self, '/signin', {icon: true});
    } else {
      // 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,
      // });
      console.log(data);
      self.props.navigation.navigate('chat', {conversation: data});
      // JMessage.getGroupInfo(
      //   {id: this.loginUserData.data.member.gid},
      //   group => {
      //     console.log(group);
      //     var item = {};

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

      //     self.props.navigation.navigate('chat', {conversation: group});
      //   },
      //   error => {
      //     Alert.alert('error', JSON.stringify(error));
      //   },
      // );
    }
  }

  @action
  checkUnRead(data) {
    data.recents.map((items, index) => {
      var unread = parseInt(items.unreadCount);
      if (unread > 0) {
        if (items.name == 'Helper') {
          this.helperUnRead = unread;
          console.log(unread);
        }
      } else {
        if (items.name == 'Helper') {
          this.helperUnRead = unread;
          console.log(unread);
        }
      }
    });
  }

  @action
  async avatarfilter() {
    console.log(this.apartmentDataDoc[0].type);
    var ans = await this.apartmentDataDoc.find(function(item) {
      return item.type == 3;
    });
    console.log(ans.uri);
    this.apartmentData.avatar = ans.uri;
  }

  @action
  resetApartmentData() {
    this.apartmentData = {
      id: null,
      floor: 'G',
      unit: '',
      seats: '',
      createDate: null,
      modifyDate: null,
      avatar: '',
      name: null,
      address: null,
      signContractDate: null,
      endContractDate: null,
      rent: null,
      leaseMonth: 12,
      deposit: null,
      country: 'hk',
      callingCode: '+852',
      rentNotification: 1,
      endContractNotification: 1,
      rentNotificationId: [],
      endContractNotificationId: null,
      remark: [],
      doc: [],
    };
    this.apartmentDataRemark = [];
    this.apartmentDataDoc = [];
    this.avatar = null;
  }

  @action
  ramdomNotificationId() {
    // return Math.round(Math.random() * 36 ** 4).toString(36);
    var min = 0;
    var max = 9999;
    var random = Math.floor(Math.random() * (+max - +min)) + +min;
    var ans = random.toString();
    return ans;
  }

  @action
  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.friendArr = friendArr;
      },
      error => {
        //    Alert.alert('error', JSON.stringify(error));
      },
    );
  }

  @action
  newRentlocalNotificationHandler(items) {
    if (items.rentNotification !== 0) {
      transaction(() => {
        var notificationDay = moment(items.signContractDate).subtract(
          items.rentNotification,
          'days',
        );
        var endday = moment(items.endContractDate);
        for (var i = 0; i <= 1; i++) {
          if (notificationDay.unix() > moment().unix()) {
            var id = this.ramdomNotificationId();
            var notificationData = {
              id: id,
              type: 0,
              date: '' + notificationDay.unix(),
            };
            var normalDay = moment(notificationDay);
            normalDay.add(items.rentNotification, 'days');
            var title = '收租提示';
            var conent =
              items.name +
              '的租客應在' +
              normalDay.format('DD-MM-YYYY') +
              '交租';
            if (this.user.memberType == 0) {
              title = '收租提示';
              conent =
                items.name +
                '的租客應在' +
                normalDay.format('DD-MM-YYYY') +
                '交租';
            } else {
              title = '交租提示';
              conent =
                items.name + '應在' + normalDay.format('DD-MM-YYYY') + '交租';
            }

            this.pushNotification(title, conent, id, notificationDay.toDate());
            // this.pushNotification(title, conent, id, notificationDay.toDate());
            notificationDay = notificationDay.add(1, 'months');
            console.log(notificationDay.toDate());
          }
        }
      });
    }
  }

  @action
  rentlocalNotificationHandler() {
    // if (this.apartmentData.rentNotification !== 0) {
    //   transaction(() => {
    //     this.apartmentData.rentNotificationId = [];
    //     var notificationDay = moment(
    //       this.apartmentData.signContractDate,
    //     ).subtract(this.apartmentData.rentNotification, 'days');
    //     console.log('notification day: ' + notificationDay.toDate());
    //     var endday = moment(this.apartmentData.endContractDate);
    //     console.log(notificationDay.toDate());
    //     console.log(endday.toDate());
    //     while (notificationDay <= endday) {
    //       var id = this.ramdomNotificationId();
    //       var notificationData = {
    //         id: id,
    //         type: 0,
    //         date: '' + notificationDay.unix(),
    //       };
    //       this.apartmentData.rentNotificationId.push(notificationData);
    //       var normalDay = moment(notificationDay);
    //       normalDay.add(this.apartmentData.rentNotification, 'days');
    //       var title = '收租提示';
    //       var conent =
    //         this.apartmentData.name +
    //         '的租客應在' +
    //         normalDay.format('DD-MM-YYYY') +
    //         '交租';
    //       if (this.user.memberType == 0) {
    //         title = '收租提示';
    //         conent =
    //           this.apartmentData.name +
    //           '的租客應在' +
    //           normalDay.format('DD-MM-YYYY') +
    //           '交租';
    //       } else {
    //         title = '交租提示';
    //         conent =
    //           this.apartmentData.name +
    //           '應在' +
    //           normalDay.format('DD-MM-YYYY') +
    //           '交租';
    //       }

    //       this.pushNotification(title, conent, id, notificationDay.toDate());
    //       // this.pushNotification(title, conent, id, notificationDay.toDate());
    //       notificationDay = notificationDay.add(1, 'months');
    //       console.log(notificationDay.toDate());
    //     }
    //   });
    // }
    this.deleteAllNotification();

    this.apartmentsData.map((items, index) => {
      console.log(items);
      if (items.rentNotification !== 0) {
        try {
          var notificationDate = moment(items.signContractDate).subtract(
            items.rentNotification,
            'days',
          );
          var now = moment();
          var id = this.ramdomNotificationId();
          var normalDay = moment();
          var title = '收租提示';

          if (
            now >= moment(items.signContractDate) &&
            now < moment(items.endContractDate)
          ) {
            if (now.month() + 1 == moment(items.signContractDate).month() + 1) {
              if (now.date() >= notificationDate.date()) {
                now = now.add(1, 'M');
                now = now.set('date', notificationDate.date());
                normalDay = normalDay.set('month', now.month());
                normalDay = normalDay.set(
                  'date',
                  moment(items.signContractDate).date(),
                );
              } else if (now.date() < notificationDate.date()) {
                normalDay = normalDay.set(
                  'date',
                  moment(items.signContractDate).date(),
                );
                now = now.set('date', notificationDate.date());
              }
              if (now <= moment(items.endContractDate)) {
                var conent =
                  items.name +
                  '的租客應在' +
                  normalDay.format('DD-MM-YYYY') +
                  '交租';
                if (this.user.memberType == 0) {
                  title = '收租提示';
                  conent =
                    items.name +
                    '的租客應在' +
                    normalDay.format('DD-MM-YYYY') +
                    '交租';
                } else {
                  title = '交租提示';
                  conent =
                    items.name +
                    '應在' +
                    normalDay.format('DD-MM-YYYY') +
                    '交租';
                }
                console.log(now);
                console.log(conent);
                console.log(normalDay);
                this.pushNotification(title, conent, id, now.toDate());
              }
            } else if (now.month() + 1 > moment(items.signContractDate) + 1) {
              if (now.date() >= notificationDate.date()) {
                now = now.add(1, 'M');
                now = now.set('date', notificationDate.date());
                normalDay = normalDay.set('month', now.month());
                normalDay = normalDay.set(
                  'date',
                  moment(items.signContractDate).date(),
                );
              } else if (now.date() < notificationDate.date()) {
                console.log(notificationDate);
                console.log(conent);
                normalDay = normalDay.set(
                  'date',
                  moment(items.signContractDate).date(),
                );
                now = now.set('date', notificationDate.date());
              }
              if (now <= moment(items.endContractDate)) {
                var conent =
                  items.name +
                  '的租客應在' +
                  normalDay.format('DD-MM-YYYY') +
                  '交租';
                if (this.user.memberType == 0) {
                  title = '收租提示';
                  conent =
                    items.name +
                    '的租客應在' +
                    normalDay.format('DD-MM-YYYY') +
                    '交租';
                } else {
                  title = '交租提示';
                  conent =
                    items.name +
                    '應在' +
                    normalDay.format('DD-MM-YYYY') +
                    '交租';
                }
                console.log(notificationDate);
                console.log(conent);
                this.pushNotification(title, conent, id, now.toDate());
              }
            }
          }
        } catch (e) {
          console.log(e);
        }
      }
    });
  }

  @action
  newendContractlocalNotificationHandler(items) {
    if (items.endContractNotification !== 0) {
      items.endContractNotificationId = null;
      var endday = moment(items.endContractDate).subtract(
        items.endContractNotification,
        'months',
      );

      var id = this.ramdomNotificationId();
      var notificationData = {id: id, type: 1, date: '' + endday.unix()};
      items.rentNotificationId.push(notificationData);
      var title = '合約到期提示';
      var normalDay = endday.add(items.endContractNotification, 'months');
      var conent =
        items.name + '的租約會在' + normalDay.format('DD-MM-YYYY') + '到期';
      this.pushNotification(title, conent, id, endday.toDate());
    }
  }

  @action
  endContractlocalNotificationHandler() {
    if (this.apartmentData.endContractNotification !== 0) {
      this.apartmentData.endContractNotificationId = null;
      var endday = moment(this.apartmentData.endContractDate).subtract(
        this.apartmentData.endContractNotification,
        'months',
      );

      var id = this.ramdomNotificationId();
      var notificationData = {id: id, type: 1, date: '' + endday.unix()};
      this.apartmentData.rentNotificationId.push(notificationData);
      var title = '合約到期提示';
      var normalDay = endday.add(
        this.apartmentData.endContractNotification,
        'months',
      );
      var conent =
        this.apartmentData.name +
        '的租約會在' +
        normalDay.format('DD-MM-YYYY') +
        '到期';
      this.pushNotification(title, conent, id, endday.toDate());
    }
  }

  @action
  deleteAllNotification() {
    PushNotification.cancelAllLocalNotifications();
  }

  @action
  deleteNotification(index) {
    let user = realm.objects('User');
    this.user.apartment[index].rentNotificationId.map((items, index) => {
      PushNotification.cancelLocalNotifications({id: items.id});
      try {
        realm.write(() => {
          if (
            user[0].notification.findIndex(element => element.id == items.id) !=
            -1
          ) {
            user[0].notification.splice(
              user[0].notification.findIndex(element => element.id == items.id),
              1,
            );
          }
        });
      } catch (e) {
        console.log('Error on creation ' + e);
      }
    });
  }

  pushNotification(title, content, id, date) {
    console.log('pushnotificationDay: ' + date);
    this.lastId++;
    PushNotification.localNotificationSchedule({
      date: date, // in 30 secs
      id: id,
      userInfo: {
        id: id, //IMPORTANT!! adding the userInfo, so that the cancel will work!
      },

      number: 0,
      /* iOS only properties */
      alertAction: 'view', // (optional) default: view

      /* iOS and Android properties */
      title: title, // (optional)
      message: content, // (required)
      playSound: true, // (optional) default: true
      soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
    });
  }

  @action
  cloneApartmentDataForUpDate(data) {
    var apartmentData = {
      id: data.id,
      createDate: data.createDate,
      modifyDate: data.modifyDate,
      floor: data.floor,
      unit: data.unit,
      seats: data.seats,
      name: data.name,
      address: data.address,
      signContractDate: data.signContractDate,
      endContractDate: data.endContractDate,
      rent: data.rent,
      country: data.country,
      deposit: data.deposit,
      leaseMonth: data.leaseMonth,
      callingCode: data.callingCode,
      rentNotification: data.rentNotification,
      endContractNotification: data.endContractNotification,
      notifications: data.rentNotificationId,
      endContractNotificationId: data.endContractNotificationId,
      remark: [],
      doc: [],
    };
    data.remark.map((item, index) => {
      apartmentData.remark.push(item);
    });

    data.doc.map((item, index) => {
      var newItems = {
        id: item.id,
        name: item.name,
        type: item.type,
        createDate: item.createDate,
        uri: item.uri,
        mime: item.mime,
        height: item.height,
        width: item.width,
      };
      apartmentData.doc.push(newItems);
    });
    console.log(apartmentData);
    return apartmentData;
  }

  @action
  async deleteAvatar() {
    var index = await this.apartmentDataDoc.findIndex(
      element => element.type == 3,
    );
    console.log(index);
    if (index != -1) {
      this.apartmentDataDoc.splice(index, 1);
    }
  }

  @action
  cloneApartmentData(index) {
    console.log('run clone');
    const data = this.apartmentsData[index];
    console.log(data.avatar);
    this.apartmentData = {
      id: data.id,
      createDate: moment(data.createDate).toDate(),
      modifyDate: data.modifyDate,
      name: data.name,
      floor: data.floor,
      unit: data.unit,
      seats: data.seats,
      address: data.address,
      signContractDate: data.signContractDate,
      endContractDate: data.endContractDate,
      deposit: data.deposit,
      leaseMonth: data.leaseMonth,
      rent: data.rent,
      country: data.country,
      callingCode: '+852',
      rentNotification: data.rentNotification,
      endContractNotification: data.endContractNotification,
      rentNotificationId: data.rentNotificationId,
      avatar: data.avatar,
      endContractNotificationId: data.endContractNotificationId,
    };
    this.avatar = _.cloneDeep(data.avatar);
    this.apartmentDataRemark = data.remark;
    var remark = [];
    data.remark.map((item, index) => {
      remark.push(item);
    });
    this.apartmentDataRemark = remark;
  }

  @action
  async cloneApartmentDocData(index) {
    const data = this.apartmentsData[index].doc;
    var doc = [];
    await data.map((item, index) => {
      var newItems = item;
      doc.push(newItems);
    });
    this.apartmentDataDoc = doc;
  }

  @action
  async localAvatarHander(data) {
    console.log('localAvatarHander');
    var docArray = [];
    var index = await this.user.apartment.findIndex(
      element => element.id == data.id,
    );
    console.log(index);
    if (index != -1) {
      await this.user.apartment[index].doc.map((items, index) => {
        if (items.type != 3) {
          docArray.push(items);
        }
      });

      await docArray.push(
        await this.apartmentDataDoc.find(element => element.type == 3),
      );
      console.log(docArray);
      return docArray;
    }
    return docArray;
  }
  @action
  async saveEdit(index) {
    var data = this.apartmentData;
    let user = realm.objects('User');

    console.log(user[0].apartment.length);
    console.log(data.id);
    var localDataIndex = await user[0].apartment.findIndex(
      element => element.id === data.id,
    );
    console.log(localDataIndex);
    if (user[0].apartment.length > 0) {
      if (user[0].apartment[localDataIndex].id == data.id) {
        //await this.deleteNotification(index);
        //await this.rentlocalNotificationHandler();
        await this.endContractlocalNotificationHandler();

        if (this.logined == true) {
          await this.editApartmentPost(data);
        }
        console.log('now testing');
        var localDocData = await this.localAvatarHander(data);
        console.log(localDocData);

        try {
          realm.write(() => {
            let newApartment = {
              id: data.id,
              createDate: data.createDate,
              floor: data.floor,
              seats: data.seats,
              unit: data.unit,
              modifyDate: new Date(),
              name: data.name,
              address: data.address,
              avatar: this.apartmentData.avatar,
              signContractDate: data.signContractDate,
              endContractDate: data.endContractDate,
              leaseMonth: parseInt(data.leaseMonth),
              deposit: parseInt(data.deposit),
              rent: parseInt(data.rent),
              country: data.country,
              callingCode: data.callingCode,
              rentNotification: data.rentNotification,
              endContractNotification: data.endContractNotification,
              rentNotificationId: [],
              remark: this.apartmentDataRemark,
            };
            user[0].apartment[index] = newApartment;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
      } else {
        console.log('online edit');
        await this.editApartmentPost(data);
      }
    } else {
      if (this.logined == true) {
        console.log('online edit');
        await this.editApartmentPost(data);
      }
    }
  }

  @action
  uploadsign(path, self, beforepageToast) {
    this.loading = true;
    var postUri =
      api.uploadSign + this.loginUserData.data.member.id + '/upload-sign';
    console.log(path);
    const fileData = new FormData();
    fileData.append('file', {
      uri: path, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
      name: 'Signature.png', // example: upload.jpg
      type: 'image/png',
    });

    var data = [
      {
        // uri: path, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
        name: 'Signature.png', // example: upload.jpg
        data: RNFetchBlob.wrap(path),
        type: 'image/*',
      },
    ];

    fetch(postUri, {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: this.loginUserData.data.token,
      },
      body: fileData,
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        if (response.hasOwnProperty('sign')) {
          this.signUri = response.sign;
          this.loginUserData.data.member.sign = response.sign;
          self.props.navigation.goBack();
        } else {
        }
        // alert("Upload success!");
        console.log(response);
      })
      .catch(error => {
        this.loading = false;
        console.log('upload error', error);
        // alert("Upload failed!");
      });

    // RNFetchBlob.fetch(
    //   'POST',
    //   postUri,
    //   {
    //     Authorization: this.loginUserData.data.token,
    //     'Content-Type': 'multipart/form-data',
    //   },
    //   data,
    // )
    //   .then(resp => {
    //     this.loading = false;
    //     console.log(resp);
    //   })
    //   .catch(err => {
    //     this.loading = false;
    //     console.log(err);
    //   });
  }

  @action
  uploadStamp(path, self, beforepageToast) {
    this.loading = true;
    var postUri =
      api.uploadSign + this.loginUserData.data.member.id + '/upload-stamp';
    const fileData = new FormData();
    fileData.append('file', {
      uri: path, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
      name: 'stampImage.png', // example: upload.jpg
    });

    fetch(postUri, {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: this.loginUserData.data.token,
      },
      body: fileData,
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        if (response.hasOwnProperty('stamp')) {
          this.stampUri = response.stamp;
          this.loginUserData.data.member.stamp = response.stamp;
          //  self.props.navigation.goBack();
        } else {
        }
        // alert("Upload success!");
        console.log(response);
      })
      .catch(error => {
        this.loading = false;
        console.log('upload error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async changeChar(self, type) {
    //this.user.memberType = type
    let user = realm.objects('User');
    try {
      await realm.write(() => {
        user[0].memberType = type;
      });
      if (type == 1 && this.logined == false) {
        history.push(self, 'signin', {icon: false});
      } else {
        self.props.navigation.navigate('home');
      }
    } catch (e) {
      console.log('Error on creation ' + e);
    }
    this.getUser();
  }

  getMatch(a, b) {
    var matches = [];
    for (var i = 0; i < a.length; i++) {
      for (var e = 0; e < b.length; e++) {
        if (a[i].id === b[e].id) matches.push(a[i]);
      }
    }
    return matches;
  }

  async deff(a, b) {
    var matches = [];
    await a.map(async (item, index) => {
      if (b.findIndex(element => element.id == item.id) == -1) {
        await matches.push(a[index]);
      }
    });
    return matches;
  }

  @action
  async saveDocEdit(index) {
    var data = this.apartmentDataDoc;
    let user = realm.objects('User');

    if (this.logined) {
      var sameImages = [];
      var deleteImages = [];
      var addImages = [];
      sameImages = await this.getMatch(
        this.apartmentsData[index].doc,
        this.apartmentDataDoc,
      );
      addImages = await this.deff(this.apartmentDataDoc, sameImages);
      deleteImages = await this.deff(
        this.apartmentsData[index].doc,
        sameImages,
      );
      console.log(this.apartmentsData[index].doc);
      console.log(this.apartmentDataDoc);
      console.log('sameImages:');
      console.log(sameImages);
      console.log('deleteImages:');
      console.log(deleteImages);
      console.log('addImages:');
      console.log(addImages);

      await deleteImages.map(async (items, index) => {
        this.deleteDoc(items.id);
      });
      await this.uploadDocFetch(this.apartmentData.id, addImages);

      var localIndex = await this.user.apartment.findIndex(
        element => element.id == this.apartmentData.id,
      );
      if (localIndex != -1) {
        var docarray = [];
        console.log(localIndex);
        await this.user.apartment[localIndex].doc.map(async (items, index) => {
          if (
            (await deleteImages.findIndex(element => element.id == items.id)) ==
            -1
          ) {
            var data = {
              id: items.id,
              height: items.height,
              width: items.width,
              type: items.type,
              name: items.name,
              uri: items.uri,
              mime: items.mime,
              createDate: items.createDate,
            };
            await docarray.push(data);
          }
        });
        await addImages.map(async (items, index) => {
          await docarray.push(items);
        });
        console.log(docarray);
        try {
          realm.write(() => {
            user[0].apartment[index].doc = docarray;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
      }
    } else {
      try {
        realm.write(() => {
          user[0].apartment[index].doc = this.apartmentDataDoc;
        });
      } catch (e) {
        console.log('Error on creation ' + e);
      }
    }
  }

  @action
  getUser() {
    let user = realm.objects('User');
    for (let p of user) {
      this.user = p;
      if (!this.logined) {
        console.log(this.user);
        this.apartmentsData = this.user.apartment;
      }
    }
  }

  isEmpty(obj) {
    for (var x in obj) {
      if (obj.hasOwnProperty(x)) return false;
    }
    return true;
  }

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

  @action
  async loadLocalData() {
    if (!this.logined) {
      this.noTenantApartmentValue = 0;
    }
    let user = await realm.objects('User');
    for (let p of user) {
      this.user = p;
      console.log(this.user);
      this.user.apartment.map((item, index) => {
        if (!item.hasOwnProperty('tenant') && !this.logined) {
          this.noTenantApartmentValue += 1;
          console.log(this.noTenantApartmentValue);
        }
        console.log(item.name);
        item.doc.map((items, index) => {
          console.log(items);
        });
      });
      console.log('length: ' + this.user.notification.length);
      this.user.notification.map((items, index) => {
        console.log('id: ' + items.id);
        console.log('type: ' + items.type);
        console.log('date: ' + moment(items.date * 1000).format('DD-MM-YYYY'));
      });
      // console.log(this.user.apartment[0].doc[0].uri)
      if (!this.logined) {
        console.log(this.user.apartment);
        this.apartmentsData = this.user.apartment;
        this.rentlocalNotificationHandler();
      }
    }
  }

  @action
  deleteApartment(index) {
    var data = this.apartmentData;
    let user = realm.objects('User');
    try {
      realm.write(() => {
        user[0].apartment.splice(index, 1);
      });
    } catch (e) {
      console.log('Error on creation ' + e);
    }
  }

  @action
  changeLanguage(lang) {
    console.log(lang);
    if (lang == 'english') {
      console.log('select english');
      Global.lang = 'en';
      this.text = language.en;
      this.languageSelection = 'english';
    } else if (lang == 'hk') {
      console.log('select hk');
      Global.lang = 'hk';
      this.text = language.hk;
      this.languageSelection = 'hk';
    } else {
      console.log('select chinese');
      this.text = language.ch;
      Global.lang = 'ch';
      this.languageSelection = 'ch';
    }

    asyncStorageHelper.saveData('language', lang);
    this.changetabBarLabel();
  }

  //api

  @action
  changetabBarLabel() {
    Global.info = this.text.rentTools;
    Global.repair = this.text.maintenance;
    Global.property = this.text.rentalInfo;
  }

  @action
  async signupWithWeChat(data, self) {
    var requestURL = api.signupWithWechat;
    this.loading = true;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      Global.login = true;
      this.loading = false;
      transaction(() => {
        this.logined = true;

        this.loginUserData = response;
      });

      await this.deleteDemo();
      await this.regUserNotificationToken(true, false);
      await this.getApartmentData();
      await this.getCreditCard();

      if (response.data.member.chara == 'owner') {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 0;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      } else {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 1;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      }

      var userdata = {
        id: response.data.member.id,
        token: response.data.token,
      };

      await this.loginIn(
        response.data.member.id,
        response.data.member.cpw,
        userdata,
        self,
        false,
        false,
      );
      self.props.navigation.navigate('Profile');
      // this.getCreditCard();
      // this.notificationInit(response.data.member.id);
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action
  async signinWithWeChat(data, self, navAction) {
    //  this.loading = true;
    var requestURL = api.signinWithWechat;
    data.nonce = this.genNonce();
    console.log(data);
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      if (response.data.hasOwnProperty('nonmember')) {
        var memberSignupData = {
          avatar: response.data.nonmember.avatar,
          fullname: response.data.nonmember.fullname,
          tpid: response.data.nonmember.tpid,
          tppf: response.data.nonmember.tppf,
          email: '',
          nonce: data.nonce,
          chara: '',
        };

        if (this.user.memberType == 0) {
          memberSignupData.chara = 'owner';
        } else {
          memberSignupData.chara = 'tenant';
        }
        console.log(memberSignupData);
        history.push(self, '/wechatSignup', {
          signupData: memberSignupData,
        });
      } else {
        Global.login = true;
        transaction(() => {
          this.logined = true;

          this.loginUserData = response;
        });
        // this.getCreditCard();
        // this.notificationInit(response.data.member.id);
        console.log(this.user);
        await this.deleteDemo();
        await this.regUserNotificationToken(true, false);
        await this.getApartmentData();
        await this.getCreditCard();

        if (response.data.member.chara == 'owner') {
          let user = realm.objects('User');
          try {
            await realm.write(() => {
              user[0].memberType = 0;
            });
          } catch (e) {
            console.log('Error on creation ' + e);
          }
          this.getUser();
        } else {
          let user = realm.objects('User');
          try {
            await realm.write(() => {
              user[0].memberType = 1;
            });
          } catch (e) {
            console.log('Error on creation ' + e);
          }
          this.getUser();
        }

        var userdata = {
          id: response.data.member.id,
          token: response.data.token,
        };

        await this.loginIn(
          response.data.member.id,
          response.data.member.cpw,
          userdata,
          self,
          navAction,
          false,
        );
      }

      // this.getCreditCard();
      // this.notificationInit(response.data.member.id);
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action
  async bindPhone(data, self) {
    console.log('right');
    this.loading = true;
    var requestURL = api.bindphone;

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: this.loginUserData.data.token,
        },
      });
      this.loading = false;
      console.log(response);
      this.loginUserData.data.countryCode = response.data.countryCode;
      this.loginUserData.data.phone = response.data.phone;
      self.props.navigation.goBack();
    } catch (e) {
      this.loading = false;
      self.refs.toast.show('add mobile fail: ');
      console.log(e);
    }
  }

  @action
  async signupPost(self, data) {
    console.log(data);

    var jsonData = {
      fullname: data.fullname,
      email: data.email,
      gender: data.gender,
      countryCode: data.countryCode,
      chara: data.chara,
      age: data.age,
      pwd: data.pwd,
      phone: data.phone,
      refcode: data.refcode.toString(),
      vercode: data.vercode,
      // ownerPhone: ""
    };
    console.log('vercode: ' + jsonData.vercode);
    this.loading = true;
    var requestURL = api.signup;
    try {
      const response = await axios.post(requestURL, jsonData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      this.loading = false;
      await this.deleteDemo();
      transaction(() => {
        this.loading = false;
        // this.isSignUp = false;
        // this.isSignUpVerify = false;
        this.logined = true;
        this.loginUserData = response;
      });

      // self.navigatieAction("menu");
      var data = {id: response.data.member.id, token: response.data.token};
      Global.login = true;
      JMessage.login(
        {
          username: response.data.member.id,
          password: response.data.member.cpw,
        },
        () => {
          this.reloaGroupList();
          console.log('success');
          JMessage.getMyInfo(UserInf => {
            if (UserInf.username === undefined) {
              // 未登录
            } else {
              console.log(UserInf);
            }
          });
        },
        error => {
          Alert.alert('login fail', JSON.stringify(error));
        },
      );
      //this.loginPost(data, self, true);
      if (jsonData.chara == 'owner') {
        await this.uploadApartmentWhenFirstTimeLogin();
      }
      await asyncStorageHelper.saveData('userInfo', data);

      await history.popToUp(self);
      await self.props.navigation.navigate('home');
    } catch (e) {
      console.log(e.response);
      self.refs.toast.show('SignUp Fail: ' + e.response.data);
      this.getApartmentData();
      this.loading = false;
    }
  }

  async uploadApartmentWhenLoginFindApartmentWhichNotSync(self) {
    await this.apartmentDataWhichNeedToSync.map(async (items, index) => {
      await this.createApartmentPost(
        this.cloneApartmentDataForUpDate(items),
        false,
      );
    });
    self.props.navigation.navigate('home');
  }

  async uploadApartmentWhenFirstTimeLogin() {
    await this.user.apartment.map((items, index) => {
      this.createApartmentPost(this.cloneApartmentDataForUpDate(items), false);
    });
  }

  reloaGroupList() {
    JMessage.getGroupIds(
      result => {
        var groupIdArr = result.map(groupId => {
          var element = {};
          element.key = groupId;
          return element;
        });
        console.log(groupIdArr);
      },
      error => {
        Alert.alert('error', JSON.stringify(error));
      },
    );
  }

  async loginIn(imusername, impassword, data, self, navAction, isGetProfile) {
    this.loading = true;
    console.log(imusername + impassword);
    //self.props.navigation.navigate('mainPage');
    await JMessage.login(
      {
        username: imusername,
        password: impassword,
      },
      async () => {
        await this.reloaGroupList();
        console.log('success');
        await this.reloadFriendList();
        await JMessage.getMyInfo(UserInf => {
          if (UserInf.username === undefined) {
            // 未登录
          } else {
            console.log(UserInf);
          }
        });
        if (navAction) {
          // asyncStorageHelper.saveData("userInfo", data);
          this.loading = false;
          console.log('go home');
          // history.push(self,'mainPage');
          if (isGetProfile) {
            self.props.navigation.navigate('mainPage');
          } else {
            asyncStorageHelper.saveData('userInfo', data);
            history.goBack(self);
          }
        } else {
          await asyncStorageHelper.saveData('userInfo', data);
          this.loading = false;
          // history.goBack(self);
          //   await self.props.navigation.state.params.backToHome({back: true});
          this.CheckWhichLocalApartmentNotSync();
        }
      },
      error => {
        this.loading = false;
        Alert.alert('login fail', JSON.stringify(error));
      },
    );
  }

  genNonce() {
    var nonce =
      Math.floor(Math.random() * (+9999999999999 - +1000000000000)) +
      +1000000000000;

    nonce += 'b';

    var randomNumber =
      Math.floor(Math.random() * (+99999999999 - +10000000000)) + +10000000000;

    nonce += randomNumber;
    console.log(nonce);
    let hex_md5v = EventEmitter.hex_md5(nonce);
    console.log(nonce + hex_md5v);
    const ans = nonce + hex_md5v;
    console.log(ans.length);
    return nonce + hex_md5v;
  }

  async getUserProfile(userInfo, self) {
    this.loading = true;
    var userdata = JSON.parse(userInfo);
    console.log(userdata.token);
    var requestURL = api.getUserProfile + userdata.id;
    try {
      const response = await axios.get(requestURL, {
        headers: {
          Authorization: userdata.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;
      Global.login = true;
      transaction(() => {
        this.logined = true;
        this.loginUserData.data.member = response.data;
        this.loginUserData.data.token = userdata.token;
      });
      // this.getCreditCard();
      // this.notificationInit(response.data.member.id);
      console.log(response.data);
      console.log(this.loginUserData);

      await this.getApartmentData();
      await this.getCreditCard();
      this.regUserNotificationToken(true, false);

      if (response.data.chara == 'owner') {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 0;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      } else {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 1;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      }
      await this.loginIn(
        response.data.id,
        response.data.cpw,
        userdata,
        self,
        true,
        true,
      );
    } catch (e) {
      // self.refs.toast.show('Login Fail');
      this.loading = false;
      if (this.user.memberType == 0) {
        self.props.navigation.navigate('mainPage');
      } else {
        self.props.navigation.navigate('signin', {icon: false});
      }
      //connectFail.fail();
      console.log(e);
    }
  }

  async loginPost(data, self, navAction) {
    this.loading = true;
    var requestURL = api.login;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      Global.login = true;
      transaction(() => {
        this.logined = true;
        this.loading = false;
        this.loginUserData = response;
      });
      // this.getCreditCard();
      // this.notificationInit(response.data.member.id);
      console.log(response);
      console.log(this.user);

      await this.getApartmentData();
      await this.getCreditCard();
      await this.regUserNotificationToken(true, false);

      if (response.data.member.chara == 'owner') {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 0;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      } else {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 1;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      }

      var userdata = {
        id: response.data.member.id,
        token: response.data.token,
      };

      await this.loginIn(
        response.data.member.id,
        response.data.member.cpw,
        userdata,
        self,
        navAction,
        false,
      );
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(JSON.stringify(e));
    }
  }

  @action
  async logoutPost(self, reset, data) {
    this.loading = true;
    var token = this.loginUserData.data.token;
    var requestURL = api.logout;
    this.regUserNotificationToken(true, true);
    try {
      const response = await axios.post(requestURL, token);
      Global.login = false;
      JMessage.logout();

      //this.regUserNotificationToken("");
      asyncStorageHelper.removeItemValue('userInfo');
      if (reset) {
        this.loginPost(data, self, true);
      } else {
        console.log('logout');
        this.logined = false;
        await this.loadLocalData();

        if (this.user.memberType == 1) {
          history.push(self, '/signin', {icon: false});
        } else {
          await self.props.navigation.navigate(
            'main',
            {},
            // NavigationActions.navigate({routeName: 'home'}),
          );
        }

        await transaction(() => {
          this.logined = false;
          this.loginUserData = null;
          this.addedCard = false;
          this.creditCardinfo = {};
          this.loading = false;
        });
      }
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }
  currencyFormat(num) {
    return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
  }

  async getRentReceipt(apartmentIndex) {
    // const formatter = new Intl.NumberFormat('en-US', {
    //   style: 'currency',
    //   currency: 'HKD',
    //   minimumFractionDigits: 0,
    // });
    try {
      var apartmentID = this.apartmentsData[apartmentIndex].id;
      var uri = api.addApartment + apartmentID + '/rent/';
      const response = await axios.get(uri, {
        headers: {
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);

      if (this.loginUserData.data.member.chara === 'owner') {
        this.receiptData = [];
        response.data.content.map(async (items, index) => {
          console.log(
            parseInt(moment(parseInt(this.getNowDate * 1000)).format('YYYYMM')),
          );
          console.log(parseInt(items.month));
          if (
            parseInt(
              moment(parseInt(this.getNowDate * 1000)).format('YYYYMM'),
            ) >= parseInt(items.month)
          ) {
            console.log('testingtesting');
            console.log(this.apartmentsData[apartmentIndex].tenant);
            var data = {
              date:
                moment(items.month + '01', 'YYYYMMDD').format('DD/MM/YYYY') +
                ' - ' +
                moment(items.month + '01', 'YYYYMMDD')
                  .add(1, 'M')
                  .format('DD/MM/YYYY'),
              signDate: moment(items.date, 'YYYY-MM-DD').format('DD/MM/YYYY'),
              rent: this.currencyFormat(parseInt(items.rent)),
              id: '' + items.id,
              owner: this.apartmentsData[apartmentIndex].owner.fullname,
              ownerPhone:
                this.apartmentsData[apartmentIndex].owner.countryCode +
                ' ' +
                this.apartmentsData[apartmentIndex].owner.phone,
              tenant: this.apartmentsData[apartmentIndex].tenant.fullname,
              tenantPhone:
                this.apartmentsData[apartmentIndex].tenant.countryCode +
                ' ' +
                this.apartmentsData[apartmentIndex].tenant.phone,
              address: this.apartmentsData[apartmentIndex].address,
              status: items.status,
            };
            await this.receiptData.push(data);
            console.log(this.receiptData);
          }
        });
      } else {
        this.receiptData = [];
        response.data.content.map(async (items, index) => {
          console.log(
            parseInt(moment(parseInt(this.getNowDate * 1000)).format('YYYYMM')),
          );
          console.log(parseInt(items.month));
          if (
            parseInt(
              moment(parseInt(this.getNowDate * 1000)).format('YYYYMM'),
            ) >= parseInt(items.month) &&
            items.status != 'Pending Payment'
          ) {
            var data = {
              date:
                moment(items.month + '01', 'YYYYMMDD').format('DD/MM/YYYY') +
                ' - ' +
                moment(items.month + '01', 'YYYYMMDD')
                  .add(1, 'M')
                  .format('DD/MM/YYYY'),
              signDate: moment(items.date, 'YYYY-MM-DD').format('DD/MM/YYYY'),
              rent: this.currencyFormat(parseInt(items.rent)),
              id: '' + items.id,
              owner: this.apartmentsData[apartmentIndex].owner.fullname,
              ownerPhone:
                this.apartmentsData[apartmentIndex].owner.countryCode +
                ' ' +
                this.apartmentsData[apartmentIndex].owner.phone,
              tenant: this.apartmentsData[apartmentIndex].tenant.fullname,
              tenantPhone:
                this.apartmentsData[apartmentIndex].tenant.countryCode +
                ' ' +
                this.apartmentsData[apartmentIndex].tenant.phone,
              address: this.apartmentsData[apartmentIndex].address,
              status: items.status,
            };
            await this.receiptData.push(data);
            console.log(this.receiptData);
          }
        });
      }
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  async getApartmentData() {
    try {
      const response = await axios.get(api.addApartment, {
        headers: {
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.reloadFriendList();
      console.log(response);
      await response.data.content.map(async (items, index) => {
        console.log(ans.uri);
        response.data.content[index].avatar = ans.uri;
        this.contractState = [];
        // await this.contractStatesReturn(items)
        // console.log(this.contractState)
      });

      transaction(() => {
        this.apartmentsData = response.data.content;
        this.noTenantApartmentValue = 0;
        this.apartmentsData = this.apartmentsData.sort((a, b) =>
          a.createDate > b.createDate ? -1 : 1,
        );
        this.getNowDate = response.data.unix_timestamp;
        this.apartmentsData.map(async (items, index) => {
          if (!items.hasOwnProperty('tenant')) {
            this.noTenantApartmentValue += 1;
            console.log(this.noTenantApartmentValue);
          }
          this.apartmentsData[index].state = '';
          console.log(items.hasOwnProperty('tenant'));
          if (items.hasOwnProperty('contracts')) {
            if (items.contracts.length > 0) {
              console.log(
                '' + items.tenant.id + ' ' + items.contracts[0].tenant.id,
              );
              if (this.loginUserData.data.member.chara == 'owner') {
                console.log('testing');
                if (
                  (await items.contracts.findIndex(
                    element => element.tenant.id == items.tenant.id,
                  )) != -1
                ) {
                  var contractindex = await items.contracts.findIndex(
                    element => element.tenant.id == items.tenant.id,
                  );
                  console.log(contractindex);
                  if (items.contracts[contractindex].signed) {
                    this.apartmentsData[index].state =
                      items.contracts[contractindex].endContractDate;
                    this.apartmentsData[index].contractClickState = 'e';
                  } else {
                    this.apartmentsData[index].state = this.text.processing;
                    this.apartmentsData[index].contractClickState = 'p';
                  }
                } else {
                  this.apartmentsData[index].state = this.text.createContract;
                  this.apartmentsData[index].contractClickState = 'c';
                }
              } else {
                // this.apartmentsData[index].state =  "Please Sign";
                if (items.contracts[0].signed) {
                  this.apartmentsData[index].state =
                    items.contracts[0].endContractDate;
                  this.apartmentsData[index].contractClickState = 'e';
                } else {
                  this.apartmentsData[index].state = this.text.pleaseSign;
                  this.apartmentsData[index].contractClickState = 's';
                }
              }
            } else {
              this.apartmentsData[index].state = this.text.createContract;
              this.apartmentsData[index].contractClickState = 'c';
            }
          }
        });
        this.rentlocalNotificationHandler();
        console.log(this.apartmentData);
      });
    } catch (error) {
      console.log(error.response);
    }
  }

  contractStatesReturn(items) {
    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 {
            this.contractState.push('Processing');
          }
        } else {
          console.log('wrong');
          this.contractState.push('Create');
        }
      } else {
        this.contractState.push('Please Sign');
      }
    } else {
      this.contractState.push('Create');
    }
  }

  @action
  async uploadAvatar(id) {
    this.loading = true;
    const fileData = new FormData();
    var avatarImage = await this.apartmentDataDoc[
      this.apartmentDataDoc.findIndex(element => element.type == 3)
    ];
    console.log(id);
    console.log(avatarImage);
    await fileData.append('apartment_id', id);

    console.log(avatarImage.uri);
    console.log(avatarImage.name);
    await fileData.append('file[]', {
      uri: avatarImage.uri, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
      name: avatarImage.name, // example: upload.jpg
    });
    await fileData.append('id[]', avatarImage.id);
    await fileData.append('height[]', avatarImage.height);
    await fileData.append('width[]', avatarImage.width);
    await fileData.append('type[]', avatarImage.type.toString());

    console.log(fileData);

    fetch(api.uploadFile, {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: this.loginUserData.data.token,
      },
      body: fileData,
    })
      .then(response => response.json())
      .then(async response => {
        this.loading = false;
        // alert("Upload success!");
        if (response[0] != null && response[0].hasOwnProperty('uri')) {
          var index = await this.apartmentsData.findIndex(
            element => element.id == response[0].apartment.id,
          );
          if (index != -1) {
            console.log(response[0].uri);
            this.apartmentsData[index].avatar = response[0].uri;
          }
        }
        console.log(response);
      })
      .catch(error => {
        this.loading = false;
        console.log('upload error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async deleteApartmentPost(index, self) {
    var uri = api.addApartment + this.apartmentData.id;
    this.loading = true;

    fetch(uri, {
      method: 'delete',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
      body: JSON.stringify({}),
    })
      .then(response => response.json())
      .then(async response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        await this.deleteApartment(index);
        await this.getApartmentData();
        await this.resetApartmentData();
        await this.getUser();
        history.goBack(self);
      })
      .catch(error => {
        this.loading = false;
        console.log(error);
        // alert("Upload failed!");
      });
  }

  @action
  async editApartmentPost(data) {
    var uri = api.addApartment + data.id;
    this.loading = true;
    let newApartment = {};
    if (data.hasOwnProperty('avatar')) {
      newApartment = {
        avatar: data.avatar,
        id: data.id,
        floor: data.floor,
        seats: data.seats,
        unit: data.unit,
        createDate: data.createDate,
        modifyDate: data.modifyDate,
        name: data.name,
        address: data.address,
        leaseMonth: parseInt(data.leaseMonth),
        deposit: parseInt(data.deposit),
        signContractDate: data.signContractDate,
        endContractDate: data.endContractDate,
        rent: data.rent,
        country: data.country,
        callingCode: data.callingCode,
        rentNotification: data.rentNotification,
        notifications: data.notificationId,
        endContractNotification: data.endContractNotification,
        remark: data.remark,
      };
    } else {
      newApartment = {
        id: data.id,
        createDate: data.createDate,
        modifyDate: data.modifyDate,
        floor: data.floor,
        seats: data.seats,
        unit: data.unit,
        name: data.name,
        address: data.address,
        signContractDate: data.signContractDate,
        endContractDate: data.endContractDate,
        rent: data.rent,
        country: data.country,
        callingCode: data.callingCode,
        rentNotification: data.rentNotification,
        endContractNotification: data.endContractNotification,
        remark: data.remark,
      };
    }

    try {
      const response = await axios.put(uri, newApartment, {
        headers: {
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      console.log(response);
      // var index = await this.apartmentsData.findIndex(
      //   element => element.id == data.id,
      // );
      // var newAvatarIndex = await this.apartmentDataDoc.findIndex(
      //   element => element.type == 3,
      // );
      // console.log(newAvatarIndex);
      // console.log(
      //   await this.apartmentsData[index].doc.findIndex(
      //     element => element.id == this.apartmentDataDoc[newAvatarIndex].id,
      //   ),
      // );
      // if (
      //   (await this.apartmentsData[index].doc.findIndex(
      //     element => element.id == this.apartmentDataDoc[newAvatarIndex].id,
      //   )) == -1
      // ) {
      //   var oldAvatarIndex = await this.apartmentsData[index].doc.findIndex(
      //     element => element.type == 3,
      //   );
      //   console.log(oldAvatarIndex);
      //   await this.deleteDoc(this.apartmentsData[index].doc[oldAvatarIndex].id);
      //   await this.uploadAvatar(data.id);
      // }

      await this.getApartmentData();
      transaction(() => {
        this.loading = false;
      });
    } catch (error) {
      this.loading = false;
      //  console.log(error.response);
    }
  }

  @action
  async deleteDoc(id) {
    // this.loading = true;
    // var token = this.loginUserData.data.token;
    // var requestURL = api.uploadFile+id;

    // try {
    //   const response = await axios.put(requestURL,{}, {
    //     headers: {
    //       Authorization: token,
    //       "Content-Type": "application/json"
    //     }
    //   });

    //   transaction(() => {
    //     self.shareVisable = true
    //     this.loading = false;
    //     this.refData = response.data

    //   });
    //   console.log(response);

    // } catch (e) {
    //   this.loading = false;
    //   console.log(e.response);

    // }

    this.loading = true;
    var requestURL = api.uploadFile + id;
    fetch(requestURL, {
      method: 'delete',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
      body: JSON.stringify({}),
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
      })
      .catch(error => {
        this.loading = false;
        console.log(error.response);
        // alert("Upload failed!");
      });
  }

  @action
  async createApartmentPost(data, type) {
    if (type) {
      this.loading = true;
    }

    let newApartment = {
      id: data.id,
      createDate: data.createDate,
      modifyDate: data.modifyDate,
      name: data.name,
      floor: data.floor,
      unit: data.unit,
      seats: data.seats,
      address: data.address,
      leaseMonth: data.leaseMonth,
      deposit: data.deposit,
      // avatar: this.store.avatar,
      signContractDate: data.signContractDate,
      endContractDate: data.endContractDate,
      rent: data.rent,
      country: data.country,
      callingCode: data.callingCode,
      rentNotification: data.rentNotification,
      endContractNotification: data.endContractNotification,
      notifications: data.rentNotificationId,
      // endContractNotificationId: data.endContractNotificationId,
      remark: data.remark,
      // doc: this.store.apartmentDataDoc
    };
    try {
      const response = await axios.post(api.addApartment, newApartment, {
        headers: {
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response);
      if (this.logined) {
        this.uploadDocFetch(response.data.id, data.doc, type);
      }
      transaction(() => {
        this.loading = false;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async updateApartment() {}

  @action
  async uploadDoc(id) {
    const fileData = new FormData();
    console.log(id);
    fileData.append('apartment_id', id);
    await this.apartmentDataDoc.map((items, index) => {
      console.log(items.uri);
      console.log(items.name);
      fileData.append('file[]', {
        uri: items.uri.replace('file://', ''), // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
        name: items.name, // example: upload.jpg
      });
      fileData.append('id[]', items.id);
      fileData.append('height[]', items.height);
      fileData.append('width[]', items.width);
      fileData.append('type[]', items.type.toString());
      fileData.append('id[]', items.id);
    });

    try {
      const response = await axios.post(api.uploadFile, fileData, {
        headers: {
          Accept: 'application/json',
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'multipart/form-data',
        },
        timeout: 5000,
      });
      console.log(response);

      transaction(() => {
        this.loading = false;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async uploadDocFetch(id, data, type) {
    if (type) {
      this.loading = true;
    }
    const fileData = new FormData();
    console.log(id);
    fileData.append('apartment_id', id);
    await data.map((items, index) => {
      console.log(items.uri);
      console.log(items.name);
      fileData.append('file[]', {
        uri: items.uri, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
        name: items.name, // example: upload.jpg
      });
      fileData.append('id[]', items.id);
      fileData.append('height[]', items.height);
      fileData.append('width[]', items.width);
      fileData.append('type[]', items.type.toString());
    });

    console.log(fileData);

    fetch(api.uploadFile, {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: this.loginUserData.data.token,
      },
      body: fileData,
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        this.getApartmentData();
        // alert("Upload success!");
      })
      .catch(error => {
        this.loading = false;
        console.log(error);
        // alert("Upload failed!");
      });
  }

  @action
  async getRepairInfo() {
    let data = {
      charset: 'big5',
      'contain-title': '1',
    };
    this.loading = true;
    try {
      const response = await axios.get(api.getRepairInfo, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      this.repairData = response.data.content;
      this.loading = false;
      transaction(() => {
        this.loading = false;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async getRentInfo() {
    this.loading = true;
    this.rentApartmentData = [];
    try {
      const response = await axios.get(api.getRentInfo, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      var newArray = [];
      response.data.content.map((items, index) => {
        var newdata = _.cloneDeep(items);
        var newPrice = newdata.rent.slice(newdata.rent.indexOf('$'));
        newPrice = newPrice.replace(/\s/g, '');
        newPrice = Number(newPrice.replace(/[^0-9\.]+/g, ''));
        if (items.rent.indexOf('萬') != -1) {
          newPrice *= 10000;
        }
        var newDate = moment(items.date, 'M/D/YY').unix();
        newdata.newprice = newPrice;
        newdata.newDate = newDate;
        newArray.push(newdata);
      });

      this.rentApartmentData = newArray;

      transaction(() => {
        this.loading = false;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async chatUploadFile(type, path, filename, self, duration) {
    var formdata = new FormData();
    var fileType = '';
    switch (type) {
      case 1:
        fileType = 'image/jpg';
        break;
      case 2:
        fileType = 'audio/m4a';
        break;
      case 3:
        fileType = 'video/mp4';
        break;
    }
    formdata.append('file', {
      uri: path,
      name: filename,
      type: fileType,
    });
    formdata.append('type', type);

    this.loading = true;
    var token = this.loginUserData.data.token;
    var requestURL = api.chatBlob;

    try {
      const response = await axios.post(requestURL, formdata, {
        headers: {
          Accept: 'application/json',
          Authorization: token,
          'Content-Type': 'multipart/form-data',
        },
      });
      this.loading = false;
      transaction(() => {
        this.creditCardinfo = response.data;
        this.loading = false;
        this.addedCard = true;
      });
      console.log(response);

      self.onSendCustomMessage(
        response.data.uri,
        response.data.name,
        type,
        duration,
      );

      // self.navigatieAction("menu");
    } catch (e) {
      this.loading = false;

      console.log(e);
    }
  }

  @action
  async chatBackup(data) {
    var token = this.loginUserData.data.token;
    var requestURL = api.chatBackup;

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          Authorization: token,
          'Content-Type': 'application/json',
        },
      });

      console.log(response);
    } catch (e) {
      console.log(e);
    }
  }

  @action
  async getbanner() {
    this.banner = [];
    try {
      const response = await axios.get(api.getBanner, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      this.banner = response.data.content;

      transaction(() => {});
    } catch (error) {
      console.log(error);
    }
  }

  @action
  async getBuildingInfo() {
    this.loading = true;
    this.rentApartmentData = [];
    try {
      const response = await axios.get(api.getIndustrialBuilding, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      var newArray = [];
      response.data.content.map((items, index) => {
        var newdata = _.cloneDeep(items);
        var newPrice = newdata.price.slice(newdata.price.indexOf('$'));
        newPrice = newPrice.replace(/\s/g, '');
        newPrice = Number(newPrice.replace(/[^0-9\.]+/g, ''));
        if (items.price.indexOf('萬') != -1) {
          newPrice *= 10000;
        }
        var newDate = moment(items.date, 'M/D/YY').unix();
        newdata.newprice = newPrice;
        newdata.newDate = newDate;
        newArray.push(newdata);
      });
      //this.rentApartmentData = response.data.content;
      this.rentApartmentData = newArray;
      transaction(() => {
        this.loading = false;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async getCreditCard() {
    this.loading = true;
    var data = {};
    var requestURL = api.creditCard;
    var token = this.loginUserData.data.token;
    try {
      const response = await axios.get(requestURL, {
        headers: {
          Authorization: token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response.data);
      if (response.data.content.length > 0) {
        this.addedCard = true;
        this.creditCardinfo = response.data.content[0];
      }
      //self.navigatieAction("menu");
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }

  @action
  async deleCreditCard(self) {
    this.loading = true;
    var token = this.loginUserData.data.token;
    var requestURL = api.creditCard + '/' + this.creditCardinfo.id.toString();
    try {
      const response = await axios.delete(requestURL, {
        headers: {
          Authorization: token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.creditCardinfo = {};
      this.loading = false;
      this.addedCard = false;
      console.log(response);
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }

  @action
  async postCreditCard(self, data) {
    console.log(data);
    this.loading = true;
    var token = this.loginUserData.data.token;
    var requestURL = api.creditCard;
    var testString =
      'cvc: ' + data.cvc + ' expiry: ' + data.expiry + ' num: ' + data.num;
    // self.testing(token,testString)

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          Authorization: token,
          'Content-Type': 'application/json',
        },
      });
      this.loading = false;
      transaction(() => {
        this.creditCardinfo = response.data;
        this.loading = false;
        this.addedCard = true;
      });
      console.log(response);
      self.addCard = false;
      self.cardData = null;
      //navigation.goBack();
      // self.navigatieAction("menu");
    } catch (e) {
      this.loading = false;
      console.log(e);
      self.refs.toast.show(e.message);
    }
  }

  @action
  async createApartmentRefCode(apartmentId, self) {
    if (this.logined) {
      this.loading = true;
      var token = this.loginUserData.data.token;
      var requestURL = api.addApartment + apartmentId + '/reset-refcode';

      try {
        const response = await axios.put(
          requestURL,
          {},
          {
            headers: {
              Authorization: token,
              'Content-Type': 'application/json',
            },
          },
        );

        transaction(() => {
          self.shareVisable = true;
          this.loading = false;
          this.refData = response.data;
        });
        console.log(response);
      } catch (e) {
        this.loading = false;
        console.log(e.response);
      }
    } else {
      self.refs.toast.show(this.text.pleaseLogin);
    }
  }

  @action
  async tenantCheckApartment(data, self) {
    this.loading = true;
    var token = this.loginUserData.data.token;
    var requestURL = api.tenantCheckApartment;
    console.log(data);
    console.log(this.loginUserData.data.token);

    fetch(requestURL, {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
      body: JSON.stringify(data),
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        if (response.name == undefined || response.name == null) {
          Alert.alert(
            '',
            'This refcode is wrong',
            [
              {
                text: 'OK',
                onPress: () => {},
              },
            ],
            {cancelable: false},
          );
        } else {
          this.tenantAddApartment(data, self);
        }
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async getCase() {
    this.loading = true;
    try {
      const response = await axios.get(api.getCase, {
        headers: {
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);

      transaction(() => {
        this.loading = false;
        this.case = response.data.content;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async tenantAddApartment(data, self) {
    this.loading = true;
    var token = this.loginUserData.data.token;
    var requestURL = api.tenantAddApartment;
    console.log(data);
    console.log(this.loginUserData.data.token);
    var arraydata = [];
    await fetch(requestURL, {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
      body: JSON.stringify(data),
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        if (response.name == undefined || response.name == null) {
          Alert.alert(
            '',
            'This refcode is wrong',
            [
              {
                text: 'OK',
                onPress: () => {},
              },
            ],
            {cancelable: false},
          );
        } else {
          this.reloadFriendList();
          arraydata.push(response);
        }
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });
    this.apartmentsData = arraydata;
  }

  @action
  async payAgain(data, self, pay, paymethod) {
    if (paymethod == 0) {
      await this.PayByCredit(data.apartment, self);
    } else {
      await this.alipayment(data.apartment, self);
    }
  }
  @action
  async alipayment(id, self) {
    this.loading = true;
    var requestURL = api.contract + id + '/create-source';
    // fetch(requestURL, {
    //   method: 'put',
    //   headers: {
    //     'Content-Type': 'application/json',
    //     Authorization: this.loginUserData.data.token,
    //   },
    // })
    //   .then(response => response.json())
    //   .then(response => {
    //     this.loading = false;
    //     // alert("Upload success!");
    //     console.log(response);
    //     if (response.hasOwnProperty('redirect')) {
    //       history.push(self, '/alipayWebView', {uri: response.redirect.url});
    //     }
    //   })
    //   .catch(error => {
    //     this.loading = false;
    //     console.log('get error', error);
    //     // alert("Upload failed!");
    //   });
    console.log(requestURL);
    // var data = {type: 'alipay'};
    //var data = {type: 'stripe_wechat'};
    var data = {type: 'wechat'};
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: this.loginUserData.data.token,
        },

        timeout: 5000,
      });

      this.loading = false;

      console.log(response);

      this.wechatQRCode = response.data.type_data.qr_code_url;

      // Linking.canOpenURL(response.data.type_data.qr_code_url).then(
      //   supported => {
      //     if (supported) {
      //       Linking.openURL(response.data.type_data.qr_code_url);
      //     } else {
      //       console.log(
      //         "Don't know how to open URI: " +
      //           response.data.type_data.qr_code_url,
      //       );
      //     }
      //   },
      // );
      // if (response.data.hasOwnProperty('redirect')) {
      //   history.push(self, '/alipayWebView', {
      //     uri: response.data.redirect.url,
      //     alipayPayAsk: self.alipayPayAsk,
      //   });
      // }
    } catch (e) {
      console.log(e.response);
      this.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }

  @action
  async PayByCredit(id, self) {
    var uri = api.contract + id + '/pay-by-credit-card';
    console.log(uri);
    var raw = JSON.stringify({creditCardId: this.creditCardinfo.id});

    var myHeaders = new Headers();
    myHeaders.append('Authorization', this.loginUserData.data.token);
    myHeaders.append('Content-Type', 'application/json');

    fetch(uri, {
      method: 'put',
      headers: myHeaders,
      body: raw,
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        var storeSelf = this;
        this.startAnimate();
        setTimeout(function() {
          storeSelf.getApartmentData();
          self.props.navigation.popToTop();
        }, 1000);
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async casePayByCredit(id, self) {
    var uri = api.getCase + id + '/pay-by-credit-card';
    console.log(uri);
    var raw = JSON.stringify({creditCardId: this.creditCardinfo.id});

    var myHeaders = new Headers();
    myHeaders.append('Authorization', this.loginUserData.data.token);
    myHeaders.append('Content-Type', 'application/json');

    fetch(uri, {
      method: 'put',
      headers: myHeaders,
      body: raw,
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        if (response[0] != 'invalid_case_status') {
          var storeSelf = this;
          this.startAnimate();
          setTimeout(function() {
            storeSelf.getApartmentData();
            self.props.navigation.goBack();
          }, 1000);
        } else {
          self.refs.toast.show('Payment Fail');
        }
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async ownerCreateContract(data, self, pay, paymethod) {
    this.loading = true;
    var requestURL = api.contract;
    console.log(data);
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: this.loginUserData.data.token,
        },
        timeout: 5000,
      });

      transaction(() => {
        this.loading = false;
      });
      console.log(response);
      if (pay) {
        self.paid = false;
        self.data.apartment = response.data.id;
        if (paymethod == 0) {
          await this.PayByCredit(response.data.id, self);
        } else {
          await this.alipayment(response.data.id, self);
        }
      } else {
        this.getApartmentData();
        self.props.navigation.popToTop();
      }
    } catch (e) {
      self.refs.toast.show('Pay Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action
  async tenantSign(id, self) {
    this.loading = true;
    var requestURL = api.contract + id + '/tenant-sign';
    console.log(requestURL);
    fetch(requestURL, {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        this.getApartmentData();
        self.props.navigation.popToTop();
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async ownerSign(id, self) {
    // this.loading = true;
    // var requestURL = api.contract+id+"/owner-sign";
    // var data = {}
    // try {
    //   const response = await axios.put(requestURL,{
    //     headers: {
    //       'Authorization': this.loginUserData.data.token,
    //     },
    //     timeout: 5000
    //   });

    //   transaction(() => {
    //     this.loading = false;
    //   });
    //   console.log(response);
    //   self.props.navigation.popToTop();

    // } catch (e) {

    //   this.loading = false;
    //   //connectFail.fail();
    //   console.log(e.response);
    // }

    this.loading = true;
    var requestURL = api.contract + id + '/owner-sign';
    fetch(requestURL, {
      method: 'put',
      headers: {
        Authorization: this.loginUserData.data.token,
      },
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        self.props.navigation.popToTop();
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });
  }

  @action
  async checkContract(id) {
    this.loading = true;
    var uri = api.addApartment + id;
    try {
      const response = await axios.get(uri, {
        headers: {
          Authorization: this.loginUserData.data.token,
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response);
      if (response.data.contracts.length == 0) {
        console.log('contract = null');
      } else {
        console.log('contract 1');
      }
      return response.data;
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async markpaid(self, item) {
    this.loading = true;
    var data = {remark: ' '};
    var requestURL = api.rent + item.id + '/mark-paid/';
    fetch(requestURL, {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
      body: JSON.stringify(data),
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);

        this.receiptData[
          this.receiptData.findIndex(element => element.id == item.id)
        ].status = 'A';
        item.signDate = moment(response.date, 'YYYY-MM-DD').format(
          'DD/MM/YYYY',
        );
        history.push(self, '/receiptDetails', {receiptData: item});
      })
      .catch(error => {
        this.loading = false;
        console.log('get error', error);
        // alert("Upload failed!");
      });

    //     var data = {"remark":" "}
    //     this.loading = true
    //     var uri = api.rent+item.id+"/mark-paid/";
    //     try {
    //       const response = await axios.get(uri ,data,{
    //         headers: {
    //           Authorization: this.loginUserData.data.token,
    //           "Content-Type": "application/json"
    //         },
    //         timeout: 5000
    //       });
    //       this.loading = false
    //       console.log(response);
    //       history.push(self,'/receiptDetails',{receiptData:item})

    //     } catch (error) {
    //       this.loading = false;
    //       console.log(error.response);
    //     }
  }

  convertToConvList = list => {
    list.map((conversation, index) => {
      this.convList.push(this.getListItem(conversation, index));
    });
    return this.convList.slice();
  };

  getListItem(conversation, index) {
    let item = new ConversationListItem();
    item.type = conversation.conversationType;
    item.conversation = conversation;
    item.key = index;
    if (item.type === 'single') {
      item.appKey = conversation.target.appKey;
      item.username = conversation.target.username;
      item.displayName = conversation.target.displayName;
      if (item.displayName === '') {
        item.displayName = conversation.target.username;
      }
      item.avatarThumbPath = conversation.target.avatarThumbPath;
      if (item.avatarThumbPath === '') {
        JMessage.getUserInfo(
          {username: item.username, appKey: item.appKey},
          userInfo => {
            console.log('Get user info succeed' + JSON.stringify(userInfo));
            // TODO update conversation item
          },
          error => {
            console.log('Get user info failed, ' + JSON.stringify(error));
          },
        );
      }
    } else if (item.type === 'group') {
      if (conversation.target.ownerAppKey != undefined) {
        item.appKey = conversation.target.ownerAppKey;
      }
      item.groupId = conversation.target.id;
      item.displayName = conversation.target.name;
      item.avatarThumbPath = conversation.target.avatarThumbPath;
      if (item.avatarThumbPath === '') {
        JMessage.getGroupInfo(
          {id: item.groupId},
          groupInfo => {
            console.log('Get group info succeed ' + JSON.stringify(groupInfo));
            // TODO update conversation item
          },
          error => {
            console.log('Get group info failed, ' + JSON.stringify(error));
          },
        );
      }
    } else {
      item.appKey = conversation.target.appKey;
      item.roomId = conversation.target.roomId;
      item.avatarThumbPath = '../../../resource/chat-icon.png';
      item.displayName = conversation.target.roomName;
      item.memberCount = conversation.target.memberCount;
      item.maxMemberCount = conversation.target.maxMemberCount;
    }

    if (conversation.latestMessage === undefined) {
      return item;
    }

    if (conversation.latestMessage.type === 'text') {
      item.latestMessageString = conversation.latestMessage.text;
    }

    if (conversation.latestMessage.type === 'image') {
      item.latestMessageString = '[图片]';
    }

    if (conversation.latestMessage.type === 'voice') {
      item.latestMessageString = '[语音]';
    }

    if (conversation.latestMessage.type === 'file') {
      item.latestMessageString = '[文件]';
    }

    return item;
  }

  @action
  gotohelperChat(self, content) {
    var data = {
      id: this.loginUserData.data.member.gid,
      type: 'group',
      nickname: 'helper',
      msgContent: content,
    };

    this.goToChat(data, self);
  }

  @action deleteConversation = key => {
    var item = this.convList[key];
    JMessage.deleteConversation(
      item,
      code => {
        this.convList.splice(key, 1);
        console.log('Delete succeed');
      },
      error => {
        console.log('Delete failed, error: ' + JSON.stringify(error));
      },
    );
  };

  @action
  async sendsmsVerify(data, self) {
    this.loading = true;
    var requestURL = api.smsVerify;

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        timeout: 5000,
      });

      this.loading = false;
      console.log(response);
    } catch (e) {
      console.log(e);
      this.loading = false;
      self.refs.toast.show(e.response);
    }
  }
  @action
  async veerify_check(data, self, signupdata) {
    this.loading = true;
    var requestURL = api.veerify_check;

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        timeout: 5000,
      });

      this.loading = false;
      console.log(response);
      console.log(signupdata.vercode);
      this.signupPost(self, signupdata);
    } catch (e) {
      console.log(e);
      this.loading = false;
      self.refs.toast.show('Varification code wrong');
    }
  }

  @action
  async checkMember(data, self) {
    this.loading = true;
    var requestURL = api.check;
    var checkData = {
      email: data.email,
      mobileWithCountryCode: data.countryCode + data.phone,
    };
    try {
      const response = await axios.post(requestURL, checkData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      this.loading = false;
      console.log(response);
      console.log(response.data[Object.keys(response.data)[0]]);
      if (response.data[Object.keys(response.data)[0]]) {
        data.thirdParty = false;
        history.push(self, '/signUpVerify', {signupData: data});
      } else {
        self.refs.toast.show(this.text.signupfail);
        this.loading = false;
      }
    } catch (e) {
      self.refs.toast.show('SignUp Fail');
      this.loading = false;
      console.log(e);
    }
  }

  @action
  async forgotPassword(data, self) {
    this.loading = true;
    var requestURL = api.forgotPassword;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      this.loading = false;

      history.goBack(self);
      console.log(response);
    } catch (e) {
      console.log(e.response.data);
      self.refs.toast.show('Reset Password Fail: ' + e.response.data);
      this.loading = false;
    }
  }

  @action
  startAddTut() {
    asyncStorageHelper.getData('addtut', addtut => {
      var tutData = JSON.parse(addtut);
      console.log(tutData);
      if (tutData != null) {
        console.log(tutData);
        console.log(tutData.tenant);
        console.log(tutData.owner);
        //this.loginAction(userInfo);
        if (tutData.owner && tutData.tenant) {
          this.addtutVisable = false;
        } else if (!tutData.owner && tutData.tenant) {
          if (this.user.memberType === 0) {
            this.addtutVisable = true;
            var data = {
              owner: true,
              tenant: true,
            };
            asyncStorageHelper.saveData('addtut', data);
          }
        } else if (tutData.owner && !tutData.tenant) {
          if (this.user.memberType === 0) {
            this.addtutVisable = false;
          } else {
            this.addtutVisable = true;
            var data = {
              owner: true,
              tenant: true,
            };
            asyncStorageHelper.saveData('addtut', data);
          }
        }
      } else {
        console.log('add tut null');
        var data = {};
        if (this.user.memberType === 0) {
          data = {
            owner: true,
            tenant: false,
          };
        } else {
          data = {
            owner: false,
            tenant: true,
          };
        }
        this.addtutVisable = true;
        asyncStorageHelper.saveData('addtut', data);
      }
    });
  }

  @action
  startTut() {
    asyncStorageHelper.getData('hometut', hometut => {
      var tutData = JSON.parse(hometut);
      console.log(tutData);
      if (tutData != null) {
        console.log(tutData);
        console.log(tutData.tenant);
        console.log(tutData.owner);
        //this.loginAction(userInfo);
        if (tutData.owner && tutData.tenant) {
          this.hometutVisable = false;
        } else if (!tutData.owner && tutData.tenant) {
          if (this.user.memberType === 0) {
            this.hometutVisable = true;
            var data = {
              owner: true,
              tenant: true,
            };
            asyncStorageHelper.saveData('hometut', data);
          }
        } else if (tutData.owner && !tutData.tenant) {
          if (this.user.memberType === 0) {
            this.hometutVisable = false;
          } else {
            this.hometutVisable = true;
            var data = {
              owner: true,
              tenant: true,
            };
            asyncStorageHelper.saveData('hometut', data);
          }
        }
      } else {
        console.log('home tut null');
        var data = {};
        if (this.user.memberType === 0) {
          data = {
            owner: true,
            tenant: false,
          };
        } else {
          data = {
            owner: false,
            tenant: true,
          };
        }
        this.hometutVisable = true;
        asyncStorageHelper.saveData('hometut', data);
      }
    });
  }

  @action async signinWithApple(data, self, navAction) {
    this.loading = true;
    var requestURL = api.signinWithApple;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response);

      Global.login = true;
      transaction(() => {
        this.logined = true;

        this.loginUserData = response;
      });
      console.log(this.user);
      await this.deleteDemo();
      await this.regUserNotificationToken(true, false);
      await this.getApartmentData();
      await this.getCreditCard();

      if (response.data.member.chara == 'owner') {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 0;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      } else {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 1;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      }

      var userdata = {
        id: response.data.member.id,
        token: response.data.token,
      };

      await this.loginIn(
        response.data.member.id,
        response.data.member.cpw,
        userdata,
        self,
        navAction,
        false,
      );
    } catch (e) {
      self.refs.toast.show('Login Fail');

      //connectFail.fail();
      console.log(e.response);
    }
  }
  @action
  async thirdPartyLogin(data, self, navAction) {
    //  this.loading = true;
    var requestURL = api.thirdPartyLogin;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response);
      // if (response.data.hasOwnProperty('nonmember')) {
      //   var min = 0;
      //   var max = 99999999;
      //   var random = Math.floor(Math.random() * (+max - +min)) + +min;
      //   var ans = random.toString();
      //   console.log(ans);
      //   var memberSignupData = {
      //     thirdParty: true,
      //     vercode: '',
      //     fullname: response.data.nonmember.fullname,
      //     email: response.data.nonmember.email,
      //     gender: 'na',
      //     countryCode: '852',
      //     chara: 'owner',
      //     age: 'na',
      //     pwd: ans,
      //     phone: '',
      //     refcode: '',
      //     ownerPhone: '', // 如果char係租客就會有，OWNER就NULL
      //   };
      //   this.loading = false;
      //   if (this.user.memberType == 0) {
      //     memberSignupData.chara = 'owner';
      //   } else {
      //     memberSignupData.chara = 'tenant';
      //   }
      //   history.push(self, '/signUpVerify', {signupData: memberSignupData});
      // } else {

      Global.login = true;
      transaction(() => {
        this.logined = true;

        this.loginUserData = response;
      });
      // this.getCreditCard();
      // this.notificationInit(response.data.member.id);
      console.log(this.user);
      await this.deleteDemo();
      await this.regUserNotificationToken(true, false);
      await this.getApartmentData();
      await this.getCreditCard();

      if (response.data.member.chara == 'owner') {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 0;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      } else {
        let user = realm.objects('User');
        try {
          await realm.write(() => {
            user[0].memberType = 1;
          });
        } catch (e) {
          console.log('Error on creation ' + e);
        }
        this.getUser();
      }

      var userdata = {
        id: response.data.member.id,
        token: response.data.token,
      };

      await this.loginIn(
        response.data.member.id,
        response.data.member.cpw,
        userdata,
        self,
        navAction,
        false,
      );
      // }

      // this.getCreditCard();
      // this.notificationInit(response.data.member.id);
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action
  getregisterID() {
    JPush.getRegistrationID(result => {
      this.registerID = result.registerID;
      console.log(result);
    });
  }
  @action
  async regUserNotificationToken(logined, logout) {
    this.loading = true;
    var requestURL = api.regPushToken;

    var data = {
      mid: '',
      token: '',
    };
    if (logined && !logout) {
      console.log('logined');
      JPush.getRegistrationID(async result => {
        this.registerID = result.registerID;
        data.mid = this.loginUserData.data.member.id;
        data.token = this.registerID;
        console.log(result);
        try {
          const response = await axios.put(requestURL, data, {
            headers: {
              Authorization: this.loginUserData.data.token,
              'Content-Type': 'application/json',
            },
          });
          console.log(response);
          this.loading = false;
          // Alert.alert('', response);
        } catch (e) {
          this.loading = false;
          console.log(e);
        }
      });
    } else if (!logined && !logout) {
      data.token = this.registerID;
      JPush.getRegistrationID(async result => {
        data.token = this.registerID;

        try {
          const response = await axios.put(requestURL, data, {
            headers: {
              Authorization: this.loginUserData.data.token,
              'Content-Type': 'application/json',
            },
          });
          console.log(response);
        } catch (e) {
          //  this.loading = false;
          console.log(e);
        }
      });
    } else {
      data.mid = this.loginUserData.data.member.id;
      JPush.getRegistrationID(async result => {
        data.mid = this.loginUserData.data.member.id;

        try {
          const response = await axios.put(requestURL, data, {
            headers: {
              Authorization: this.loginUserData.data.token,
              'Content-Type': 'application/json',
            },
          });
          console.log(response);
        } catch (e) {
          //  this.loading = false;
          console.log(e);
        }
      });
    }
  }

  @action
  async remindTenantPayTheRent(self, items) {
    //contract
    this.loading = true;
    var requestURL = api.addApartment + items.id + '/reminder/';
    try {
      const response = await axios.post(
        requestURL,
        {remark: ''},
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: this.loginUserData.data.token,
          },
          timeout: 5000,
        },
      );

      this.loading = false;
      console.log(response);
      self.refs.toast.show('remind success');
    } catch (e) {
      self.refs.toast.show(this.text.remindFail);
      this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action insertConversation = conv => {
    this.convList.push(getListItem(conv, this.convList.length));
  };
  saveImage(index) {
    console.log(this.apartmentDataDoc[0].uri);
    console.log(index.imageIndex);
    if (Platform.OS === 'android') {
      // RNFetchBlob.config({
      //   fileCache: true,
      //   appendExt: 'jpg',
      // })
      //   .fetch('GET', image.urls.small)
      //   .then(res => {
      //     CameraRoll.saveToCameraRoll(res.path())
      //       .then(Alert.alert('Success', 'Photo added to camera roll!'))
      //       .catch(err => console.log('err:', err));
      //   });
    } else {
      CameraRoll.saveToCameraRoll(
        this.apartmentDataDoc[index.imageIndex].uri,
      ).then(Alert.alert('Success', 'Photo added to camera roll!'));
    }
    // var promise = CameraRoll.saveToCameraRoll(uri);
    // promise
    //   .then(function(result) {
    //     console.log(result);
    //     // const source = { uri:convertLocalIdentifierToAssetLibrary(result,'jpg') };
    //     // this.store.image = source
    //     this.removeIMageTag(uri);
    //   })
    //   .catch(function(error) {
    //     console.log(error);
    //   });
  }
  @action
  async postCase(data, self) {
    var casedata = {
      apartment: data.id,
      description: data.content,
      status: data.status,
      log: data.log,
    };
    if (casedata.log.length == 1) {
      if (casedata.log[0].content == '') {
        casedata.log = [];
      }
    }

    this.loading = true;
    var requestURL = api.getCase;
    try {
      const response = await axios.post(requestURL, casedata, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: this.loginUserData.data.token,
        },
        timeout: 5000,
      });

      transaction(() => {
        this.loading = false;
      });
      console.log(response);

      this.getCase();
      self.props.navigation.popToTop();
    } catch (e) {
      self.refs.toast.show('Failed');
      this.loading = false;

      console.log(e.response);
    }
  }

  @action
  async updateCaseLog(log, caseId, nav, self) {
    var requestURL = api.getCase + caseId + '/log';
    var logData = _.cloneDeep(log);
    try {
      const response = await axios.post(requestURL, logData, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: this.loginUserData.data.token,
        },
        timeout: 5000,
      });

      transaction(() => {});
      console.log(response);
      if (nav) {
        self.props.navigation.popToTop();
      }
      this.getCase();
    } catch (e) {
      console.log(e.response);
    }
  }

  @action
  async updateCase(data, self, index, caseId, clientId) {
    console.log(clientId);
    console.log(this.loginUserData.data.token);

    var casedata = {
      id: caseId,
      client: clientId,
      date: moment().format('X') * 1000,
      apartment: data.id,
      description: data.content,
      status: data.status,
    };
    console.log(casedata.status);
    this.loading = true;
    var requestURL = api.getCase + caseId;

    await fetch(requestURL, {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
      body: JSON.stringify(casedata),
    })
      .then(response => response.json())
      .then(response => {
        console.log(response);
        if (data.log.length > index) {
          console.log('bigger');
          console.log(data.log[index]);
          this.updateCaseLog(data.log[index], caseId);
        } else {
          console.log('same');
        }
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        this.getCase();
        self.props.navigation.popToTop();
      })
      .catch(error => {
        this.loading = false;
        self.refs.toast.show('Failed');
        console.log(error.response);
      });
  }

  @action
  async finishCase(nav, self, caseId) {
    this.loading = true;
    var requestURL = api.getCase + caseId + '/complete';
    await fetch(requestURL, {
      method: 'put',
      body: JSON.stringify({}),
      headers: {
        'Content-Type': 'application/json',
        Authorization: this.loginUserData.data.token,
      },
    })
      .then(response => response.json())
      .then(response => {
        this.loading = false;
        // alert("Upload success!");
        console.log(response);
        this.getCase();
        if (nav) {
          self.props.navigation.popToTop();
        }
      })
      .catch(error => {
        this.loading = false;
        self.refs.toast.show('Failed');
        console.log(error.response);
      });
  }

  @action
  async startAnimate() {
    this.animateStatus.show = true;
    await Animated.timing(this.animateStatus.progress, {
      toValue: 1,
      duration: 1000,
      easing: Easing.linear,
    }).start();
    //this.animateStatus.show = false;
    var self = this;
    setTimeout(function() {
      self.animateStatus.show = false;
      self.animateStatus.progress = new Animated.Value(0);
    }, 1000);
  }

  @action
  async CheckWhichLocalApartmentNotSync() {
    this.apartmentDataWhichNeedToSync = [];
    console.log(this.apartmentsData);
    // console.log(this.loginUserData);
    if (this.loginUserData.data.member.chara == 'owner') {
      this.user.apartment.map((items, index) => {
        console.log('in');
        if (
          this.apartmentsData.findIndex(element => element.id === items.id) ===
            -1 &&
          items.id != 'demo'
        ) {
          var syncData = items;
          syncData.selected = true;
          console.log(syncData);
          this.apartmentDataWhichNeedToSync.push(syncData);
        }
      });
      console.log(this.apartmentDataWhichNeedToSync);
      if (this.apartmentDataWhichNeedToSync.length > 0) {
        // self.props.navigation.navigate('syncApartment');
        NavigationService.navigate('syncApartment');
      } else {
        NavigationService.navigate('home');
      }
    } else {
      NavigationService.navigate('home');
    }
  }

  @action
  async getOneClickRental() {
    var url = api.getOneClickApartment;
    this.loading = true;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      console.log(response);
      this.oneClickApartment = response.data.content;
      this.loading = false;
    } catch (error) {
      console.log(error);
      this.loading = false;
    }
  }

  @action
  async getService(self, items) {
    var url = api.service;
    this.loading = true;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      console.log(response);
      this.loading = false;
      this.serviceContent = response.data.content;
      this.serviceContent.map((data, index) => {
        data.select = false;
      });
      history.push(self, '/newContractData', {apartmentData: items});
    } catch (error) {
      console.log(error);
      this.loading = false;
      self.refs.toast.show('Network failed');
    }
  }
}

export default new Stores();
