import React, {Component} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableHighlight,
  TouchableOpacity,
  PermissionsAndroid,
  Dimensions,
  Linking,
  Image,
  Alert,
  Platform,
} from 'react-native';
import {observable} from 'mobx';
var RNFS = require('react-native-fs');
import Share from 'react-native-share';
import Icon from 'react-native-vector-icons/FontAwesome5';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import ViewShot from 'react-native-view-shot';
import history from '../../common/history';
import RNImageToPdf from 'react-native-image-to-pdf';
import BackHeader from '../../components/backHeader';
import {inject, observer} from 'mobx-react';
import NaviBar from '../../components/navi-bar';
var _ = require('lodash');
import HTML from 'react-native-render-html';
import RNHTMLtoPDF from 'react-native-html-to-pdf';
import CameraRoll from '@react-native-community/cameraroll';
import {width, height} from '../../common/screen';
import {colors} from '../../assets/styles/colors-theme';
import Swiper from 'react-native-swiper';
import {Fonts} from '../../assets/styles/fonts-theme';
import RNFetchBlob from 'rn-fetch-blob';
import LoadingView from '../../common/loading';
import Toast, {DURATION} from 'react-native-easy-toast';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
import Size from '../../common/size';
import {date} from 'serializr';
import moment from 'moment';
const IMAGES_MAX_WIDTH = Dimensions.get('window').width - 50;
const CUSTOM_STYLES = {};
const {SlideInMenu} = renderers;
// const formatter = new Intl.NumberFormat('en-US', {
//   style: 'currency',
//   currency: 'HKD',
//   minimumFractionDigits: 0,
// });
const CUSTOM_RENDERERS = {};
const size = new Size();
const DEFAULT_PROPS = {
  htmlStyles: CUSTOM_STYLES,
  renderers: CUSTOM_RENDERERS,
  imagesMaxWidth: IMAGES_MAX_WIDTH,
  onLinkPress: (evt, href) => {
    Linking.openURL(href);
  },
  debug: true,
};

@inject('appStore')
@observer
export default class NewLease extends Component {
  @observable data = {};
  @observable signContractDate = null;
  @observable contractExpiryDate = null;
  @observable remarkString = '';
  @observable saving = false;
  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.data = this.props.navigation.state.params.contractData;
    this.signContractDate = this.data.signContractDate;
    this.contractExpiryDate = this.data.endContractDate;
  }
  currencyFormat(num) {
    return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
  }
  async hasAndroidPermission() {
    const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;

    const hasPermission = await PermissionsAndroid.check(permission);
    if (hasPermission) {
      return true;
    }

    const status = await PermissionsAndroid.request(permission);
    return status === 'granted';
  }

  getPermissionAndroid = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'Image Download Permission',
          message: 'Your permission is required to save images to your device',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        return true;
      }
      Alert.alert(
        'Save remote Image',
        'Grant Me Permission to save Image',
        [{text: 'OK', onPress: () => console.log('OK Pressed')}],
        {cancelable: false},
      );
    } catch (err) {
      Alert.alert(
        'Save remote Image',
        'Failed to save Image: ' + err.message,
        [{text: 'OK', onPress: () => console.log('OK Pressed')}],
        {cancelable: false},
      );
    }
  };

  handleDownload = async uri => {
    // if device is android you have to ensure you have permission
    if (Platform.OS === 'android') {
      const granted = await this.getPermissionAndroid();
      if (!granted) {
        return;
      }
    }
    this.saving = true;
    RNFetchBlob.config({
      fileCache: true,
      appendExt: 'png',
    })
      .fetch('GET', uri)
      .then(res => {
        CameraRoll.saveToCameraRoll(res.data, 'photo')
          .then(() => {
            Alert.alert(
              'Save remote Image',
              'Image Saved Successfully',
              [{text: 'OK', onPress: () => console.log('OK Pressed')}],
              {cancelable: false},
            );
          })
          .catch(err => {
            Alert.alert(
              'Save remote Image',
              'Failed to save Image: ' + err.message,
              [{text: 'OK', onPress: () => console.log('OK Pressed')}],
              {cancelable: false},
            );
          })
          .finally(() => this.setState({saving: false}));
      })
      .catch(error => {
        this.setState({saving: false});
        Alert.alert(
          'Save remote Image',
          'Failed to save Image: ' + error.message,
          [{text: 'OK', onPress: () => console.log('OK Pressed')}],
          {cancelable: false},
        );
      });
  };
  async sign(repay) {
    console.log(repay);
    var newAppliances = [];
    var newKeys = [];
    var newRemark = [];
    var newService = [];
    await this.data.appliances.map((items, index) => {
      var data = {
        chineseName: items.chineseName,
        englishName: items.englishName,
        value: items.value,
      };
      newAppliances.push(data);
    });
    await this.data.key.map((items, index) => {
      var data = {
        chineseName: items.chineseName,
        englishName: items.englishName,
        value: items.value,
      };
      newKeys.push(data);
    });
    await this.data.remark.map((items, index) => {
      newRemark.push(items);
    });

    if (repay) {
      await this.store.serviceContent.map((items, index) => {
        if (items.select) {
          newService.push(_.cloneDeep(items));
        }
      });
    } else {
      await this.data.services.map((items, index) => {
        newService.push(_.cloneDeep(items));
      });
    }
    console.log(this.data.apartment);

    var data = {
      apartment: this.data.apartment,
      ownerId: this.data.ownerId,
      services: newService,
      ownerName: this.data.ownerName,
      payRentDate: this.data.payRentDate,
      numberOfkey: this.data.numberOfkey,
      rentFreePeriod: this.data.rentFreePeriod,
      noteLeasebackMonth: this.data.noteLeasebackMonth,
      monthOfpaymentInLieuOfNotice: this.data.monthOfpaymentInLieuOfNotice,
      atleastRentOfmonth: this.data.atleastRentOfmonth,
      whoPayManagementFee: this.data.whoPayManagementFee,
      whoPayGovernemtRate: this.data.whoPayGovernemtRate,
      whoPayGovernmentRent: this.data.whoPayGovernmentRent,
      ownerPaymentAc: this.data.ownerPaymentAc,
      ownerPhone: this.data.ownerPhone,
      ownerContractAddress: this.data.ownerContactAddress,
      tenantId: this.data.tenantId,
      tenantName: this.data.tenantName,
      tenantPhone: this.data.tenantPhone,
      tenantContractAddress: this.data.tenantContactAddress,
      rent: '' + this.data.rent,
      rates: '' + this.data.rates,
      managementFee: '' + this.data.managementFee,
      leaseMonth: this.data.leaseMonth,
      deposit: '' + this.data.deposit,
      address: this.data.apartmentAddress,
      signContractDate: this.data.signContractDate,
      endContractDate: this.data.endContractDate,
      remark: newRemark,
      appliances: newAppliances,
      key: newKeys,
    };
    console.log(data);
    if (this.store.loginUserData.data.member.chara == 'tenant') {
      Alert.alert(
        '',
        '您在簽租約前，需要自行核實業主身份，如因此合約造成財物損失，我們恕不負責。所以我們建議您進行「土地查冊」，請尋找客服提出需要「土地查冊」服務。',
        [
          {text: this.store.text.cancel, onPress: () => history.goBack(this)},
          {
            text: this.store.text.signatureText,
            onPress: async () => {
              this.store.tenantSign(this.data.id, this);
            },
          },
        ],
      );
    } else {
      if (this.data.services.length > 0) {
        if (this.store.addedCard) {
          history.push(this, '/servicePayment', {data: data, paid: repay});
        } else {
          Alert.alert('', this.store.text.addcreditCardFirst, [
            {
              text: this.store.text.cancel,
              onPress: () => console.log('Cancel'),
            },
            {
              text: this.store.text.add,
              onPress: () => {
                history.push(this, '/card');
              },
            },
          ]);
        }
      } else {
        this.store.ownerCreateContract(data, this, false);
      }

      //this.store.ownerCreateContract(data, this);
    }
    console.log(JSON.stringify(data));
  }

  saveAsFunction(value) {
    this.refs.viewShot.capture().then(uri => {
      console.log('do something with ', uri);
      console.log(value);
      if (value === 2) {
        if(Platform.OS == 'android'){
          uri = uri.replace('file://','')
        }
        this.myAsyncPDFFunction(uri);
      } else if (value === 1) {
        this.saveImage(uri);
      } else if (value === 3) {
        this.shareIt(uri);
      }
    });
  }

  async shareIt(uri) {
    var data = [uri];
    try {
      const options = {
        imagePaths: data,
        name: 'Contract' + moment().format('YYYYMMDDhhmmss'),
      };
      const pdf = await RNImageToPdf.createPDFbyImages(options);
      const shareOptions = {
        title: this.data.apartment + '的租約',
        url: pdf.filePath,
      };

      try {
        const ShareResponse = await Share.open(shareOptions);
        setResult(JSON.stringify(ShareResponse, null, 2));
      } catch (error) {
        console.log('Error =>', error);
        setResult('error: '.concat(getErrorString(error)));
      }
    } catch (e) {
      console.log(e);
    }
  }

  dateHandler(which) {
    if (this.signContractDate !== null) {
      switch (which) {
        case 0:
          return this.signContractDate.getDate();
          break;
        case 1:
          return '' + (this.signContractDate.getMonth() + 1);
          break;
        case 2:
          return this.signContractDate.getFullYear();
          break;
        case 3:
          return this.contractExpiryDate.getDate();
          break;
        case 4:
          return '' + (this.contractExpiryDate.getMonth() + 1);
          break;
        case 5:
          return this.contractExpiryDate.getFullYear();
          break;
        case 6:
          return (
            this.contractExpiryDate.getFullYear() -
            this.signContractDate.getFullYear()
          );
          break;
      }
    }
  }

  async saveImage(uri) {
    if (Platform.OS === 'android') {
      if (!(await this.hasAndroidPermission())) {
        return;
      }

      await CameraRoll.saveToCameraRoll(uri).then(
        this.refs.toast.show('Saved, Photo added to camera roll.'),
      );
    } else {
      await CameraRoll.saveToCameraRoll(uri).then(
        this.refs.toast.show('Saved, Photo added to camera roll.'),
      );
    }
  }

  async myAsyncPDFFunction(uri) {
    var data = [uri];
    try {
      const options = {
        imagePaths: data,
        name: 'Contract' + moment().format('YYYYMMDDhhmmss'),
      };
      const pdf = await RNImageToPdf.createPDFbyImages(options);
      console.log(pdf.filePath);
      this.refs.toast.show('Saved');
    } catch (e) {
      console.log(e);
    }
  }

  renderSignButton() {
    console.log(this.data.signed);
    console.log(this.props.navigation.state.params.showSign);
    if (this.data.signed) {
      return <View />;
    } else {
      if (this.props.navigation.state.params.showSign) {
        return (
          <TouchableHighlight
            style={styles.buttonView}
            onPress={() => {
              this.sign(true);
            }}>
            {this.data.services.length > 0 ? (
              <Text style={styles.buttonText}>
                {this.store.text.signandpay}
              </Text>
            ) : (
              <Text style={styles.buttonText}>
                {this.store.text.signatureText}
              </Text>
            )}
          </TouchableHighlight>
        );
      } else {
        if (this.store.loginUserData.data.member.chara == 'tenant') {
          return (
            <TouchableHighlight
              style={styles.buttonView}
              onPress={() => {
                this.sign(true);
              }}>
              <Text style={styles.buttonText}>
                {this.store.text.signatureText}
              </Text>
            </TouchableHighlight>
          );
        } else {
          if (this.data.servicePaymentStatus == 'Pending Payment') {
            return (
              <TouchableHighlight
                style={styles.buttonView}
                onPress={() => {
                  this.sign(false);
                }}>
                <Text style={styles.buttonText}>{this.store.text.pay}</Text>
              </TouchableHighlight>
            );
          } else {
            return <View />;
          }
        }
      }
    }
  }

  charSelectedHandler(char, which) {
    if (which) {
      if (char == 'owner') {
        return '業主 Landlord';
      } else {
        return '租客 Tenant';
      }
    } else {
      if (char == '業主 Landlord') {
        return 'owner';
      } else {
        return 'tenant';
      }
    }
  }

  renderBackIcon() {
    return (
      <TouchableOpacity
        style={{
          position: 'absolute',
          left: 20,
          justifyContent: 'center',
          alignItems: 'center',
          height: 40,
          width: 40,
        }}
        onPress={() => {
          console.log('back');
          history.goBack(this);
        }}>
        <Icon
          name={'arrow-left'}
          size={22}
          color={'white'}
          style={{
            ...Platform.select({
              ios: {},
              android: {
               // top: 40,
              },
            }),
          }}
        />
      </TouchableOpacity>
    );
  }
  numberToChinese(num) {
    var chnNumChar = [
      '零',
      '一',
      '二',
      '三',
      '四',
      '五',
      '六',
      '七',
      '八',
      '九',
    ];
    var chnUnitChar = [
      '',
      '十',
      '百',
      '千',
      '萬',
      '十',
      '百',
      '千',
      '億',
      '十',
      '百',
      '千',
    ];
    var chnStr = '';
    var str = num.toString();
    while (str.length > 0) {
      var tmpNum = chnNumChar[parseInt(str.substr(0, 1))];
      var tmpChar = chnUnitChar[str.length - 1];
      chnStr += chnStr.substr(-1, 1) == '零' && tmpNum == '零' ? '' : tmpNum;
      if (tmpNum != '零') {
        chnStr += tmpChar;
      }
      if (chnStr == '一十') {
        chnStr = '十';
      }
      str = str.substr(1);
      if (parseInt(str) === 0) {
        if (str.length >= 8) {
          if (chnStr.substr(-1, 1) != '億') {
            chnStr += '億';
          }
        } else if (str.length >= 5) {
          if (chnStr.substr(-1, 1) != '萬万') {
            chnStr += '萬';
          }
        }
        str = '';
      }
    }
    return chnStr;
  }

  renderContent() {
    const content = [
      {
        eng: `The Tenant shall pay to the Landlord the Rent in advance on the  day of each and every calendar month during the Term. If the Tenant shall fail to pay the Rent within 7 days from the due date, the Landlord shall have right to institute appropriate action to recover the Rent and all costs, expenses and other outgoing so incurred by the Landlord in relation to such action shall be a debt owed by the Tenant to the Landlord and shall be recoverable in full by the Landlord.`,
        ch: `租客須在租期內每個月份第 1 天上期繳付指定的租金予業主。倘租客於應繳租金之日的7天內仍未清付該租金，則業主有權採取適當行動追討租客所欠的租金而由此而引起的一切費用及開支將構成租客所欠業主的債項，業主將有權向租客一併追討所欠款項全數。`,
      },
      {
        eng: `The Tenant shall not make any alteration and / or additions to the Premises without the prior written consent of the Landlord, which consent shall not be unreasonably withheld.`,
        ch: `租客在沒有業主書面同意前，不得對該物業作任何改動及／或加建，惟業主不得無理拒絕給予租客有關的同意書。`,
      },
      {
        eng: `The Tenant shall not assign, transfer, sublet or part with the possession of the Premises or any part thereof to any other person. This tenancy shall be personal to the Tenant named herein.`,
        ch: `租客不得轉讓、轉租或分租該物業或其任何部分或將該物業或其任何部分的佔用權讓予任何其他人等。此租約權益將為租客個人擁有。`,
      },
      {
        eng: `The Tenant shall comply with all ordinances, regulations and rules of Hong Kong and shall observe and perform the covenants, terms and conditions of the Deed of Mutual Covenant and Sub-Deed of Mutual Covenant（if any）relating to the Premises. The Tenant shall not contravene any negative or restrictive covenants contained in the Government Lease(s) under which the Premises are held from the Government.`,
        ch: `租客須遵守香港一干法律條例和規則及該物業所屬的大廈有關的公契內的條款。租客亦不可違反屬該物業地段內的官批地契上的任何制約性條款。`,
      },
      {
        eng: `The Tenant shall during the Term pay and discharge all charges in respect of water, electricity, gas and telephone and other similar charges payable in respect of the Premises.`,
        ch: `租客須在租約期內清繳一切有關該物業的水費、電費、煤氣費、電話費及其他類似的雜費等。`,
      },
      {
        eng: `The Tenant shall during the Term keep the interior of the Premises in good and tenantable repair and condition (fair wear and tear and damage caused by inherent defects excepted) and shall deliver up vacant possession of the Premises in the same repair and condition on the expiration or sooner determination of this Agreement.`,
        ch: `租客須在租約期內保持物業內部的維修狀態良好（自然損耗及因固有的缺陷所產生的損壞除外）並須於租約期滿或終止時將物業在同樣的維修狀態下交吉交回業主。`,
      },
      {
        eng: `The Tenant shall pay to the Landlord the Security Deposit set out in Schedule I for the due observance and performance of the terms and conditions herein contained and on his part to be observed and performed. Provided that there is no antecedent breach of any of the terms and conditions herein contained, the Landlord shall refund the Security Deposit to the Tenant without interest within 15 days from the date of delivery of vacant possession of the Premises to the Landlord or settlement of any outstanding payment owed by the Tenant to the Landlord, whichever is later. If the Rent and /or any charges payable by the Tenant hereunder or any part thereof shall be unpaid for seven (7) days after the same shall become payable (whether legally demanded or not) or if the Tenant shall commit a breach of any of the terms and conditions herein contained, it shall be lawful for the Landlord at any time thereafter to re-enter the Premises whereupon this Agreement shall absolutely terminate and the Landlord may deduct any loss or damage suffered by the Landlord as a result of the Tenant's breach from the Security Deposit without prejudice to any other right of action or any remedy of the Landlord in respect of such breach of the Tenant.`,
        ch: `租客須交予業主保証金（金額如附表一所列）作為保証租客遵守及履行此租約上租客所需遵守及履行的條款的按金。若租客在租期內並無干犯此合約內任何條款，則業主須於收回交吉的物業或一切租客欠款後（以較遲者作準）十五天內無息退還該保証金予租客。但若租客拖欠根據此合約需要支付的租金及／或其他款項超過七天（無論有否以法律行動追討）或若租客違反此合約內任何條款，業主可合法收回該物業而此租約將立即被終止；業主可從保証金內扣除因租客違約而令業主所受的損失，而此項權利將不會影響業主因租客違約而可採取的其他合法行動的權利`,
      },
      {
        eng: `Provided the Tenant shall have paid the Rent and other outgoing on the days and in the manner herein provided and observe and perform the terms and conditions herein contained and on the Tenant's part to be observed and performed, the Tenant shall peacefully hold and enjoy the Premises during the Term without any interruption by the Landlord.`,
        ch: `若租客按時清繳租金和雜費及沒有干犯此合約內任何條款，則業主不得在租約期內干擾租客享用該物業。`,
      },
      {
        eng: `The Landlord shall keep and maintain the structural parts of the Premises including the main drains, pipes and cables in proper state of repair Provided that the Landlord's liability shall not be incurred unless and until written notice of any defect or want of repair has been given by the Tenant to the Landlord and the Landlord shall have failed to take reasonable steps to repair and remedy the same after the lapse of a reasonable time from the date of service of such notice.`,
        ch: `業主須保養及適當維修該物業內各主要結構部分（包括主要的排污渠、喉管和電線）。唯業主須在收到租客的書面要求後才會有責任在合理時限內將有關損壞維修妥當。`,
      },
      {
        eng: `The Landlord shall pay the Property tax payable in respect of the Premises.`,
        ch: `業主負責繳付有關該物業的物業稅。`,
      },
      {
        eng: `The Stamp Duty payable on this Agreement in duplicate shall be borne by the landlord and the Tenant in equal shares.`,
        ch: `業主及租客各負責屬此合約一式兩份的印花稅一半費用。`,
      },
      {
        eng: `The Landlord and the Tenant agree to be bound by the additional terms and conditions contained in ScheduleⅡ(if any).`,
        ch: `業主及租客雙方同意遵守附表一內的附加條款（如有的話）。`,
      },
      {
        eng: `If there is any conflict between the English version and the Chinese version in this Agreement, the English version shall prevail.`,
        ch: `此合約內的英文文本與中文文本存有差異時，將以英文文本為準。`,
      },
    ];
    return content.map((items, index) => {
      var num = index + 1;
      return (
        <View style={{marginTop: 10}}>
          <Text style={styles.text}>{num + '.    ' + items.eng}</Text>
          <Text style={styles.text}>{items.ch}</Text>
        </View>
      );
    });
  }

  renderappliances() {
    return this.data.appliances.map((items, index) => {
      return (
        <Text style={styles.text}>
          {items.value + ' ' + items.chineseName + items.englishName}
        </Text>
      );
    });
  }
  renderkeys() {
    console.log(this.data.key);
    return this.data.key.map((items, index) => {
      return (
        <Text style={styles.text}>
          {items.value + '  條' + items.chineseName + items.englishName}
        </Text>
      );
    });
  }

  renderRemark() {
    return this.data.remark.map((items, index) => {
      var value = index + 1;
      return <Text style={styles.text}>{value + '-  ' + items}</Text>;
    });
  }

  render() {
    console.log(this.data);
    return (
      <MenuProvider
        style={{
          flex: 1,

          backgroundColor: 'white',
        }}>
        <LoadingView visible={this.store.loading} />
        <View
          style={{
            marginTop: Platform.OS === 'ios' ? 0 : 10,
            width: width,
            height: Platform.OS === 'ios' ? 65 : 70,
            backgroundColor: colors.mainColor,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text
            style={{fontFamily: Fonts.ubuntu, color: 'white', fontSize: 20}}>
            {this.store.text.addContract}
          </Text>
          <TouchableOpacity
            style={{
              position: 'absolute',
              left: 20,
              justifyContent: 'center',
              alignItems: 'center',
              height: 40,
              width: 40,
            }}
            onPress={() => {
              console.log('back');
              history.goBack(this);
            }}>
            <Icon
              name={'arrow-left'}
              size={22}
              color={'white'}
              style={{
                ...Platform.select({
                  ios: {},
                  android: {},
                }),
              }}
            />
          </TouchableOpacity>

          <View
            style={{
              position: 'absolute',
              right: 20,
              justifyContent: 'center',
              alignItems: 'center',
              height: 40,
              width: 40,
            }}>
            <Menu
              name="share"
              renderer={SlideInMenu}
              onSelect={value => this.saveAsFunction(value)}>
              <MenuTrigger>
                <MaterialCommunityIcons
                  name={'export-variant'}
                  size={30}
                  color={'white'}
                  style={{
                    ...Platform.select({
                      ios: {},
                      android: {},
                    }),
                  }}
                />
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    fontFamily: Fonts.ubuntu,
                    color: 'white',
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                <MenuOption value={1}>
                  <Text
                    style={{
                      color: 'white',
                      fontFamily: Fonts.ubuntu,
                      fontSize: 18,
                    }}>
                    {this.store.text.saveAsImage}
                  </Text>
                </MenuOption>
                <MenuOption value={2}>
                  <Text
                    style={{
                      color: 'white',
                      fontFamily: Fonts.ubuntu,
                      fontSize: 18,
                    }}>
                    {this.store.text.saveAsPdf}
                  </Text>
                </MenuOption>
                <MenuOption value={3}>
                  <Text
                    style={{
                      color: 'white',
                      fontFamily: Fonts.ubuntu,
                      fontSize: 18,
                    }}>
                    {'分享'}
                  </Text>
                </MenuOption>
              </MenuOptions>
            </Menu>
          </View>
        </View>
        <ScrollView style={{flex: 1, backgroundColor: 'white'}}>
          <ViewShot
            ref="viewShot"
            options={{format: 'png', quality: 0.9}}
            captureMode="mount">
            <View style={{flex: 1, margin: 10}}>
              <View style={{width: width - 20, alignItems: 'center'}}>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: Fonts.ubuntu,
                    fontWeight: 'bold',
                  }}>
                  {'Tenancy Agreement'}
                </Text>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: Fonts.ubuntu,
                    fontWeight: 'bold',
                  }}>
                  {'租約'}
                </Text>
              </View>
              <Text style={[styles.text, {marginTop: 10}]}>
                {`An Agreement made the ` +
                  moment(this.data.signContractDate).format('LL') +
                  ` between the Landlord and the Tenant as more particularly described in Schedule I.`}
              </Text>
              <Text style={[styles.text]}>
                {`此合約由業主及租客（雙方資料詳列於附表一）於` +
                  moment(this.data.signContractDate).year() +
                  `年` +
                  moment(this.data.signContractDate).format('MM') +
                  `月` +
                  moment(this.data.signContractDate).format('DD') +
                  `日訂立。`}
              </Text>
              {this.renderContent()}
              <Text style={[styles.text, {marginTop: 10}]}>
                {`Received the Security Deposit of `}
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {this.currencyFormat(parseInt(this.data.deposit))}
                </Text>
                <Text style={[styles.text]}>{` by the Landlord`}</Text>
              </Text>
              <Text style={[styles.text]}>
                {`業主收到租客所交的保証金港幣  `}
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {this.numberToChinese(parseInt(this.data.deposit))}
                </Text>
                <Text style={[styles.text]}>{` 元正`}</Text>
              </Text>
              <Text style={[styles.text, {marginTop: 10}]}>
                {`Received ` +
                  this.data.numberOfkey +
                  ` key(s) of the Premises by the Tenant`}
              </Text>
              <Text style={[styles.text]}>
                {`租客接收業主所交屬該物業的鎖匙共` +
                  this.data.numberOfkey +
                  `條`}
              </Text>
              <View
                style={{
                  width: width - 20,
                  alignItems: 'center',
                  marginTop: 20,
                }}>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: Fonts.ubuntuTh,
                  }}>
                  {'Schedule'}
                </Text>
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: Fonts.ubuntuTh,
                  }}>
                  {'附表 '}
                </Text>
              </View>
              <Text style={[styles.text, {fontWeight: 'bold'}]}>
                {'1.User用途'}
              </Text>
              <Text style={styles.text}>
                {
                  'To use the property for the purpose stipulated in the tenancy agreement only.'
                }
              </Text>
              <Text style={styles.text}>{'物業只可作租約指定的用途。'}</Text>
              <View style={{marginTop: 10}}>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {'2.Rent Free Period免租期'}
                </Text>
                <Text style={styles.text}>
                  {`The Tenant shall be entitled to a rent free period from the ` +
                    moment(this.data.signContractDate).format('DD/MM/YYYY') +
                    ` to ` +
                    moment(this.data.signContractDate)
                      .add(parseInt(this.data.rentFreePeriod), 'days')
                      .format('DD/MM/YYYY') +
                    ` (both days inclusive) provided that the Tenant shall be responsible for the charges of, water, electricity, gas, telephone and other outgoings payable in respect of Premises during such rent free period.`}
                </Text>
                <Text style={styles.text}>
                  {`租客可享有` +
                    this.data.rentFreePeriod +
                    `天免租期（由` +
                    moment(this.data.signContractDate).format('DD/MM/YYYY') +
                    `至` +
                    moment(this.data.signContractDate)
                      .add(parseInt(this.data.rentFreePeriod), 'days')
                      .format('DD/MM/YYYY') +
                    `）（包括首尾兩天）但租客仍需負責繳付免租期內一切水、電、煤電及電話費用及其他一切雜費支出。`}
                </Text>
              </View>
              <View style={{marginTop: 10}}>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {'3.Break Clause退租權'}
                </Text>
                <Text style={styles.text}>
                  {`Notwithstanding anything to the contrary hereinbefore contained, both the Tenant and the Landlord shall be entitled to terminate this Agreement earlier than as herein provided by serving not less than  ` +
                    this.data.noteLeasebackMonth +
                    ` months' written notice or by paying ` +
                    this.data.monthOfpaymentInLieuOfNotice +
                    ` months' Rent in lieu to the other party provided that this Agreement shall not be terminated earlier than a date which shall be ` +
                    this.data.atleastRentOfmonth +
                    ` months from the commencement date of the Term（i.e., the Tenant shall rent the Premises for at least ` +
                    this.data.atleastRentOfmonth +
                    ` months）.`}
                </Text>
                <Text style={styles.text}>
                  {`租客可給予業主不少於 ` +
                    this.data.noteLeasebackMonth +
                    ` 個月的書面通知或 ` +
                    this.data.monthOfpaymentInLieuOfNotice +
                    ` 個月租金作代通知金提早解除此租約；唯此租約的終止日期不得早於由租期開始日計 ` +
                    this.data.atleastRentOfmonth +
                    ` 個月（即租客最少要租用該
物業 ` +
                    this.data.atleastRentOfmonth +
                    ` 個月）。`}
                </Text>
              </View>
              <View style={{marginTop: 10}}>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {`4. 業主或租客需負責下列費用 Landlord or Tenant shall be responsible for the following payments:`}
                </Text>
                <Text style={[styles.text]}>
                  {`管理費Management Fee ` +
                    this.charSelectedHandler(
                      this.data.whoPayManagementFee,
                      true,
                    ) +
                    ` 負責responsible`}
                </Text>
                <Text style={[styles.text]}>
                  {`差餉Government Rate ` +
                    this.charSelectedHandler(
                      this.data.whoPayGovernemtRate,
                      true,
                    ) +
                    ` 負責responsible`}
                </Text>
                <Text style={[styles.text]}>
                  {`地租Government Rent ` +
                    this.charSelectedHandler(
                      this.data.whoPayGovernmentRent,
                      true,
                    ) +
                    ` 負責responsible`}
                </Text>
              </View>
              <View style={{marginTop: 10}}>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {`5.費用細節(如有):Fee Detail(If Any) :`}
                </Text>
                <Text style={[styles.text]}>
                  {`業主提供以下電器予租客使用 Landlord provides the following appliances for Tenant to use:`}
                </Text>
                {this.renderappliances()}
                <Text style={[styles.text]}>
                  {`業主給予租客保管的鎖匙 The key given to the tenant by the landlord for keeping:`}
                </Text>
                {this.renderkeys()}
              </View>
              <View style={{marginTop: 10}}>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {`6. 業主收租之銀行戶口  :` + this.data.ownerPaymentAc}
                </Text>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {`Landlord's bank account for receiving rent payment :` +
                    this.data.ownerPaymentAc}
                </Text>
              </View>
              <View style={{marginTop: 10}}>
                <Text style={[styles.text, {fontWeight: 'bold'}]}>
                  {'7. 其他 Others:'}
                </Text>
                {this.renderRemark()}
              </View>
              <View style={{marginTop: 10, flexDirection: 'row'}}>
                <View style={{width: 200}}>
                  <Text style={styles.text}>
                    {'業主簽署 Signed by the Landlord '}
                  </Text>
                  <Image
                    style={{width: 100, height: 100}}
                    source={{uri: this.data.ownerSignUri}}
                  />
                  {this.data.stamp != '' ? (
                    <View>
                      <Text style={styles.text}>
                        {'公司印章 company chop '}
                      </Text>
                      <Image
                        style={{width: 100, height: 100}}
                        source={{uri: this.data.stamp}}
                      />
                    </View>
                  ) : (
                    <View />
                  )}
                </View>
                <View style={{width: 200}}>
                  <Text style={styles.text}>
                    {'租客簽署 Signed by the Tenant '}
                  </Text>
                  <Image
                    style={{width: 100, height: 100}}
                    source={{uri: this.data.tenantSignUri}}
                  />
                </View>
              </View>
            </View>
          </ViewShot>
          {this.renderSignButton()}
        </ScrollView>

        <Toast
          ref="toast"
          style={{backgroundColor: colors.mainColor}}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{color: 'white'}}
        />
      </MenuProvider>
    );
  }
}
const styles = StyleSheet.flatten({
  textView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntuL,
    fontSize: size.getSize(13),
  },
  buttonText: {
    color: '#fff',
  },
  buttonView: {
    backgroundColor: colors.mainColor,
    marginRight: 30,
    marginLeft: 30,
    marginTop: 30,
    marginBottom: 30,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },
  buttonText: {
    fontSize: 15,
    fontFamily: Fonts.ubuntu,
    color: 'white',
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#9DD6EB',
  },
  slide2: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#97CAE5',
  },
  slide3: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#92BBD9',
  },
  text: {
    fontSize: 9,
    fontFamily: Fonts.ubuntuL,
  },
});
