/**
 * PayPerUse PayNow支付页面
 * @邠心vbe on 2022/01/10
 */
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, ScrollView } from 'react-native';
import CameraRoll from "@react-native-community/cameraroll";
import ViewShot from "react-native-view-shot";
import Button from '../../components/Button';
import Dialog from '../../components/Dialog';
import { Balance } from '../wallet/Payment';
import {check, request, openSettings, PERMISSIONS, RESULTS} from 'react-native-permissions';

export default class PayPerUse extends Component {
  constructor(props) {
    super(props);
    this.state = {
      amount: 0,
      base64: ''
    };
    this.denied = true;
    this.viewShot = React.createRef();
  }

  componentDidMount() {
    if (this.props.route.params.amount) {
      this.setState({
        amount: this.props.route.params.amount,
        base64: 'data:image/png;base64,' + this.props.route.params.base64
      });
    }
  }

  savePhoto() {
    Dialog.showProgressDialog();
    this.viewShot.current.capture().then(uri => {
      Dialog.dismissLoading();
      CameraRoll.save(uri, { type: 'photo' });
      console.log("Save Photo with ", uri);
      toastShort('Save to gallery successfully');
    }).catch(err => {
      toastShort(err)
      Dialog.dismissLoading();
    });
  }

  getPermission() {
    request(
      isIOS 
    ? PERMISSIONS.IOS.PHOTO_LIBRARY_ADD_ONLY
    : PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE)
    .then(res => {
      console.log('getPermission', res)
      this.checkPermission();
    }).catch(err => {
      console.info('getPermission', err)
    });
  }

  checkPermission() {
    check(
      isIOS 
    ? PERMISSIONS.IOS.PHOTO_LIBRARY_ADD_ONLY
    : PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE)
    .then(res => {
      switch (res) {
        case RESULTS.UNAVAILABLE:
          console.log('此功能不可用（在此设备上/在此上下文中）');
          if (isIOS) {
            this.savePhoto();
          } else {
            toastShort('Save to gallery failed');
          }
          break;
        case RESULTS.DENIED:
          console.log('权限未被请求/被拒绝，但可以请求');
          if (this.denied) {
            this.denied = false;
            this.getPermission();
          } else {
            this.denied = true;
            toastShort('Save to gallery failed');
          }
          break;
        case RESULTS.LIMITED:
          console.log('权限是有限的：有些操作是可能的');
          this.savePhoto();
          break;
        case RESULTS.GRANTED:
          console.log('许可被授予');
          this.savePhoto();
          break;
        case RESULTS.BLOCKED:
          console.log('权限被拒绝，不再可请求');
          Dialog.showDialog({
            title: 'Error',
            message: 'Can not save images, Please grant storage or gallery permissions.',
            ok: 'SETTING',
            callback: btn => {
              if (btn == Dialog.BUTTON_OK) {
                console.log('ok');
                openSettings().catch(() => console.warn('cannot open settings'));
              }
            }
          });
          //toastShort('Save to gallery failed');
          break;
      }
    }).catch(err => {

    })
  }

  render() {
    return (
      <ScrollView
        style={styles.container}>
        <View style={styles.headerView}>
          <Text></Text>
        </View>
        <ViewShot
          ref={this.viewShot}
          style={styles.contentView}
          options={{
            format: "jpg",
            quality: 1
          }}>
          { this.state.base64
          ? <Image
              style={styles.qrCode}
              source={{uri: this.state.base64}}/>
          : <View style={styles.qrCode}></View>
          }
        </ViewShot>
        <Text style={styles.title}>Amount: {currency + ' ' + this.state.amount}</Text>
        <Text style={styles.tips}>Please save the QR Code, and use your bank/eWallet app to scan the QR Code. </Text>
        <Text style={styles.tips}>Once the payment is received, the charging will start automatically.</Text>
        <Text style={styles.tips}>Unutilized amount will be refunded.</Text>
        <View style={styles.button}>
          <Button
            text='Save QR Code to Gallery'
            elevation={1.5}
            onClick={() => {
              this.checkPermission();
            }}/>
        </View>
        <View style={styles.button2}>
          <Button
            text='Payment Completed'
            elevation={1.5}
            onClick={() => {
              goBack();goBack();
            }}/>
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5'
  },
  headerView: {
    paddingBottom: 76,
    //backgroundColor: colorAccent
  },
  contentView: {
    marginTop: -88
  },
  qrCode: {
    margin: 16,
    width: $vw(100) - 32,
    height: $vw(100) - 32,
    borderRadius: 4,
    backgroundColor: '#F0F0F0'
  },
  title: {
    color: '#333',
    fontSize: 18,
    paddingBottom: 16,
    textAlign: 'center'
  },
  tips: {
    color: '#333',
    ...$padding(0, 16, 16),
  },
  button: {
    margin: 16,
    //paddingBottom: 16
  },
  button2: {
    marginLeft: 16,
    marginRight: 16,
  }
})