import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  Image,
  ScrollView,
  Keyboard,
  TouchableWithoutFeedback,
  StyleSheet,
  TextInput,
  Alert,
  Platform,
  Linking
} from 'react-native';
var _ = require('lodash');
import Modal from 'react-native-modal';
import HoshiTextInput from '../../components/hoshiTextInput';
import Dialog from "react-native-dialog";
import { inject, observer } from 'mobx-react';
import moment from 'moment';
import { observable } from 'mobx';
import { images } from '../../assets/images/imageIndex';
import DatePicker from 'react-native-date-picker';
import FastImage from 'react-native-fast-image';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import DateTimePicker from '@react-native-community/datetimepicker';
import CheckAnimate from '../../components/checkAnimate';
import { width, height } from '../../services/screen';
import Loading from '../../components/Loading';
import CustomLoginButon from '../../components/customLoginButton';
import { colors } from '../../assets/styles/colors-theme';
import Toast, { DURATION } from 'react-native-easy-toast';
import { getStatusBarHeight } from 'react-native-status-bar-height';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import IonIcon from 'react-native-vector-icons/dist/Ionicons';
import CustomTextInput from '../../components/customTextInput';
import TitleBar from '../../components/titleBar';
import CustomLoginButton from '../../components/customLoginButton';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const { SlideInMenu } = renderers;
Icon.loadFont();
@inject('appStore')
@observer
export default class Order extends React.Component {
  @observable
  paymentseletion = [
    { label: 'Visa', value: 0 },
    // { label: this.store.text.cashOnDelivery, value: 1 },
    { label: this.store.text.fpsorpayme, value: 2 },
    // {label: 'Alipay', value: 1},
  ];

  @observable
  isOrder = true;
  @observable
  selectDateCheck = false;
  @observable
  usingDiscount = false
  @observable
  data = null;
  @observable
  discountPrice = '0'
  @observable
  shippingSelection = [
    // { label: '門市自取', value: 0, price: 0, freeShippingPrice: 0 },
    {
      label: '送到上門（滿' + '200' + '免運費)',
      value: 0,
      price: 0,
      freeShippingPrice: 0,
    },
  ];

  @observable
  paymentSelected = 0;

  @observable
  payDisable = false;

  @observable
  shippingSelected = 0;

  @observable
  coupon1 = '0';
  @observable
  coupon2 = '';
  @observable
  coupon2Correct = false;
  @observable
  coupon2Index = null;
  @observable
  shippingPrice = 50;
  @observable
  totalProductsPrice = 0;
  @observable
  discountProducts = [];
  @observable
  normalProducts = [];
  @observable
  discountTotalPrice = 0;
  @observable
  discountProductsEnable = false;
  @observable
  totalPrice = 0;
  @observable
  shippingDate = new Date();
  @observable
  freeShip = false;
  @observable showDatePicker = false;
  @observable
  uploadImage = null;
  @observable
  dateWithoutHoliday = [];
  @observable
  shoppingGroup = null;
  @observable
  totalamount = 0;
  @observable
  totalDiscount = 0;
  @observable
  discountTitle = ''
  @observable
  cancelOrderVisable = false
  @observable
  cancelOrderReason = ''

  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.isOrder = this.props.route.params.order;
    if (!this.isOrder) {
      this.data = this.props.route.params.data;
      console.log(this.data)
      this.data.items.map((products, index) => {
        if (products.hasOwnProperty('discount')) {
          console.log('test')
          this.discountTitle = products.discount.name
          this.discountTotalPrice += products.discount.discountAmount
        }
      })
      if (this.data.discounts.length > 0) {
        console.log('test1')
        this.discountTitle = this.data.discounts[0].name
        this.discountTotalPrice = this.data.discounts[0].discountAmount

      }
      if (this.data.status == 'PRJ') {
        this.paymentSelected = 2
      }
    }
  }
  statusHandler(text) {
    const lang = this.store.text;
    switch (text) {
      case 'PC':
        return lang.pc;
        break;
      case 'PP':
        return lang.pp;
        break;
      case 'PRV':
        return lang.prv;
        break;
      case 'PRJ':
        return lang.prj;
        break;
      case 'PA':
        return lang.pa;
        break;
      case 'ARV':
        return lang.arv;
        break;
      case 'FIN':
        return lang.fin;
        break;
      case 'CAN':
        return lang.can;
        break;
      case 'EXP':
        return lang.exp;
      case "VO":
        return lang.vo;
        break;
    }
  }

  async componentWillMount() {
    await this.store.getShippingOrderDate();
    await this.getUserShoppingGroup();
    await this.store.getPoints();
    await this.cloneOrderList();
    await this.store.getCoupons(this);
    await this.store.getDiscount();
    await this.store.getShipppingMethods(this);
    this.shippingDate = await this.minOrderDateHandler();
    if (this.store.creditCardinfo != null) {
      this.paymentseletion[0].label =
        this.store.text.creditCard +
        '   ' +
        '**** **** **** ' +
        this.store.creditCardinfo.number;
    }
    this.countTotalPrice();
    if (this.store.orderList.findIndex(element => element.on_sale == true) > -1) {
      this.usingDiscount = true

    }

    if (this.usingDiscount) {
      this.countDiscount()
    }
    console.log(this.discountPrice)

  }

  componentDidMount() {
    this.shippingPriceReturn();
  }

  async getUserShoppingGroup() {
    await this.store.getOwnShoppingGroup(this, true, false);
    this.findThisMonthTotalAmount()
  }

  saveImageHandler(image) {
    var photoId = this.store.idGenerator();
    console.log(photoId);
    return {
      id: photoId,
      name: photoId + '.jpg',
      createDate: new Date(),
      uri: image.uri,
      mime: image.type,
      height: image.height,
      width: image.width,
    };
  }

  saveAndroidImageHandler(image) {
    var photoId = this.store.idGenerator();
    return {
      id: photoId,
      name: photoId + '.jpg',
      createDate: new Date(),
      uri: image.uri,
      mime: image.type,
      height: image.height,
      width: image.width,
    };
  }

  minOrderDateHandler() {
    if (this.store.shippingOrderDate.order_cutoff_time != null) {
      if (parseInt(moment().format('HHmm')) < parseInt(this.store.shippingOrderDate.order_cutoff_time)) {
        return moment(this.store.dateWithoutHoliday[0].date).toDate();
      } else {
        return moment(this.store.dateWithoutHoliday[0].date).add('days', 1).toDate()
      }
    } else {
      return moment(this.store.dateWithoutHoliday[0].date).toDate();
    }

  }

  maxOrderDateHandler() {
    return moment(
      this.store.dateWithoutHoliday[this.store.dateWithoutHoliday.length - 1].date,
    ).toDate();
  }

  changeDate(date) {
    var selectedDateIndex = this.store.shippingOrderDate.available_delivery_dates.findIndex(
      element => element.date == moment(date).format('YYYY-MM-DD'),
    );
    console.log(selectedDateIndex);
    if (
      this.store.shippingOrderDate.available_delivery_dates[selectedDateIndex]
        .holiday
    ) {
      this.shippingDate = this.minOrderDateHandler();
      this.refs.toast.show(
        this.store.shippingOrderDate.available_delivery_dates[selectedDateIndex]
          .description,
      );
    } else {
      this.shippingDate = moment(date).toDate();
    }
  }

  shippingPriceReturn(which) {
    if (this.store.shippingMethods.length > 0) {
      var shipToHome = this.store.shippingMethods.findIndex(
        element => element.type == 1,
      );

      var takeGoodsInShop = this.store.shippingMethods.findIndex(
        element => element.type == 0,
      );

      if (takeGoodsInShop != -1) {
        this.shippingSelection = [
          {
            label: '門市自取',
            value: 0,
            price: 0,
            id: this.store.shippingMethods[takeGoodsInShop].id,
            freeShippingPrice: parseFloat(
              this.store.shippingMethods[shipToHome].free_shipping_min_amount,
            ),
          },
          {
            freeShippingPrice: parseFloat(
              this.store.shippingMethods[shipToHome].free_shipping_min_amount,
            ),
            id: this.store.shippingMethods[shipToHome].id,
            label:
              '送到上門（滿' +
              this.store.priceFormatReturn(
                parseFloat(
                  this.store.shippingMethods[shipToHome]
                    .free_shipping_min_amount,
                ),
              ) +
              '免運費)',
            value: 1,
            price: parseFloat(this.store.shippingMethods[shipToHome].fee),
          },
        ];
      }
    }
  }

  renderShippingSelection(items) {
    return (
      <TouchableOpacity
        style={{
          flexDirection: 'row',
          marginTop: 5,
          alignItems: 'center',
          marginRight: 10,
        }}
        onPress={() => {
          this.shippingSelected = items.value;
          this.countTotalPrice();
        }}>
        <View style={{ flexDirection: 'row', alignItems: 'center', flex: 0.8 }}>
          {items.value === this.shippingSelected ? (
            <Icon name="circle-slice-8" color={colors.mainColor} size={12} />
          ) : (
              <Icon name="circle-outline" color={'black'} size={12} />
            )}
          <Text style={{ marginLeft: 5, fontSize: 12 }}>{items.label}</Text>
        </View>
        <View style={{ flex: 0.2 }}>
          <Text style={{ marginLeft: 5, fontSize: 12 }}>
            {this.store.priceFormatReturn(items.price)}
          </Text>
        </View>
      </TouchableOpacity>
    );
  }

  cloneOrderList() {
    this.normalProducts = [];
    this.store.orderList.map((items, index) => {
      this.normalProducts.push(_.cloneDeep(items));
    });
  }

  renderPaymentSelection(items) {
    return (
      <TouchableOpacity
        style={{ flexDirection: 'row', marginTop: 5, alignItems: 'center' }}
        onPress={() => (this.paymentSelected = items.value)}>
        {items.value === this.paymentSelected ? (
          <Icon name="circle-slice-8" color={colors.mainColor} size={12} />
        ) : (
            <Icon name="circle-outline" color={'black'} size={12} />
          )}
        <Text style={{ marginLeft: 5, fontSize: 12 }}>{items.label}</Text>
      </TouchableOpacity>
    );
  }


  async orderAction() {
    var cutoffDate = [];
    if (this.store.nowDate != null &&
      parseInt(moment(this.store.nowDate).format('DD')) == parseInt(moment().format('DD'))) {
      if (this.store.loginUserData.data.mobile != null) {
        if (this.store.addresses.length > 0) {
          //  if (this.store.creditCardinfo != null || this.paymentSelected != 0) {

          var data = {
            usePoints: this.coupon1,
            deliveryDate: moment(this.shippingDate).format('YYYY-MM-DD'),
            items: [],
            // coupons: {
            //   couponsId: this.coupon2,
            // },
            discounts: [],
            coupons: [],
          };

          if (this.store.discount.length > 0) {
            if (this.store.discount[0].type == 0) {
              const on_saleIndex = await this.store.orderList.findIndex(e => e.on_sale == true)
              if (on_saleIndex >= 0) {
                var discountData = {
                  discountId: this.store.discount[0].id
                }
                data.discounts.push(discountData)
              }
            }
          }
          if (this.coupon2 != '' && this.coupon2Correct) {
            var coupon = {
              couponId: this.coupon2,
            };
            data.coupons.push(coupon);
          }
          await this.store.orderList.map(async (items, index) => {
            var orderData = {
              itemId: items.id,
              qty: items.buyCount,
            };
            if (this.store.discount.length > 0 && items.on_sale) {
              if (this.store.discount[0].type > 0) {
                orderData.discount = {
                  discountId: this.store.discount[0].id
                }
              }
            }
            if (items.hasOwnProperty('deliveryCutoffDate')) {
              cutoffDate.push(items)
            }
            await data.items.push(orderData);
          });
          console.log(data);
          if (this.props.route.params.order) {
            if (this.selectDateCheck) {
              if (cutoffDate.length > 0) {
                var cutoffIndex = 1;
                cutoffIndex = await cutoffDate.findIndex(e => moment(this.shippingDate).valueOf() > moment(e.deliveryCutoffDate).valueOf())
                console.log(moment(cutoffDate[0].deliveryCutoffDate).valueOf())
                console.log(moment(this.shippingDate).valueOf())
                console.log(cutoffIndex)
                if (cutoffIndex >= 0) {
                  Alert.alert(
                    this.store.text.pleaseSelectAnotherDeiveryDate,
                    cutoffDate[cutoffIndex].name + " " + this.store.text.lastDeliveryDate + " " + moment(cutoffDate[cutoffIndex].deliveryCutoffDate).format('DD/MM/YYYY'),
                    [
                      {
                        text: "OK",
                        onPress: () => { },
                        style: "cancel",
                      },
                    ],

                  );
                } else {
                  if (parseInt(moment(this.shippingDate).format('DD')) != parseInt(moment(this.store.dateWithoutHoliday[0].date).format('DD'))) {
                    this.store.postOrder(data, this);
                  } else {
                    if (parseInt(moment().format('HHmm')) < parseInt(this.store.shippingOrderDate.order_cutoff_time)) {
                      this.store.postOrder(data, this);
                    } else {
                      Alert.alert('', 'Error', [
                        {
                          text: this.store.text.sure,
                          onPress: () => {
                            this.props.navigation.goBack()
                          },
                        },
                      ]);
                    }
                  }
                }
              } else {
                if (parseInt(moment(this.shippingDate).format('DD')) != parseInt(moment(this.store.dateWithoutHoliday[0].date).format('DD'))) {
                  this.store.postOrder(data, this);
                } else {
                  if (parseInt(moment().format('HHmm')) < parseInt(this.store.shippingOrderDate.order_cutoff_time)) {
                    this.store.postOrder(data, this);
                  } else {
                    Alert.alert('', 'Error', [
                      {
                        text: this.store.text.sure,
                        onPress: () => {
                          this.props.navigation.goBack()
                        },
                      },
                    ]);
                  }
                }
              }

            } else {
              this.refs.toast.show(this.store.text.pleasePickTheShippingDate)
            }
          } else {
            if (this.paymentSelected == 0) {
              if (this.store.creditCardinfo != null || this.paymentSelected != 0) {
                this.store.payByCreditCard(this.data.id, this)
              } else {
                this.refs.toast.show('請先加入信用卡');
              }
            } else if (this.paymentSelected == 1) {
              this.store.payBycash(this.data.id, this)
            } else {
              if (this.uploadImage != null) {
                this.store.payByBank(this.data.id, this.uploadImage.uri, this)
              } else {
                this.refs.toast.show('Please upload image')
              }
            }
          }
          // } else {
          //   this.refs.toast.show('請先加入信用卡');
          // }
        } else {
          this.refs.toast.show('請先加入地址');
        }
      } else {
        Alert.alert('', '請先加入電話號碼', [
          { text: '取消', onPress: () => console.log('Cancel') },
          {
            text: '加入',
            onPress: () => {
              this.props.navigation.navigate('SignUpVerify', {
                data: {
                  first_name: '',
                  last_name: '',
                  welcome_code: '',
                  country_code: '+852',
                  mobile: '',
                  email: '',
                  ver_code: '',
                  password: '',
                },
                addMobile: true,
              });
            },
          },
        ]);
      }
    } else {
      Alert.alert('', 'Error', [
        {
          text: this.store.text.sure,
          onPress: () => {
            this.props.navigation.goBack()
          },
        },
      ]);
    }

  }

  async coupon2OnChangeText(text) {
    this.coupon2 = text;
    console.log(this.coupon2);
    console.log(this.store.coupons);
    var index = this.store.coupons.findIndex(element => element.id === text);
    console.log(index);
    if (index != -1) {
      console.log('index != -1');
      var coupon = this.store.coupons[index];

      if (coupon.limitPerUser > coupon.userUsed || coupon.limitPerUser == 0) {
        if (this.totalProductsPrice >= coupon.minAmount) {
          this.coupon2Correct = true;
          this.coupon2Index = index;
          console.log(index);
          console.log(this.totalProductsPrice);
        } else {
          console.log(this.totalProductsPrice);

          this.coupon2 = '';
          this.refs.toast.show(
            '此優惠券需要購買總數超過' +
            this.store.priceFormatReturn(parseFloat(coupon.minAmount)) +
            '的産品',
          );
        }
      } else {
        this.coupon2 = '';
        this.refs.toast.show('已超過優惠券使用次數');
      }
    } else {
      this.coupon2Correct = false;
      this.coupon2Index = null;
      this.discountProductsEnable = false;
      this.discountProducts = [];
      this.discountTotalPrice = 0;
      this.cloneOrderList();
    }
    this.countTotalPrice();
  }

  checkPrice(price) {
    if (price <= this.store.coupons[this.coupon2Index].minAmount) {
      this.coupon2 = '';
      this.refs.toast.show(
        '此優惠券需要購買總數超過' +
        this.store.priceFormatReturn(
          parseFloat(this.store.coupons[this.coupon2Index].minAmount),
        ) +
        '的優惠券支持的産品價格',
      );
      this.coupon2Correct = false;
      this.coupon2Index = null;
      this.discountProductsEnable = false;
      this.discountProducts = [];
      this.discountTotalPrice = 0;
      this.cloneOrderList();
    }
  }

  async discountProductsHandler(which, ids) {
    this.discountTotalPrice = 0;
    this.discountProducts = [];
    if (which) {
      await ids.forEach(element => {
        this.store.orderList.map((items, index) => {
          if (items.id == element) {
            this.normalProducts.splice(
              this.normalProducts.findIndex(
                normalItem => normalItem.id == element,
              ),
              1,
            );
            this.discountTotalPrice += parseFloat(items.price) * items.buyCount;
            this.discountProducts.push(_.cloneDeep(items));
          }
        });
      });
      console.log(this.discountProducts);
    } else {
      await ids.forEach(element => {
        this.store.orderList.map((items, index) => {
          items.categories.map((categoriesItems, index) => {
            if (categoriesItems.id == element) {
              this.normalProducts.splice(
                this.normalProducts.findIndex(
                  normalItem => normalItem.id == items.id,
                ),
                1,
              );
              this.discountTotalPrice +=
                parseFloat(items.price) * items.buyCount;
              this.discountProducts.push(_.cloneDeep(items));
            }
          });
        });
      });
      console.log(this.discountProducts);
      this.store.removeDuplicates(this.discountProducts, it => it.id);
    }
  }

  async exclude_sale_itemsHandler() {
    this.x = 0;
    this.discountProducts = [];
    await this.store.orderList.map(async (items, index) => {
      if (!items.on_sale) {
        await this.normalProducts.splice(
          this.normalProducts.findIndex(element => element.id == items.id),
          1,
        );
        await this.discountProducts.push(_.cloneDeep(items));
        this.discountTotalPrice += parseFloat(items.price) * items.buyCount;
      }
    });
    console.log(this.discountProducts);
  }

  imagepick(which) {
    if (which == 1) {

      launchCamera({ mediaType: 'photo' }, response => {
        console.log(response);
        //var response = image;
        if (response.hasOwnProperty('errorMessage')) {
          Alert.alert(
            "",
            this.store.text.openCamera,
            [
              {
                text: "ok",
                onPress: () => Linking.openSettings(),
              },
            ]
          );

        } else {
          if (Platform.OS === 'ios') {
            // const uri = this.store.convertLocalIdentifierToAssetLibrary(
            //   response.localIdentifier,
            //   'JPG',
            // );
            // response.path = uri;
            // console.log(response.path);
            this.uploadImage = this.saveImageHandler(response);
            console.log(this.uploadImage);
          } else {
            this.uploadImage = this.saveAndroidImageHandler(response);
          }
        }
      });
    } else {
      // ImagePicker.openPicker({
      //   includeExif: true,
      //   includeBase64: false,
      //   writeTempFile: false,
      //   multiple: false,
      //   mediaType: 'photo',
      //   cropping: false,
      // }).then(image => {
      //   console.log(image);
      //   var response = image;

      //   if (Platform.OS === 'ios') {
      //     // const uri = this.store.convertLocalIdentifierToAssetLibrary(
      //     //   response.localIdentifier,
      //     //   'JPG',
      //     // );
      //     // response.path = uri;
      //     // console.log(response.path);
      //     this.uploadImage = this.saveImageHandler(response);
      //     console.log(this.uploadImage);
      //   } else {
      //     this.uploadImage = this.saveAndroidImageHandler(response);
      //   }
      // });
      launchImageLibrary({ mediaType: 'photo' }, response => {
        console.log(response);
        //var response = image;

        if (Platform.OS === 'ios') {
          // const uri = this.store.convertLocalIdentifierToAssetLibrary(
          //   response.localIdentifier,
          //   'JPG',
          // );
          // response.path = uri;
          // console.log(response.path);
          this.uploadImage = this.saveImageHandler(response);
          console.log(this.uploadImage);
        } else {
          this.uploadImage = this.saveAndroidImageHandler(response);
        }
      });
    }
  }

  renderPaymeOrFps() {
    const picker = [
      {
        value: 0,
        label: this.store.text.album,
      },
      {
        value: 1,
        label: this.store.text.camera,
      },
    ];

    if (this.paymentSelected == 2) {
      return (
        <View
          style={{
            marginTop: 10,
            width: width - 80,
            marginLeft: 20,
          }}>
          <Text style={{ fontSize: 12 }}>{this.store.text.bank + ': 035 華僑永亨銀行'}</Text>
          <Text style={{ fontSize: 12 }}>{this.store.text.accountName + ': Asian Mea Inc Limited'}</Text>
          <Text style={{ fontSize: 12 }}>{this.store.text.accountnumber + ': 822-403841-051'}</Text>
          <View
            style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Menu
              name="upload"
              renderer={SlideInMenu}
              onSelect={value => {
                this.imagepick(value);
              }}>
              <MenuTrigger
                disabled={!this.areaSelectIndex == null}
                style={{ flexDirection: 'row', marginBottom: 5 }}>
                {this.uploadImage != null ? (
                  <FastImage
                    style={{
                      width: 250,
                      height: 250,
                      marginTop: 20,
                      borderRadius: 40,
                      borderWidth: 1,
                      borderColor: colors.line2Color,
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                    source={{ uri: this.uploadImage.uri }}
                  />
                ) : (
                    <View
                      style={{
                        width: 250,
                        height: 250,
                        marginTop: 20,
                        borderRadius: 40,
                        borderWidth: 1,
                        borderColor: colors.line2Color,
                        justifyContent: 'center',
                        alignItems: 'center',
                      }}>
                      <Icon
                        name="image-plus"
                        size={40}
                        color={colors.line2Color}
                      />
                      <Text
                        style={{
                          color: colors.line2Color,
                          marginTop: 5,
                          fontSize: 12,
                        }}>
                        {this.store.text.uploadreceipt}
                      </Text>
                    </View>
                  )}
              </MenuTrigger>

              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    color: 'white',
                    fontSize: 15,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                {picker.map((obj, i) => {
                  return <MenuOption value={obj.value} text={obj.label} />;
                })}
              </MenuOptions>
            </Menu>
          </View>
        </View>
      );
    }
  }

  renderCoupon2SubValue() {
    if (this.coupon2Index != null) {
      if (this.store.coupons[this.coupon2Index].percent > 0) {
        return (
          <Text>
            {'-' + this.store.coupons[this.coupon2Index].percent + '%'}
          </Text>
        );
      } else {
        return (
          <Text>
            {'-' +
              this.store.priceFormatReturn(
                parseFloat(this.store.coupons[this.coupon2Index].amount),
              )}
          </Text>
        );
      }
    }
  }

  async findThisMonthTotalAmount() {
    console.log(this.shoppingGroup)
    var index = await this.shoppingGroup.summaries.findIndex(element => element.month == moment().format('YYYYMM'))
    console.log(index)
    this.totalamount = this.shoppingGroup.summaries[index].amount
    console.log(this.totalamount)
    this.handleShoppingGroupMemberDiscount()
  }


  async handleShoppingGroupMemberDiscount() {
    var total = 0;
    await this.shoppingGroup.groupTargets.map(async (items, index) => {
      if (moment().format('YYYYMM') == items.month) {
        if (this.totalamount >= items.target) {
          total += items.memberPercentAdd
        }
      }
    })
    this.totalDiscount = total + this.shoppingGroup.shoppingGroup.memberBaseDiscountPercent
  }


  renderShoppingGroupDiscount() {
    return (
      <Text>
        {'-' + this.totalDiscount + '%'}
      </Text>
    );
  }

  async countDiscount() {
    var discountPrice = 0
    this.store.orderList.map(async (items, index) => {
      if (items.on_sale) {
        discountPrice += (items.originalPrice - items.price) * items.buyCount
        console.log(discountPrice)
      }
    })
    console.log(discountPrice)
    this.discountPrice = this.store.priceHandler(discountPrice)
  }

  renderDiscountInfo() {
    if (this.usingDiscount) {
      return (
        <View style={{ flexDirection: 'row' }}>
          <View style={{ flex: 1 }}>
            <Text>{this.store.discount.length > 0 ? this.store.discount[0].name : ''}</Text>
          </View>

          <View style={{ flex: 1, alignItems: 'flex-end' }}>
            <Text>
              {'-' + this.discountPrice}
            </Text>
          </View>
        </View>
      )
    }
  }

  // totalPrice() {
  //   var totalPrice = 0;
  //   this.normalProducts.map(async (items, index) => {
  //     console.log(items.price);
  //     totalPrice += parseFloat(items.price) * items.buyCount;
  //   });
  //   this.totalProductsPrice = totalPrice;
  //   // return this.store.priceFormatReturn(
  //   //   ((totalPrice - parseInt(this.coupon1)) * (100 - parseInt(this.coupon2))) /
  //   //     100 +
  //   //     this.shippingPrice,
  //   // );
  //   if (this.coupon2Index != null) {
  //     if (this.store.coupons[this.coupon2Index].discount_type == 'percent') {
  //       totalPrice =
  //         ((totalPrice - parseFloat(0)) *
  //           (100 - parseFloat(this.store.coupons[this.coupon2Index].amount))) /
  //         100;
  //     } else {
  //       totalPrice =
  //         totalPrice -
  //         parseFloat(0) -
  //         parseFloat(this.store.coupons[this.coupon2Index].amount);
  //     }
  //   }
  //   return this.store.priceFormatReturn(totalPrice);
  // }

  renderDiscountProduct() {
    console.log('here' + this.discountProducts);
    return this.discountProducts.map((items, index) => {
      return this.renderItems(items);
    });
  }

  renderNoDiscountTotalPrice(data) {
    var total = 0;
    data.map((items, index) => {
      //total += items.on_sale ? (items.originalPrice * this.isOrder ? items.buyCount : items.qty) : (items.price * this.isOrder ? items.buyCount : items.qty)
      if (items.on_sale) {
        if (this.isOrder) {
          total += items.originalPrice * items.buyCount
        } else {
          total += items.originalPrice * items.qty
        }
      } else {
        if (this.isOrder) {
          total += items.price * items.buyCount
        } else {
          total += items.price * items.qty
        }
      }
    })
    console.log(total)
    return (
      <View style={{ width: width - 40, alignItems: 'flex-end', marginTop: 20 }}>
        <Text>
          {this.store.text.subTotal + " " + this.store.priceFormatReturn(total)}
        </Text>
      </View>
    )
  }

  renderItems(items) {
    return (
      <View style={{ flexDirection: 'row', marginTop: 20 }}>
        <View style={{ flex: 0.5 }}>
          <Text style={{}}>{items.name}</Text>
        </View>
        <View style={{ flex: 0.2 }}>
          <Text style={{}}>
            {this.isOrder ? 'x' + items.buyCount : 'x' + items.qty}
          </Text>
        </View>
        <View style={{ flex: 0.3, alignItems: 'flex-end' }}>
          {items.hasOwnProperty('discount') || items.hasOwnProperty('on_sale') ? (<Text style={{ textDecorationLine: 'line-through', fontSize: 9 }}>
            {this.store.priceFormatReturn(
              this.isOrder
                ? items.originalPrice * items.buyCount
                : items.originalPrice * items.qty,
            )}
          </Text>) : (<View />)}
          <Text style={{ color: items.hasOwnProperty('discount') || items.hasOwnProperty('on_sale') ? 'red' : 'black' }}>
            {this.store.priceFormatReturn(
              this.isOrder
                ? items.price * items.buyCount
                : items.price * items.qty,
            )}
          </Text>
        </View>
      </View>
    );
  }

  payAction() {
    var data = {
      coupon_lines: [],
      shipping: {
        first_name: '',
        last_name: '',
        company: '',
        address_1: '',
        address_2: '',
        city: '',
        state: '',
        postcode: '',
        country: 'hong kong',
      },
      line_items: [],
    };
  }

  onlyDigits(s) {
    for (let i = s.length - 1; i >= 0; i--) {
      const d = s.charCodeAt(i);
      if (d < 48 || d > 57) return false;
    }
    return true;
  }

  usePoints(text) {
    if (this.onlyDigits(text)) {
      var numbers = parseInt(text);
      if (numbers > this.store.points) {
        this.coupon1 = '';
        this.countTotalPrice();
      } else {
        this.coupon1 = text;
        this.countTotalPrice();
      }
    } else {
      console.log('must numbers');
      this.coupon1 = '';
      this.countTotalPrice();
    }
  }

  countTotalPrice() {
    console.log(this.shippingSelection[this.shippingSelected]);
    this.totalPrice = 0;
    this.totalProductsPrice = 0;
    this.normalProducts.map((items, index) => {
      this.totalPrice += parseFloat(items.price) * items.buyCount;
      //this.totalProductsPrice += parseFloat(items.price) * items.buyCount;
      this.totalProductsPrice = _.cloneDeep(this.totalPrice);
    });
    console.log(this.totalPrice);
    // this.totalPrice += this.discountProductsTotalPriceHandler(
    //   this.discountTotalPrice,
    // );
    console.log(this.totalPrice);

    if (this.discountProductsEnable == false && this.coupon2Correct == true) {
      if (this.store.coupons[this.coupon2Index].percent > 0) {
        console.log('testing2');
        this.totalPrice =
          this.totalPrice *
          ((100 - parseFloat(this.store.coupons[this.coupon2Index].percent)) /
            100);
      } else {
        console.log('testing');
        console.log(this.totalPrice);
        console.log(this.store.coupons[this.coupon2Index].amount);
        this.totalPrice -= parseFloat(
          this.store.coupons[this.coupon2Index].amount,
        );
        console.log(this.totalPrice);
      }
    }
    if (
      this.totalProductsPrice <
      parseFloat(
        this.shippingSelection[this.shippingSelected].freeShippingPrice,
      )
    ) {
      this.freeShip = false;
      this.totalPrice += this.shippingSelection[this.shippingSelected].price;
    } else {
      this.freeShip = true;
    }

    if (this.shoppingGroup != null) {
      this.totalPrice -=
        (this.totalProductsPrice *
          this.totalDiscount /
          100)
    }

    if (parseInt(this.coupon1) != 0 || this.coupon1 != '') {
      if (parseInt(this.coupon1) / this.store.pointsMemony <= this.totalPrice) {
        this.totalPrice -= parseInt(this.coupon1) / this.store.pointsMemony;
      }
    }
    console.log(this.totalPrice);
  }

  discountProductsTotalPriceHandler(price) {
    console.log(this.store.coupons[this.coupon2Index]);
    if (this.coupon2Index != null) {
      if (
        this.store.coupons[this.coupon2Index].discount_type != undefined ||
        this.store.coupons[this.coupon2Index].discount_type != null ||
        this.coupon2Index != null
      ) {
        if (this.store.coupons[this.coupon2Index].discount_type == 'percent') {
          return (
            price *
            ((100 - parseFloat(this.store.coupons[this.coupon2Index].amount)) /
              100)
          );
        } else {
          return (
            price - parseFloat(this.store.coupons[this.coupon2Index].amount)
          );
        }
      }
    } else {
      return 0;
    }
  }
  renderShippingPrice() {
    if (this.isOrder) {
      if (this.shoppingGroup != null) {
        return this.store.text.undetermined;
      } else {
        if (!this.freeShip) {
          return this.store.priceFormatReturn(
            this.shippingSelection[this.shippingSelected].price,
          );
        } else {
          return this.store.priceFormatReturn(0);
        }
      }
    } else {
      return this.data.shippingFee
    }
  }

  countCoupon1() {
    if (this.coupon1 == '0' || this.coupon1 == '') {
      return '-HK$0.0';
    } else {
      return (
        '-' +
        this.store.priceFormatReturn(
          parseFloat(this.coupon1) / this.store.pointsMemony,
        )
      );
    }
  }

  renderAddress() {
    if (this.isOrder) {
      return (
        <View style={{ marginTop: 10, marginLeft: 20, width: width - 40 }}>
          {/* {this.shippingSelection.map((items, index) => {
        return this.renderShippingSelection(items);
      })} */}
          <Text
            style={{
              //  marginTop:10,
              marginBottom: 5,
            }}>
            {this.shoppingGroup == null
              ? this.store.text.shippingAddress
              : this.store.text.shippingAddress +
              '(' +
              this.store.text.ShoppingGroupShippingAddress +
              ')'}
          </Text>
          {this.shoppingGroup != null ? (
            <View
              style={{
                flexDirection: 'row',
                marginTop: 5,
                justifyContent: 'space-between',
              }}>
              <Text
                style={{
                  //marginLeft: 17,
                  fontSize: 12,

                  flex: 0.75,
                }}>
                {this.shoppingGroup.shoppingGroup.district.parent.name +
                  ', ' +
                  this.shoppingGroup.shoppingGroup.district.name +
                  ', ' +
                  this.shoppingGroup.shoppingGroup.addr}
              </Text>
              <View style={{ flex: 0.25 }}></View>
            </View>
          ) : (
              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 5,
                  justifyContent: 'space-between',
                }}>
                <Text
                  style={{
                    //marginLeft: 17,
                    fontSize: 12,

                    flex: 0.75,
                  }}>
                  {this.store.addresses.length > 0
                    ? this.store.addresses[0].region.name +
                    ', ' +
                    this.store.addresses[0].district.name +
                    ', ' +
                    this.store.addresses[0].addr
                    : ''}
                </Text>
                <View style={{ flex: 0.25 }}>
                  {this.isOrder ? (
                    <TouchableOpacity
                      onPress={() =>
                        this.props.navigation.navigate('AddressSetting')
                      }
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: colors.mainColor,
                        width: 60,
                        height: 15,
                        marginLeft: 8,
                        borderRadius: 5,
                      }}>
                      <Text style={{ fontSize: 10, color: 'white' }}>
                        {this.store.addresses.length > 0
                          ? this.store.text.changeAddress
                          : this.store.text.addAddress}
                      </Text>
                    </TouchableOpacity>
                  ) : (
                      <View />
                    )}
                </View>
              </View>
            )}
        </View>
      );
    } else {
      return (
        <View style={{ marginTop: 20, marginLeft: 20, width: width - 40 }}>
          <Text
            style={{
              marginBottom: 5,
            }}>
            {this.data.hasOwnProperty('shoppingGroup')
              ? this.store.text.shippingAddress +
              '(' +
              this.store.text.ShoppingGroupShippingAddress +
              ')'
              : this.store.text.shippingAddress}
          </Text>
          {this.data.hasOwnProperty('shoppingGroup') ? (
            <View
              style={{
                flexDirection: 'row',
                marginTop: 5,
                justifyContent: 'space-between',
              }}>
              <Text
                style={{
                  //marginLeft: 17,
                  fontSize: 12,

                  flex: 0.75,
                }}>
                {this.data.shipping.regionName +
                  ', ' +
                  this.data.shipping.districtName +
                  ', ' +
                  this.data.shipping.addr}
              </Text>
              <View style={{ flex: 0.25 }}></View>
            </View>
          ) : (
              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 5,
                  justifyContent: 'space-between',
                }}>
                <Text
                  style={{
                    //marginLeft: 17,
                    fontSize: 12,

                    flex: 0.75,
                  }}>
                  {this.store.addresses.length > 0
                    ? this.store.addresses[0].region.name +
                    ', ' +
                    this.store.addresses[0].district.name +
                    ', ' +
                    this.store.addresses[0].addr
                    : ''}
                </Text>
                <View style={{ flex: 0.25 }}>
                  {this.isOrder ? (
                    <TouchableOpacity
                      onPress={() =>
                        this.props.navigation.navigate('AddressSetting')
                      }
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: colors.mainColor,
                        width: 60,
                        height: 15,
                        marginLeft: 8,
                        borderRadius: 5,
                      }}>
                      <Text style={{ fontSize: 10, color: 'white' }}>
                        {this.store.addresses.length > 0
                          ? this.store.text.changeAddress
                          : this.store.text.addAddress}
                      </Text>
                    </TouchableOpacity>
                  ) : (
                      <View />
                    )}
                </View>
              </View>
            )}
        </View>
      );
    }
  }

  renderReceipt() {
    if (!this.isOrder) {

      if (this.data.status == "PRV") {
        return (
          <View style={{ marginTop: 20 }}>
            <Text
              style={{
                marginBottom: 5,
              }}>
              {this.store.text.rotp}
            </Text>
            <FastImage
              style={{
                width: 250,
                height: 250,
                marginTop: 20,

                borderWidth: 1,
                borderColor: colors.line2Color,
                justifyContent: 'center',
                alignItems: 'center',
              }}
              source={{ uri: this.data.bankReceiptURL }}
            />
          </View>
        )
      } else if (this.data.status == 'PRJ') {

        return (
          <View style={{ marginTop: 20 }}>
            <Text
              style={{
                marginBottom: 5,
              }}>
              {this.store.text.resendReceipt}
            </Text>
            {this.renderPaymeOrFps()}
            <View style={{ width: width - 40, marginTop: 30, alignItems: 'center' }}>
              <CustomLoginButon
                title={this.store.text.resendReceipt}
                onPress={() => {
                  if (this.uploadImage != null) {
                    this.store.uploadBankReceipt(this.data.id, this.uploadImage.uri, this)
                  } else {
                    this.refs.toast.show('Please upload image')
                  }
                }}
              />
            </View>

          </View>
        )
      }

    } else {

    }
  }
  pointHandler(points, which) {
    var int_part = Math.trunc(points);

    if (which) {
      return int_part
    } else {
      console.log(Number((points - int_part).toFixed(2)))
      return Number((points - int_part).toFixed(2));
    }
  }

  shippingDateStringHandler() {
    if (this.selectDateCheck) {
      return moment(this.shippingDate).format('DD/MM/YYYY')
    } else {
      return this.store.text.pleasePickTheShippingDate
    }
  }

  renderShippingMessage() {

    if (this.isOrder) {
      if (this.store.shippingMethods.content[this.store.shippingMethods.content.findIndex(e => e.id == (this.store.loginUserData.data.hasOwnProperty('shoppingGroup') ? 4 : 2))].freeShippingMinAmount > this.totalPrice) {
        return (
          <View style={{ marginTop: 10 }}>
            <Text>
              {this.store.text.shippingMessage1 +
                this.store.priceHandler(this.store.shippingMethods.content[this.store.shippingMethods.content.findIndex(e => e.id == (this.shoppingGroup != null ? 4 : 2))].freeShippingMinAmount) +
                this.store.text.shippingMessage2 +
                this.store.priceHandler(this.store.shippingMethods.content[this.store.shippingMethods.content.findIndex(e => e.id == (this.shoppingGroup != null ? 4 : 2))].fee) +
                this.store.text.shippingMessage3
              }
            </Text>
            {this.shoppingGroup != null ? (<Text style={{ marginTop: 5 }}>
              {this.store.text.groupShippingMessage1 +
                this.store.priceHandler(this.store.shippingMethods.content[this.store.shippingMethods.content.findIndex(e => e.id == (this.shoppingGroup != null ? 4 : 2))].freeShippingMinAmount) +
                this.store.text.groupShippingMessage2
              }
            </Text>) : (<View />)}
            <View style={styles.lineView} />
          </View>
        )
      }
    }
  }

  renderDatePicker() {
    if (this.isOrder) {
      return (
        <View>
          <TouchableOpacity
            style={{
              width: width - 40,
              height: 40,

              marginTop: 20,
              flexDirection: 'row',
            }}
            onPress={() => {
              this.showDatePicker = !this.showDatePicker;// this.selectDateCheck = true
            }}>
            <View style={{ flex: 0.9, justifyContent: 'center' }}>
              <Text style={{ fontWeight: '800', color: colors.mainColor }}>
                {this.store.text.shippingDate +
                  ': ' +
                  this.shippingDateStringHandler()}
              </Text>
            </View>
            <View
              style={{
                flex: 0.1,
                alignItems: 'flex-end',
                justifyContent: 'center',
              }}>
              <Icon
                name={this.showDatePicker ? 'chevron-down' : 'chevron-right'}
                size={20}
                color={colors.mainColor}
              />
            </View>
          </TouchableOpacity>
        </View>
      );
    }
  }

  renderPointsAndCouponsInput() {
    if (this.isOrder) {
      return (
        <View
          style={{
            marginTop: 40,
            width: width - 40,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <View
            style={{
              width: width - 60,
              height: 40,
              // borderWidth: 1,
              borderColor: colors.mainColor,
              justifyContent: 'center',
              borderRadius: 50,
              alignItems: 'center',
            }}>
            <View style={{ width: width - 40, flexDirection: 'row' }}>
              <View style={{ flex: 1, justifyContent: 'center' }}>
                <Text style={{ fontSize: 12, fontWeight: '800' }}>
                  {this.store.text.usePoints}
                </Text>
              </View>
              <View
                style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}>
                <Text
                  style={{
                    fontSize: 12,
                    fontWeight: '800',
                    color: colors.labelColor,
                  }}>
                  {this.store.text.yourPoints + '  ' + this.pointHandler(this.store.points, true)}
                </Text>
              </View>
            </View>

            <View style={styles.inputView}>
              <TextInput
                editable={this.store.points <= 0 ? false : true}
                keyboardType={'number-pad'}
                underlineColorAndroid="rgba(0,0,0,0)"
                style={{ marginLeft: 10, color: colors.mainColor }}
                value={this.coupon1.toString()}
                onChangeText={text => {
                  this.usePoints(text);
                }}
              />
            </View>
          </View>
          <View
            style={{
              marginTop: 20,
              width: width - 40,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <View style={{ width: width - 40, flexDirection: 'row' }}>
              <View style={{ flex: 1, justifyContent: 'center' }}>
                <Text style={{ fontSize: 12, fontWeight: '800' }}>
                  {this.store.text.coupon}
                </Text>
              </View>
              <View
                style={{
                  flex: 1,
                  justifyContent: 'center',
                  alignItems: 'flex-end',
                }}></View>
            </View>

            <View style={styles.inputView}>
              <TextInput
                underlineColorAndroid="rgba(0,0,0,0)"
                style={{ marginLeft: 10, color: colors.mainColor }}
                value={this.coupon2}
                onChangeText={text => {
                  this.coupon2OnChangeText(text);
                }}
              />
            </View>
          </View>
        </View>
      );
    }
  }

  renderItemsAndPrice() {
    if (this.isOrder) {
      return (
        <View>
          {this.normalProducts.map((items, index) => {
            return this.renderItems(items);
          })}
          {this.renderNoDiscountTotalPrice(this.normalProducts)}
          {/* <View style={styles.lineView} />
          <View style={{ flexDirection: 'row', marginTop: 10 }}>
            <View style={{ flex: 0.2 }}>
              <Text>{this.store.text.shippingPrice}</Text>
            </View>
            <View style={{ flex: 0.5 }}>
              <Text>
                {this.shoppingGroup != null
                  ? this.store.text.shoppingGroupShippingPrice
                  : ''}
              </Text>
            </View>
            <View style={{ flex: 0.3, alignItems: 'flex-end' }}>
              <Text>{this.renderShippingPrice()}</Text>
            </View>
          </View> */}
          <View style={styles.lineView} />
          <View style={{ flexDirection: 'row', marginTop: 10 }}>
            <View style={{ flex: 1 }}>
              <Text>{this.store.text.discount}</Text>
            </View>

            <View style={{ flex: 1, alignItems: 'flex-end' }}>
              <Text>{this.countCoupon1()}</Text>
            </View>
          </View>
          {this.coupon2Correct ? (
            <View>
              <View style={{ flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text>{this.store.text.coupon}</Text>
                </View>

                <View style={{ flex: 1, alignItems: 'flex-end' }}>
                  {this.renderCoupon2SubValue()}
                </View>
              </View>
              {this.discountProductsEnable ? (
                <View style={{ marginTop: 20, flex: 1 }}>
                  <Text>{this.store.text.productsThatCanUseCoupons}</Text>
                  {this.renderDiscountProduct()}
                  <View style={{ alignItems: 'flex-end' }}>
                    <Text style={{ marginTop: 10 }}>
                      <Text>
                        {this.store.text.totalNumberOfDiscountedProducts +
                          '： '}
                      </Text>
                      {this.store.priceFormatReturn(
                        this.discountProductsTotalPriceHandler(
                          this.discountTotalPrice,
                        ),
                      )}
                    </Text>
                  </View>
                </View>
              ) : (
                  <View></View>
                )}
            </View>
          ) : (
              <View />
            )}
          {this.shoppingGroup != null ? (
            <View>
              <View style={{ flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text>{this.store.text.shoppingGroupDiscount}</Text>
                </View>

                <View style={{ flex: 1, alignItems: 'flex-end' }}>
                  {this.renderShoppingGroupDiscount()}
                </View>
              </View>
            </View>
          ) : (
              <View></View>
            )}
          {this.renderDiscountInfo()}
          <View style={styles.lineView} />

          <View style={{ flexDirection: 'row', marginTop: 20 }}>
            <View style={{ flex: 1 }}>
              <Text>{' ' + this.store.text.total + ': '}</Text>
            </View>
            <View style={{ flex: 1, alignItems: 'flex-end' }}>
              <Text style={{ fontWeight: '800', fontSize: 15 }}>
                {this.store.priceFormatReturn(this.totalPrice)}
              </Text>
            </View>
          </View>
        </View>
      );
    } else {
      return (
        <View>
          {this.data.items.map((items, index) => {
            return this.renderItems(items);
          })}
          {this.renderNoDiscountTotalPrice(this.data.items)}
          {/* <View style={styles.lineView} />
          <View style={{ flexDirection: 'row', marginTop: 10 }}>
            <View style={{ flex: 0.2 }}>
              <Text>{this.store.text.shippingPrice}</Text>
            </View>
            <View style={{ flex: 0.5 }}>
              <Text>
                {this.shoppingGroup != null
                  ? this.store.text.shoppingGroupShippingPrice
                  : ''}
              </Text>
            </View>
            <View style={{ flex: 0.3, alignItems: 'flex-end' }}>
              <Text>{this.renderShippingPrice()}</Text>
            </View>
          </View> */}
          <View style={styles.lineView} />
          <View style={{ flexDirection: 'row', marginTop: 10 }}>
            <View style={{ flex: 1 }}>
              <Text>{this.store.text.pointsDiscount}</Text>
            </View>

            <View style={{ flex: 1, alignItems: 'flex-end' }}>
              <Text>
                {'-' +
                  this.store.priceFormatReturn(
                    parseFloat(this.data.pointsDiscount),
                  )}
              </Text>
            </View>
          </View>

          {this.data.hasOwnProperty('couponDiscount') ? (<View>
            <View style={{ flexDirection: 'row' }}>
              <View style={{ flex: 1 }}>
                <Text>{this.store.text.couponDiscount}</Text>
              </View>

              <View style={{ flex: 1, alignItems: 'flex-end' }}>
                <Text>
                  {'-' +
                    this.store.priceFormatReturn(
                      parseFloat(this.data.couponDiscount),
                    )}
                </Text>
              </View>
            </View>
          </View>) : (<View />)}


          {this.data.hasOwnProperty('shoppingGroup') ? (
            <View>
              <View style={{ flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text>{this.store.text.shoppingGroupDiscount}</Text>
                </View>

                <View style={{ flex: 1, alignItems: 'flex-end' }}>
                  <Text>
                    {'-' +
                      this.store.priceFormatReturn(
                        this.data.shoppingGroupDiscount,
                      )}
                  </Text>
                </View>
              </View>
            </View>
          ) : (
              <View></View>
            )}
          {this.discountTitle !== '' ? (<View>
            <View style={{ flexDirection: 'row' }}>
              <View style={{ flex: 1 }}>
                <Text>{this.discountTitle}</Text>
              </View>

              <View style={{ flex: 1, alignItems: 'flex-end' }}>
                <Text>
                  {'-' +
                    this.store.priceFormatReturn(
                      this.discountTotalPrice,
                    )}
                </Text>
              </View>
            </View>
          </View>) : (<View></View>)}

          {/* here */}
          <View style={styles.lineView} />

          <View style={{ flexDirection: 'row', marginTop: 20 }}>
            <View style={{ flex: 1 }}>
              <Text>{' ' + this.store.text.total + ': '}</Text>
            </View>
            <View style={{ flex: 1, alignItems: 'flex-end' }}>
              <Text style={{ fontWeight: '800', fontSize: 15 }}>
                {this.store.priceFormatReturn(this.data.amount)}
              </Text>
            </View>
          </View>
        </View>
      );
    }
  }

  renderOrderHistoryDetails() {
    if (!this.isOrder) {
      return (
        <View style={{ marginTop: 20 }}>
          <Text style={{}}>
            {this.store.text.orderNumber + ': ' + this.data.receiptId}
          </Text>
          <Text style={{ marginTop: 5 }}>
            {this.store.text.orderDate +
              ': ' +
              moment(this.data.created).format('DD-MM-YYYY hh:mm')}
          </Text>
          <Text style={{ marginTop: 5 }}>
            {this.store.text.cutoffDate +
              ': ' +
              moment(this.data.cutoffDate).format('DD-MM-YYYY hh:mm')}
          </Text>
          <Text style={{ marginTop: 5 }}>
            {this.store.text.shippingDate +
              ': ' +
              moment(this.data.deliveryDate).format('DD-MM-YYYY hh:mm')}
          </Text>
          <Text style={{ marginTop: 5 }}>
            {this.store.text.paymentDieline +
              ': ' +
              moment(this.data.paymentDeadline).format('DD-MM-YYYY hh:mm')}
          </Text>
          <View style={{ marginTop: 5, flexDirection: "row", alignItems: 'center', }}>
            <Text >
              {this.store.text.orderStatus +
                ': ' +
                this.statusHandler(this.data.status)}
            </Text>

            {this.renderCancelOrder()}

          </View>

        </View>
      );
    }
  }

  renderCancelOrder() {
    if (!this.isOrder) {
      if (this.data.status == 'PC' || this.data.status == 'PP' || this.data.status == 'PA' || this.data.status == 'PRV' || this.data.status == 'PRJ') {
        return (
          <TouchableOpacity style={{ marginLeft: 10 }}
            onPress={() => { this.cancelOrderAction() }}>
            <Text style={{ color: colors.mainColor }}>
              {this.store.text.requestToCancelOrder}
            </Text>
          </TouchableOpacity>
        )
      }
    }
  }

  cancelOrderAction() {
    if (this.data.status == "PA") {
      // Alert.prompt(
      //   this.store.text.requestToCancelOrder,
      //   this.store.text.cancelOrderReason,
      //   [
      //     {
      //       text: this.store.text.cancel,
      //       onPress: () => console.log("Cancel Pressed"),
      //       style: "cancel"
      //     },
      //     {
      //       text: this.store.text.requestToCancelOrder,
      //       onPress: text => { this.sendTheCancelRequest(text, true) }
      //     }
      //   ],

      // );
      this.cancelOrderVisable = true
    } else {
      // Alert.prompt(
      //   this.store.text.requestToCancelOrder,
      //   this.store.text.cancelOrderReason,
      //   [
      //     {
      //       text: this.store.text.cancel,
      //       onPress: () => console.log("Cancel Pressed"),
      //       style: "cancel"
      //     },
      //     {
      //       text: this.store.text.requestToCancelOrder,
      //       onPress: text => { this.sendTheCancelRequest(text, false) }
      //     }
      //   ],

      // );
      this.cancelOrderVisable = true
    }

  }

  sendTheCancelRequest(reason, which) {
    if (reason.length == 0) {
      this.refs.toast.show(this.store.text.pleaseInputReason)
    } else {
      if (which) {
        this.store.cancelOrderRequest(this.data.id, reason, this)
      } else {
        this.store.cancelOrderRequestWithNotPay(this.data.id, this)
      }
    }
  }

  renderPaymentMethod() {
    if (!this.props.route.params.order) {
      if (this.data.status == 'PP') {
        return (
          <View>
            <View style={{ marginTop: 20, marginLeft: 20 }}>
              <Text
                style={{
                  marginBottom: 10,
                }}>
                {this.store.text.paymentMethods}
              </Text>
              {this.paymentseletion.map((items, index) => {
                if (!this.store.loginUserData.data.hasOwnProperty('shoppingGroup') && items.value == 1) {
                  return
                } else {
                  return this.renderPaymentSelection(items);
                }

              })}
            </View>
            {this.renderPaymeOrFps()}
          </View>
        );
      }
    }
  }



  renderOrderButton() {
    if (this.props.route.params.order) {
      return (
        <CustomLoginButon
          title={this.store.text.confirmOrder}
          onPress={() => {
            this.orderAction();
          }}
        />
      );
    } else {
      if (this.data.status == 'PP') {
        return (
          <CustomLoginButon
            title={this.store.text.confirmPayment}
            onPress={() => {
              this.orderAction();
            }}
          />
        );
      }
    }
  }

  render() {
    return (
      <MenuProvider
        style={{
          flex: 1,
          backgroundColor: colors.bgc,
        }}>
        <Loading loading={this.store.loading} />
        <CheckAnimate
          visible={this.store.animateStatus.show}
          progress={this.store.animateStatus.progress}
        />
        <TitleBar
          showBack={true}
          title={this.store.text.paymentDetails}
          self={this}
        />


        <KeyboardAwareScrollView>
          <View style={{ marginRight: 20, marginLeft: 20, flex: 1 }}>
            <View
              style={{
                width: width,

                justifyContent: 'center',
              }}>
              {this.renderOrderHistoryDetails()}
              <Text style={{ marginTop: 20 }}>{this.store.text.products}</Text>
            </View>
            {this.renderItemsAndPrice()}
            {this.renderPointsAndCouponsInput()}
            {this.renderDatePicker()}

            {this.renderAddress()}
            {this.renderPaymentMethod()}
            <View style={styles.lineView} />
            {this.renderShippingMessage()}
            {this.renderReceipt()}
            <View
              style={{
                width: width - 40,
                alignItems: 'center',
                marginBottom: 40,
              }}>
              {this.renderOrderButton()}
            </View>
          </View>
          <Modal isVisible={this.showDatePicker}
            deviceWidth={width}
            deviceHeight={height}>
            <View style={{ height: height * 0.3, backgroundColor: 'white', borderRadius: 20, alignItems: 'center' }}>
              <DatePicker
                date={this.shippingDate}
                onDateChange={date => {
                  this.changeDate(date);
                }}
                mode={'date'}
                locale={'zh_HK'}
                minimumDate={this.minOrderDateHandler()}
                maximumDate={this.maxOrderDateHandler()}
              />
              <TouchableOpacity style={{ position: 'absolute', bottom: 0, justifyContent: 'center', alignItems: 'center', width: width - 40, height: 50, backgroundColor: colors.mainColor, borderBottomRightRadius: 20, borderBottomLeftRadius: 20, }}
                onPress={() => { this.showDatePicker = false; this.selectDateCheck = true }}>
                <Text style={{ fontSize: 17, color: 'white' }}>
                  {this.store.text.sure}
                </Text>
              </TouchableOpacity>
            </View>
          </Modal>
          <Modal isVisible={this.cancelOrderVisable}
            deviceWidth={width}
            deviceHeight={height}>
            <View style={{ height: height * 0.3, backgroundColor: 'white', borderRadius: 20, alignItems: 'center' }}>

              <Text style={{ fontSize: 20, color: colors.mainColor, fontWeight: '800', marginTop: 30 }}>
                {this.store.text.cancelOrderReason}
              </Text>
              <HoshiTextInput
                placeholder={this.store.text.reason}
                value={this.cancelOrderReason}

                onChangeText={text => {
                  this.cancelOrderReason = text;
                }}

              />
              <View style={{ flexDirection: 'row', position: 'absolute', bottom: 0 }}>
                <TouchableOpacity style={{ width: width / 2 - 20, height: 40, borderBottomLeftRadius: 20, backgroundColor: 'gray', justifyContent: 'center', alignItems: 'center' }}
                  onPress={() => { this.cancelOrderReason = ''; this.cancelOrderVisable = false }}>
                  <Text style={{ color: 'white' }}>
                    {this.store.text.cancel}
                  </Text>

                </TouchableOpacity>
                <TouchableOpacity style={{ width: width / 2 - 20, height: 40, borderBottomRightRadius: 20, backgroundColor: colors.mainColor, justifyContent: 'center', alignItems: 'center' }}
                  onPress={() => {
                    if (this.data.status == "PA") {
                      this.sendTheCancelRequest(this.cancelOrderReason, true)

                    } else {
                      this.sendTheCancelRequest(this.cancelOrderReason, false)

                    }

                    this.cancelOrderReason = '';
                    this.cancelOrderVisable = false;
                  }}>
                  <Text style={{ color: 'white' }}>
                    {this.store.text.sure}
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          </Modal>
        </KeyboardAwareScrollView>
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="center"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </MenuProvider>
    );
  }
}
const styles = StyleSheet.flatten({
  lineView: {
    height: 1,
    width: width - 40,
    backgroundColor: colors.line2Color,
    marginTop: 10,
  },
  label: {
    color: colors.labelColor,
  },
  inputView: {
    marginTop: 10,
    width: width - 40,
    height: 40,
    borderRadius: 10,
    justifyContent: 'center',
    shadowColor: '#000',
    backgroundColor: 'white',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,

    elevation: 2,
  },
});
