import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  FlatList,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import history from '../../common/history';
import moment from 'moment';
import LoadingView from '../../common/loading';
import BackHeader from '../../components/backHeader';
import NaviBar from '../../components/navi-bar';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Migrations from '../../services/realm/Mirgrations';
import {inject, observer} from 'mobx-react';
import {queryUser} from '../../services/realm/realmManger';
import Swiper from 'react-native-swiper';
import Global from '../../services/Global';
import {width, height} from '../../common/screen';
import ReceiptList from './receiptList';
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';

import Realm from 'realm';
import {observable, toJS} from 'mobx';
import {func} from 'prop-types';
let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});

let data = [
  {
    date: '1/9/2019',
    rent: '9800',
    id: '649245',
    owner: 'Herbert Chan',
    ownerPhone: '+852 94321156',
    tenant: 'Sam Cheung',
    tenantPhone: '+852 54321123',
    address: '323, La Ha Village, Sha Tin, N.T.',
  },
  {
    date: '1/8/2019',
    rent: '9800',
    id: '649254',
    owner: 'Herbert Chan',
    ownerPhone: '+852 94321156',
    tenant: 'Sam Cheung',
    tenantPhone: '+852 54321123',
    address: '323, La Ha Village, Sha Tin, N.T.',
  },
];

@inject('appStore')
@observer
export default class Receipt extends Component<Props> {
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }
  currencyFormat(num) {
    return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
 }
  componentWillMount() {
    //this.getRceipt()
    this.store.getRentReceipt(this.props.navigation.state.params.index);
  }

  async getRceipt() {
    if (this.store.loginUserData.data.member.chara == 'owner') {
      var contractindex = await this.store.apartmentsData[
        this.props.navigation.state.params.index
      ].contracts.findIndex(
        element =>
          element.tenant.id ==
          this.store.apartmentsData[this.props.navigation.state.params.index]
            .tenant.id,
      );
      console.log(this.store.getNowDate);
      console.log(
        moment(parseInt(this.store.getNowDate * 1000)).format('YYYYMM'),
      );
      if (contractindex != -1) {
        this.store.receiptData = [];
        this.store.apartmentsData[
          this.props.navigation.state.params.index
        ].contracts[contractindex].rents.map(async (items, index) => {
          console.log(
            parseInt(
              moment(parseInt(this.store.getNowDate * 1000)).format('YYYYMM'),
            ),
          );
          console.log(parseInt(items.month));
          if (
            parseInt(
              moment(parseInt(this.store.getNowDate * 1000)).format('YYYYMM'),
            ) >= parseInt(items.month)
          ) {
            console.log('testingtesting');
            // const formatter = new Intl.NumberFormat('en-US', {
            //   style: 'currency',
            //   currency: 'HKD',
            //   minimumFractionDigits: 0,
            // });
            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.store.apartmentsData[
                this.props.navigation.state.params.index
              ].owner.fullname,
              ownerPhone:
                this.store.apartmentsData[
                  this.props.navigation.state.params.index
                ].owner.countryCode +
                ' ' +
                this.store.apartmentsData[
                  this.props.navigation.state.params.index
                ].owner.phone,
              tenant: this.store.apartmentsData[
                this.props.navigation.state.params.index
              ].tenant.fullname,
              tenantPhone:
                this.store.apartmentsData[
                  this.props.navigation.state.params.index
                ].tenant.countryCode +
                ' ' +
                this.store.apartmentsData[
                  this.props.navigation.state.params.index
                ].tenant.phone,
              address: this.store.apartmentsData[
                this.props.navigation.state.params.index
              ].address,
              status: items.status,
            };
            await this.store.receiptData.push(data);
            console.log(this.store.receiptData);
          }
        });
      }
    } else {
      this.store.receiptData = [];
      this.store.apartmentsData[
        this.props.navigation.state.params.index
      ].contracts[0].rents.map(async (items, index) => {
        console.log(
          parseInt(
            moment(parseInt(this.store.getNowDate * 1000)).format('YYYYMM'),
          ),
        );
        console.log(parseInt(items.month));
        if (
          parseInt(
            moment(parseInt(this.store.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.store.apartmentsData[
              this.props.navigation.state.params.index
            ].owner.fullname,
            ownerPhone:
              this.store.apartmentsData[
                this.props.navigation.state.params.index
              ].owner.countryCode +
              ' ' +
              this.store.apartmentsData[
                this.props.navigation.state.params.index
              ].owner.phone,
            tenant: this.store.apartmentsData[
              this.props.navigation.state.params.index
            ].tenant.fullname,
            tenantPhone:
              this.store.apartmentsData[
                this.props.navigation.state.params.index
              ].tenant.countryCode +
              ' ' +
              this.store.apartmentsData[
                this.props.navigation.state.params.index
              ].tenant.phone,
            address: this.store.apartmentsData[
              this.props.navigation.state.params.index
            ].address,
            status: items.status,
          };
          await this.store.receiptData.push(data);
          console.log(this.store.receiptData);
        }
      });
    }
  }

  clickAction(item) {
    if (item.status == 'Pending Payment') {
      Alert.alert(
        '',
        '確定收到租客租金?',
        [
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          {
            text: 'Yes',
            onPress: () => {
              item.index = this.props.navigation.state.params.index;
              this.store.markpaid(this, item);
            },
          },
        ],
        {cancelable: false},
      );
    } else {
      item.index = this.props.navigation.state.params.index;
      history.push(this, '/receiptDetails', {receiptData: item});
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <BackHeader instance={this} back={true} />
        <LoadingView visible={this.store.loading} />
        <FlatList
          data={toJS(this.store.receiptData)}
          renderItem={({item}) => (
            <ReceiptList
              items={item}
              onPress={() => {
                this.clickAction(item);
              }}
            />
          )}
          keyExtractor={item => item.id}
        />
      </View>
    );
  }
}

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