import { inject, observer } from "mobx-react"
import { makeAutoObservable, action, observable, transaction, runInAction } from "mobx";
import AsyncStorage from '@react-native-community/async-storage';
import axios from 'axios';
import { Alert, Platform, Animated, Easing, Linking, View, Image } from 'react-native';
import base64 from 'react-native-base64';
import BackgroundTimer from '../components/backgroundTimer';
import api from '../services/api';
import moment from 'moment';
const qs = require('qs');
var _ = require('lodash');
import uuid from 'react-native-uuid';
var underscore = require('underscore');
import { images } from '../assets/images/imageIndex'
import messaging from '@react-native-firebase/messaging';
import { Notifier, NotifierComponents } from 'react-native-notifier';
import appVersion from "../../appVersion";
class Stores {
  routerRef;

  animateStatus = {
    progress: new Animated.Value(0),
    show: false,
  };
  networkConnection = true
  storeInfo = [];
  about = '';
  privacyPolicy = '';
  loyaltyProgramTerms = '';
  token = '';
  uuid = '';
  addedCard = false;
  paymentMethod = [];
  searchHistory = [];
  routerState;
  userData = {};
  regions = [];
  addresses = [];
  currentScene = 'Main';
  splash = false;
  logined = false;
  groupBuyList = [];
  loginUserData = null;
  saleProduct = [];
  allProducts = [];
  topSale = [];
  categories = [];
  mainCategories = [];
  allCategories = [];
  categoriesForSearch = [];
  youMayLikeList = [];
  tagForSearch = [];
  favorite = [];
  favoriteIds = [];
  shoppingCartList = [];
  shoppingCartIds = [];
  orderList = [];
  banners = [];
  topBanners = [];
  bottomBanners = [];
  coupons = [];
  shippingMethods = [];
  searchResult = [];
  loading = false;
  creditCardinfo = null;
  timer = 10;
  //text = language.hk;
  languageSelection = 'hk';
  points = 0;
  pointsMemony = 0;
  news = []
  recommendProducts = []
  constructor(rootStore) {
    makeAutoObservable(this, {
      storeInfo: observable,
      about: observable,
      privacyPolicy: observable,
      loyaltyProgramTerms: observable,
      animateStatus: observable,
      token: observable,
      uuid: observable,
      addedCard: observable,
      paymentMethod: observable,
      searchHistory: observable,
      routerState: observable,
      userData: observable,
      regions: observable,
      addresses: observable,
      currentScene: observable,
      splash: observable,
      logined: observable,
      groupBuyList: observable,
      loginUserData: observable,
      saleProduct: observable,
      allProducts: observable,
      topSale: observable,
      categories: observable,
      mainCategories: observable,
      allCategories: observable,
      categoriesForSearch: observable,
      youMayLikeList: observable,
      tagForSearch: observable,
      favorite: observable,
      favoriteIds: observable,
      shoppingCartList: observable,
      shoppingCartIds: observable,
      orderList: observable,
      banners: observable,
      topBanners: observable,
      bottomBanners: observable,
      coupons: observable,
      shippingMethods: observable,
      searchResult: observable,
      loading: observable,
      creditCardinfo: observable,
      timer: observable,
      // text: observable,
      languageSelection: observable,
      points: observable,
      pointsMemony: observable,
      news: observable,
      recommendProducts: observable,
      loadingHandler: action,
    })
  }


  setCurrentScene = () => {
    let routeName = this.currentRoute;
    if (routeName) {
      this.currentScene = routeName;
    }
  };

  networkConnect(data) {
    console.log(data.isConnected)
    if (data.isConnected != this.networkConnect) {
      if (data.isConnected == false) {
        Notifier.showNotification({
          title: 'The request was failed',
          description: 'Check your internet connection, please',
          Component: NotifierComponents.Alert,
          componentProps: {
            alertType: 'error',
          },
        });
      }
    }
    this.networkConnection = data.isConnected
  }


  timeout(ms, promise) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('timeout'));
      }, ms);
      promise.then(resolve, reject);
    });
  }

  setRouterRef = ref => {
    this.routerRef = ref;
  };

  priceHandler(price) {
    var priceInt = parseFloat(price).toFixed(2);
    return '$' + priceInt.toString();
  }

  setRouterState = state => {
    this.routerState = state;
  };


  // changeLanguage(lang) {
  //   console.log(lang);
  //   if (lang == 'en') {
  //     console.log(lang);
  //     this.text = language.en;
  //     this.languageSelection = 'en';
  //   } else {
  //     console.log(lang);
  //     this.text = language.hk;
  //     this.languageSelection = 'hk';
  //   }
  // }

  navigate = routeName => {
    this.routerRef.navigate(routeName);
  };

  loadingHandler(loading) {
    runInAction(() => {
      this.loading = loading
    });
  }

  currentRoute() {
    if (this.routerState) {
      return this.routerState.routeNames[this.routerState.index];
    } else {
      return null;
    }
  }


  async getStoreInfo(self) {
    this.storeInfo = []
    var url = api.shopinfo;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      this.storeInfo = response.data

      self.setRegion({ latitude: parseFloat(this.storeInfo[0].lat), longitude: parseFloat(this.storeInfo[0].lng), latitudeDelta: 0.0922, longitudeDelta: 0.0421, })
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }

  async getAbout() {
    this.about = '';
    var url = api.about;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      this.about = response.data.content

    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getPivacyPolicy() {
    this.privacyPolicy = '';
    var url = api.privacyPolicy;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      this.privacyPolicy = response.data.content

    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }

  async getLoyaltyProgramTerms() {
    this.loyaltyProgramTerms = '';
    var url = api.loyaltyProgramTerms;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      this.loyaltyProgramTerms = response.data.content

    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }

  async getAppVersion() {
    this.loadingHandler(true);
    var url = api.getVersion;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          //  Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);

      console.log(response);
      console.log(appVersion)
      if (response.data.content === appVersion) {
        // Alert.alert(
        //   'Alert Title',
        //  'test',
        //   [

        //     { text: 'OK', onPress: () => console.log('OK Pressed') },
        //   ],
        //   { cancelable: false },
        // );
        return 'match'

      } else {
        return 'not match'
      }


    } catch (error) {
      this.loadingHandler(false);
      return 'fail'
      console.log(error);
    }
  }



  async uploadBankReceipt(orderId, imageLink, self) {
    this.loadingHandler(true);
    var uploadURL = api.order + orderId + '/upload-banking-receipt';
    const date = moment().format('DDMMYYYYssmmhh');
    const fileData = new FormData();
    fileData.append('file', {
      uri: imageLink,
      name: 'bank' + date + '.png',
      type: 'image/png',
    });
    try {
      const uploadImageResponse = await axios.post(uploadURL, fileData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
        timeout: 5000,
      })
      this.loadingHandler(false);
      console.log(uploadImageResponse);
      this.startAnimate();
      setTimeout(function () {
        self.payDisable = false;
        self.props.navigation.navigate('BuyHistory');
      }, 1000);
    } catch (error) {
      this.loadingHandler(false);
      console.log(error.response)
    }

  }


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


  priceFormatReturn(price) {
    var floatPrice = parseFloat(price);
    return 'HK$' + floatPrice.toFixed(1);
  }


  async getShoppingCart() {
    console.log(this.token);
    this.loadingHandler(true);
    var url = api.shoppingCart;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);

      console.log(response);
      this.shoppingCartIds = response.data;
      // await response.data.map((items, index) => {
      //   items.selected = false;
      //   items.buyCount = 1;
      //   this.favorite.push(items);
      // });
      if (response.data.length > 0) {
        var ids = '';
        await response.data.map((items, index) => {
          ids += items.product_id;
          if (index + 1 < response.data.length) {
            ids += ',';
          }
        });

        this.getProductById(true);
      }
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getPaymentMethods() {

    var url = api.payment_methods;

    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
        timeout: 5000,
      });


      console.log(response);
      this.paymentMethod = response.data

    } catch (e) {
      //self.refs.toast.show('Login Fail');
      this.loadingHandler(false);

    }
  }


  async modifyShoppingCart(index, self, itemsQty) {
    console.log(this.shoppingCartList[index]);
    console.log(
      this.shoppingCartIds[
      this.shoppingCartIds.findIndex(
        element => element.product_id === this.shoppingCartList[index].id,
      )
      ],
    );

    var oldQty = this.shoppingCartIds[
      this.shoppingCartIds.findIndex(
        element => element.product_id === this.shoppingCartList[index].id,
      )
    ].qty;

    this.shoppingCartIds[
      this.shoppingCartIds.findIndex(
        element => element.product_id === this.shoppingCartList[index].id,
      )
    ].qty = parseInt(itemsQty);
    console.log(
      this.shoppingCartIds[
        this.shoppingCartIds.findIndex(
          element => element.product_id === this.shoppingCartList[index].id,
        )
      ].qty,
    );

    this.loadingHandler(true);
    var url = api.shoppingCart;
    try {
      const response = await axios.put(url, this.shoppingCartIds, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      self.refs.toast.show('已更改數量');
      this.shoppingCartList[index].buyCount = itemsQty;
    } catch (error) {
      this.loadingHandler(false);
      self.refs.toast.show('更改數量失敗');
      this.shoppingCartIds[
        this.shoppingCartIds.findIndex(
          element => element.product_id === this.shoppingCartList[index].id,
        )
      ].qty = oldQty;
      Alert.alert(
        'Alert Title',
        JSON.stringify(error.message),
        [
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          { text: 'OK', onPress: () => console.log('OK Pressed') },
        ],
        { cancelable: false },
      );
      console.log(error.response);
    }
  }


  async addSingleItemToShoppingCart(items, self) {
    if (this.logined) {
      if (items.stock_quantity > 0) {
        var itemIndex = await this.shoppingCartList.findIndex(
          element => element.id === items.id,
        );
        var shoppcartIdIndex = await this.shoppingCartIds.findIndex(
          element => element.product_id === items.id,
        );

        if (items.stock_quantity > 0) { }

        if (itemIndex != -1) {
          this.shoppingCartList[itemIndex].buyCount =
            parseInt(items.buyCount) +
            parseInt(this.shoppingCartList[itemIndex].buyCount);
        } else {
          this.shoppingCartList.push(items);
        }
        if (shoppcartIdIndex != -1) {
          this.shoppingCartIds[itemIndex].qty =
            parseInt(items.buyCount) +
            parseInt(this.shoppingCartIds[shoppcartIdIndex].qty);
        } else {
          var data = {
            product_id: items.id,
            qty: items.buyCount,
          };
          this.shoppingCartIds.push(data);
        }
        this.addShoppingCart(self);
      } else {
        Alert.alert(
          this.text.outOfStock,
          this.text.outOfStock,
          [
            {
              text: 'OK',
              onPress: () => console.log('Cancel Pressed'),
              style: 'cancel',
            },
            // { text: this.text.login, onPress: () => self.props.navigation.navigate('Signin') },
          ],
          { cancelable: false },
        );
      }
    } else {
      Alert.alert(
        this.text.pleaseLogin,
        this.text.pleaseLogin,
        [
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          { text: this.text.login, onPress: () => self.props.navigation.navigate('Signin') },
        ],
        { cancelable: false },
      );
    }
  }


  async addShoppingCart(self) {
    this.loadingHandler(true);
    var url = api.shoppingCart;
    try {
      const response = await axios.put(url, this.shoppingCartIds, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      self.refs.toast.show('已加入購物車');
    } catch (error) {
      this.loadingHandler(false);
      self.refs.toast.show('加入失敗');
      Alert.alert(
        'Alert Title',
        JSON.stringify(error.message),
        [
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          { text: 'OK', onPress: () => console.log('OK Pressed') },
        ],
        { cancelable: false },
      );
      console.log(error.response);
    }
  }


  async getCategories() {
    this.loadingHandler(true);
    this.categories = [];
    this.allCategories = [];
    this.mainCategories = [];
    var categories = [];
    var url = api.getcategories;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
        params: { page: 1, per_page: 100 },
      });
      console.log(response);
      this.loadingHandler(false);
      this.splash = true;
      this.allCategories = response.data;
      response.data.map((items, index) => {
        if (items.parent === '') {
          items.subCat = [];
          categories.push(items);
        }
      });
      response.data.map((items, index) => {
        if (items.parent !== '') {
          const parentIndex = categories.findIndex(
            element => element.id == items.parent,
          );
          if (parentIndex !== -1) {
            categories[parentIndex].subCat.push(items);
          }
        }
      });
      console.log(categories);
      this.mainCategories = categories;
      transaction(() => {
        var count = 0;
        var matrix = [];
        categories.map((items, index) => {
          if (items.name !== 'none') {
            var data = {
              id: items.id,
              name: items.name,
            };
            this.categoriesForSearch.push(data);
            count += 1;
            matrix.push(items);
            if (count % 4 == 0) {
              this.categories.push(matrix);
              matrix = [];
              console.log(matrix);
            }
          }
        });
        if (matrix.length > 0) {
          this.categories.push(matrix);
          matrix = [];
        }
      });
      //this.allProducts = response.data;
      //  self.props.navigation.navigate('BottomTabScreen');
      this.getRecommendProducts();
      this.getbanners();
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getTags(tagpage) {
    var url = api.tag;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: tagpage, per_page: 100 },
        timeout: 5000,
      });
      console.log(response);
      response.data.map((items, index) => {
        var data = {
          id: items.id,
          name: items.name,
        };
        this.tagForSearch.push(data);
      });
      return response.data.length;
    } catch (error) {
      console.log(error);
      return 0;
    }
  }

  async getAllTag() {
    var page = 1;
    this.tagForSearch = [];

    while ((await this.getTags(page)) == 100) {
      page += 1;
    }
    console.log(this.tagForSearch);
  }

  async searchByCategories(value) {
    // var index = await this.categoriesForSearch.findIndex(
    //   element => element.name == value,
    // );
    var searchindex = [];
    await this.categoriesForSearch.forEach((items, index) => {
      console.log(items.name);
      var charindex = items.name.indexOf(value);
      if (charindex != -1) {
        searchindex.push(items.id);
      }
    });
    if (searchindex.length > 0) {
      this.searchItems(searchindex, 0);
    } else {
      console.log('No');
    }
  }

  async searchByTag(value) {
    var searchindex = [];
    await this.tagForSearch.forEach((items, index) => {
      console.log(items.name);
      var charindex = items.name.indexOf(value);
      if (charindex != -1) {
        searchindex.push(items.id);
      }
    });
    if (searchindex.length > 0) {
      this.searchItems(searchindex, 1);
    } else {
      console.log('No');
    }
  }


  async searchProductsAction(value) {
    this.searchResult = [];
    // await this.searchByCategories(value);
    //  await this.searchByTag(value);
    //await this.searchItems(value, 2);
    this.searchProducts(value);
    var searchIndex = await this.searchHistory.findIndex(
      element => element === value,
    );
    if (searchIndex === -1) {
      this.searchHistory.push(value);
      this.saveDataToLocal('searchHistory', _.cloneDeep(this.searchHistory));
    }
  }


  async deleteShoppingCartItem(deleteIndex, idsIndex, self) {
    const indexSet = new Set(deleteIndex);
    const idsIndexSet = new Set(idsIndex);
    const deletedShoppingcartList = this.shoppingCartList.filter(
      (value, i) => !indexSet.has(i),
    );
    const delectShoppingCartIds = this.shoppingCartIds.filter(
      (value, i) => !idsIndexSet.has(i),
    );
    console.log(deletedShoppingcartList);
    console.log(this.shoppingCartList);
    console.log(delectShoppingCartIds);
    console.log(this.shoppingCartIds);

    this.loadingHandler(true);
    var url = api.shoppingCart;
    try {
      const response = await axios.put(url, delectShoppingCartIds, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      self.refs.toast.show('刪除成功');
      this.shoppingCartIds = delectShoppingCartIds;
      this.shoppingCartList = deletedShoppingcartList;
      self.deleteAble = false;
    } catch (error) {
      this.loadingHandler(false);
      self.refs.toast.show('刪除失敗');

      console.log(error.response);
    }
  }


  async deleteAllShoppingCartItem() {
    this.shoppingCartList = [];
    this.shoppingCartIds = [];

    this.loadingHandler(true);
    var url = api.shoppingCart;
    try {
      const response = await axios.put(url, this.shoppingCartIds, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
    } catch (error) {
      this.loadingHandler(false);

      console.log(error.response);
    }
  }


  async getPoints() {
    this.loadingHandler(true);

    var url = api.editAddress;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      this.points = parseInt(response.data.points);
      this.getPointsSetting();
      // this.pointsMemony = parseInt(
      //   response.data.points_settings.es_point_2_amount,
      // );
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getPointsSetting() {
    this.loadingHandler(true);

    var url = api.points;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);

      this.pointsMemony = parseInt(response.data.point_2_amount);
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async checkVersion() {
    this.loadingHandler(true);
    console.log(this.token);
    var url = api.checkVersion;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      return response.data.app;

      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
      return '0.0';
    }
  }


  async getCreditCard() {
    this.loadingHandler(true);
    console.log(this.token);
    var url = api.creditCard;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      if (response.data.length > 0) {
        this.creditCardinfo = response.data[0];
      }
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async deleCreditCard(self) {
    this.loadingHandler(true);
    console.log();
    var requestURL = api.creditCard + this.creditCardinfo.id;
    try {
      const response = await axios.delete(requestURL, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.creditCardinfo = null;
      this.loadingHandler(false);
      this.addedCard = false;
      console.log(response);
    } catch (e) {
      this.loadingHandler(false);
      console.log(e);
    }
  }


  async postCreditCard(self, data) {
    console.log(data);
    this.loadingHandler(true);
    var requestURL = api.creditCard;

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      transaction(() => {
        this.creditCardinfo = response.data;
        this.loadingHandler(false);
        this.addedCard = true;
      });
      console.log(response);
      self.addCard = false;
      self.cardData = null;
      //navigation.goBack();
      // self.navigatieAction("menu");
    } catch (e) {
      this.loadingHandler(false);
      console.log(e.response);
      //  self.refs.toast.show(e.message);
    }
  }


  async addToFavorite(item, self) {
    let dataIndex = await this.favorite.findIndex(
      element => element.id === item.id,
    );
    if (dataIndex === -1) {
      self.refs.toast.show('己加入我的清單');
      this.favorite.push(item);
    } else {
      self.refs.toast.show('此産品己在我的清單');
    }
  }


  httpsHandler(link) {
    return link.substr(0, 4) + link.substring(5);
  }


  async getProductById(which) {
    this.loadingHandler(true);
    var url = api.getAllProducts;
    var ids = [];
    if (which) {
      this.shoppingCartList = [];
      await this.shoppingCartIds.map((items, index) => {
        ids.push(items.product_id);
      });
    } else {
      this.favorite = [];
      await this.favoriteIds.map((items, index) => {
        ids.push(items.product_id);
      });
    }
    console.log(ids);
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { 'id[]': ids },
        paramsSerializer: function (params) {
          return qs.stringify(params, { arrayFormat: 'repeat' });
        },
        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      transaction(async () => {
        if (which) {
          await response.data.map(async (items, index) => {
            items.buyCount = this.shoppingCartIds[
              await this.shoppingCartIds.findIndex(
                element => element.product_id === items.id,
              )
            ].qty;
            items.selected = false;
            this.shoppingCartList.push(items);
          });
        } else {
          await response.data.map(async (items, index) => {
            items.buyCount = 1;
            items.selected = false;
            this.favorite.push(items);
          });
        }
      });
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getFavourite() {
    this.loadingHandler(true);
    var url = api.favourite;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);

      console.log(response.data);

      if (response.data.length > 0) {
        this.favoriteIds = response.data;
        this.getProductById(false);
      }
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async deleteFavourite(deleteIndex, idsIndex, deleteId, self) {
    console.log(deleteIndex);
    console.log(deleteId);
    this.loadingHandler(true);
    var url = api.favourite;
    try {
      const response = await axios.delete(url, {
        data: deleteId,
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      self.refs.toast.show('刪除成功');
      const indexSet = new Set(deleteIndex);
      const idsIndexSet = new Set(idsIndex);
      this.favorite = this.favorite.filter((value, i) => !indexSet.has(i));
      this.favoriteIds = this.favoriteIds.filter(
        (value, i) => !idsIndexSet.has(i),
      );
      self.deleteAble = false;
    } catch (error) {
      this.loadingHandler(false);
      self.refs.toast.show('刪除失敗');
      console.log(error);
    }
  }

  async addFavouritePost(data, self) {
    var uploadData = {
      product_id: '' + data.id,
    };
    console.log(uploadData);
    this.loadingHandler(true);
    var url = api.favourite;
    try {
      const response = await axios.post(url, uploadData, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      self.refs.toast.show('已加入我的清單');
      var newData = _.cloneDeep(data);
      newData.selected = false;
      newData.buyCount = 1;
      this.favorite.push(newData);
      this.favoriteIds.push({ product_id: '' + data.id });
      console.log(response);
    } catch (error) {
      this.loadingHandler(false);
      self.refs.toast.show('加入失敗');
      console.log(error.response);
    }
  }


  getTopSale(items) {
    // var topSaleList = underscore
    //   .sortBy(this.allProducts, 'total_sales')
    //   .reverse();
    // for (var i = 0; i < 3; i++) {
    //   this.topSale.push(topSaleList[i]);
    // }
    // console.log(topSaleList);
    // // this.allProducts.map((items, index) => {
    // //   this.topSale.push(_.cloneDeep(items));
    // // });

    var index = items.attributes.findIndex(element => element.name == 'top');
    if (index != -1) {
      items.top = items.attributes[index].options;
      console.log(items.top);
      this.topSale.push(_.cloneDeep(items));
    }
  }

  getRandomItem(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
  }



  async getRecommendProducts() {
    this.recommendProducts = []
    var url = api.recommend;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page_no: 1, per_page: 150 },
        timeout: 20000,
      });
      console.log(response);
      response.data.map((items, index) => {
        items.sweetIcon = this.sweetIconHandler(items.sweet);
        this.recommendProducts.push(items);
      });
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }

  sweetIconHandler(sweet) {
    var sweetIcon = [[], []]
    if (sweet >= 3) {
      for (var i = 0; i < 2; i++) {
        sweetIcon[0].push(<Image source={images.sweet} />)
      }
      for (var i = 0; i < sweet - 2; i++) {
        sweetIcon[1].push(<Image source={images.sweet} />)
      }
    } else if (sweet <= 2) {
      for (var i = 0; i < sweet; i++) {
        sweetIcon[0].push(<Image source={images.sweet} />)
      }
    }
    return sweetIcon
  }

  startTimer(data, self) {
    if (this.timer == 10) {
      this.sendsmsVerify(data, self)
      const timer = BackgroundTimer.setInterval(() => {
        if (this.timer == 0) {
          BackgroundTimer.clearInterval(timer)
        } else {
          this.timer -= 1
        }
        console.log(this.timer)
      }, 1000);
    }
  }



  async getcategoriesProducts(categoryID, self) {
    this.allProducts = []
    this.loadingHandler(true);
    console.log(categoryID);
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { category: categoryID },
        timeout: 20000,
      });
      console.log(response);
      this.loadingHandler(false);

      response.data.map((items, index) => {
        items.sweetIcon = this.sweetIconHandler(items.sweet);
        this.allProducts.push(items);
      });
      // var newArray = [...this.allProducts];
      // self.productItems = newArray.sort((a, b) =>
      //   a.price > b.price ? 1 : b.price > a.price ? -1 : 0,
      // );
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getProducts(page) {
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: page, per_page: 100 },
        timeout: 20000,
      });
      console.log(response);
      response.data.map((items, index) => {
        if (items.purchasable) {
          this.allProducts.push(items);
          this.getGroupBuyItems(items);
          this.getTopSale(items);
          if (items.on_sale) {
            if (
              items.date_on_sale_from != null &&
              items.date_on_sale_to != null
            ) {
              let today = moment();
              let dateOnSale = moment(items.date_on_sale_to);
              console.log(dateOnSale.month());
              if (dateOnSale.unix() > today.unix()) {
                //console.log(dateOnSale.unix() - today.unix());
                items.unix = dateOnSale.unix() - today.unix();
                this.saleProduct.push(items);
                console.log('time sale:' + items.name);
              }
            }
          }
        }
      });

      return response.data.length;
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
      return 0;
    }
  }


  getGroupBuyItems(items) {
    var index = items.attributes.findIndex(
      element => element.name == 'groupbuy',
    );
    if (index != -1) {
      this.groupBuyList.push(_.cloneDeep(items));
    }
    console.log(this.groupBuyList);
  }


  async getAllProductFromStart(self) {
    this.groupBuyList = [];
    this.saleProduct = [];
    this.topSale = [];
    this.loadingHandler(true);
    var productPage = 1;
    this.allProducts = [];
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: productPage, per_page: 100 },
        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      response.data.map((items, index) => {
        if (items.purchasable) {
          this.allProducts.push(items);
        }
        this.getGroupBuyItems(items);
        this.getTopSale(items);
        if (items.on_sale) {
          if (
            items.date_on_sale_from != null &&
            items.date_on_sale_to != null
          ) {
            let today = moment();
            let dateOnSale = moment(items.date_on_sale_to);
            console.log(dateOnSale.month());
            if (dateOnSale.unix() > today.unix()) {
              //console.log(dateOnSale.unix() - today.unix());
              items.unix = dateOnSale.unix() - today.unix();
              this.saleProduct.push(items);
              console.log('time test');
            }
          }
        }
      });

      productPage += 1;
      while ((await this.getProducts(productPage)) == 100) {
        console.log(productPage);
        productPage += 1;
      }
      console.log('testing');
      //this.getTopSale();

      transaction(() => {
        this.getCategories();
        //this.getAllTag();

        this.getbanners();
        //this.sortTopSale();
        if (this.logined) {
          this.getFavourite();
          this.getShoppingCart();
          this.getOrders();
        }
      });
      this.splash = true;

      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  sortTopSale() {
    this.topSale = underscore.sortBy(this.topSale, 'top');
  }


  async getbanners() {
    this.topBanners = [];
    this.bottomBanners = [];
    var url = api.banner;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      transaction(() => {
        response.data.map((items, index) => {
          if (items.status === 'A') {
            if (items.position === 'top') {
              this.topBanners.push(items);
            } else if (items.position === 'bottom') {
              this.bottomBanners.push(items);
            }
          }
        });
      });
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
      return 0;
    }
  }


  removeSearchHistory() {
    this.removeValue('searchHistory');
    this.searchHistory = [];
  }

  async searchParamsReturn(value, which) {
    var params = {};
    switch (which) {
      case 0:
        var categoryData = '';
        await value.map((items, index) => {
          if (index > 0) {
            categoryData += ',' + items;
          } else {
            categoryData += items;
          }
        });
        params = {
          page: 1,
          per_page: 100,
          category: categoryData,
        };
        break;

      case 1:
        var tagData = '';
        await value.map((items, index) => {
          if (index > 0) {
            tagData += ',' + items;
          } else {
            tagData += items;
          }
        });
        params = {
          page: 1,
          per_page: 100,
          tag: tagData,
        };
        break;

      case 2:
        params = {
          page: 1,
          per_page: 100,
          search: value,
        };
        break;
    }
    return params;
  }


  removeDuplicates(data, key) {
    return [...new Map(data.map(x => [key(x), x])).values()];
  }


  async postOrder(data, points, paymentMethod, self) {
    console.log(data);
    this.loadingHandler(true);
    var url = api.order;
    try {
      const response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      this.deleteAllShoppingCartItem();
      if (paymentMethod == 0) {
        this.payByCreditCard(response.data.id, points, self);
      } else {
        this.payBycash(response.data.id, paymentMethod, points, self);
      }
    } catch (error) {
      this.loadingHandler(false);
      self.refs.toast.show('下單失敗');
      console.log(error);
    }
  }


  async searchProducts(value) {
    this.loadingHandler(true);
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { keyword: value },
        timeout: 20000,
      });
      this.loadingHandler(false);
      console.log(response);
      this.searchResult = response.data;
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }

  async getNews() {
    this.news = []
    this.loadingHandler(true);
    var url = api.news
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      this.loadingHandler(false);
      console.log(response);

      transaction(() => {
        response.data.map((items, index) => {
          this.news.push(items)
        });
      });

      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async searchItems(value, which) {
    this.loadingHandler(true);
    var searchParams = await this.searchParamsReturn(value, which);
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: searchParams,
        timeout: 20000,
      });
      this.loadingHandler(false);
      console.log(response);
      if (response.data.length > 0) {
      }

      transaction(() => {
        response.data.map((items, index) => {
          this.searchResult.push(items);
        });
      });

      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }

  shippingPriceReturn(self) {
    if (this.shippingMethods.length > 0) {
      var shippingPriceIndex = this.shippingMethods.findIndex(
        element => element.id == 11,
      );
      var totalPriceForFreeShippingIndex = this.shippingMethods.findIndex(
        element => element.id == 3,
      );
      console.log(shippingPriceIndex);
      if (shippingPriceIndex != -1 && totalPriceForFreeShippingIndex != -1) {
        self.shippingSelection = [
          {
            label: '門市自取',
            value: 0,
            price: 0,
            freeShippingPrice: parseFloat(
              this.shippingMethods[totalPriceForFreeShippingIndex].settings
                .min_amount.value,
            ),
          },
          {
            label:
              '送到上門（滿' +
              this.priceFormatReturn(
                parseFloat(
                  this.shippingMethods[totalPriceForFreeShippingIndex].settings
                    .min_amount.value,
                ),
              ) +
              '免運費)',
            value: 1,
            freeShippingPrice: parseFloat(
              this.shippingMethods[totalPriceForFreeShippingIndex].settings
                .min_amount.value,
            ),
            price: parseFloat(
              this.shippingMethods[shippingPriceIndex].settings.cost.value,
            ),
          },
        ];
      }
    }
  }


  async getShipppingMethods(self) {
    this.loadingHandler(true);
    var url = api.getShippingMethods;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      console.log(response);

      this.loadingHandler(false);
      this.shippingMethods = response.data;
      self.shippingPriceReturn();
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async bindMobile(data, self) {
    this.loadingHandler(true);
    var requestURL = api.bindMobile;

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
      });
      this.loadingHandler(false);
      console.log(response);
      this.loginUserData.data.country_code = response.data.country_code;
      this.loginUserData.data.mobile = response.data.mobile;
      self.props.navigation.goBack();
    } catch (e) {
      this.loadingHandler(false);
      self.refs.toast.show('add mobile fail: ');
      console.log(e);
    }
  }


  async checkMember(data, self) {
    this.loadingHandler(true);
    var requestURL = api.check;
    var checkData = {
      email: data.email,
      mobile: data.mobile,
      country_code: data.country_code,
    };
    try {
      const response = await axios.post(requestURL, checkData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      this.loadingHandler(false);
      console.log(response);
      console.log(response.data[Object.keys(response.data)[0]]);
      if (response.data[Object.keys(response.data)[0]]) {
        // data.thirdParty = false;
        // history.push(self, '/signUpVerify', {signupData: data});
        self.props.navigation.navigate('SignUpVerify', {
          data: data,
          addMobile: false,
        });
      } else {
        self.refs.toast.show('Signup fail');
        this.loadingHandler(false);
      }
    } catch (e) {
      self.refs.toast.show('SignUp Fail');
      this.loadingHandler(false);
      console.log(e);
    }
  }

  async saveDataToLocal(key, data) {
    try {
      const jsonValue = JSON.stringify(data);
      await AsyncStorage.setItem(key, jsonValue);
    } catch (e) {
      console.log(e);
    }
  }

  async getLocalData(key) {
    try {
      const jsonValue = await AsyncStorage.getItem(key);
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (e) {
      // error reading value
      console.log(e);
    }
  }


  async postComment(data, self) {
    console.log(data);
    this.loadingHandler(true);
    var url = api.getAllProducts + data.product_id + '/reviews';
    var newData = {
      review: data.review,
      rating: data.rating,
    };
    try {
      const response = await axios.post(url, newData, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      self.refs.toast.show('評論成功');
      self.commentPage = 1;
      self.productComment = [];
      this.getComment(data.product_id, 1, self);
      // if (response.data.verified) {
      //   this.checkCommentRepeat(data, response.data.id, self);
      // } else {
      //   self.refs.toast.show('需要購買過此産品才能評論');
      // }
    } catch (error) {
      this.loadingHandler(false);
      if (error.response.data[0] == 'review_exists') {
        self.refs.toast.show('已在此產品評論過');
      } else if (error.response.data[0] == 'unauthorized') {
        self.refs.toast.show('需購買過此產品才能評論');
      } else {
        self.refs.toast.show('評論失敗，網絡問題');
      }

      console.log(error.response);
    }
  }


  async checkCommentRepeat(data, commentId, self) {
    this.loadingHandler(true);
    var url = api.review;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: {
          page: 1,
          per_page: 100,
          orderby: 'date',
          product: data.product_id,
          status: 'approved',
          reviewer_email: data.reviewer_email,
        },
        timeout: 5000,
      });
      console.log(response);
      if (response.data.length > 0) {
        self.refs.toast.show('已在此產品評論過');
      } else {
        this.commentStatusChange(commentId, data.product_id, self);
      }
      this.loadingHandler(false);
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
      self.refs.toast.show('評論失敗，網絡問題');
    }
  }


  async commentStatusChange(commentId, product_id, self) {
    this.loadingHandler(true);
    var requestURL = api.review + commentId;
    var data = {
      status: 'approved',
    };
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      self.commentPage = 1;
      self.productComment = [];
      self.refs.toast.show('評論成功');
      this.getComment(product_id, 1, self);
    } catch (e) {
      console.log(e);
      this.loadingHandler(false);
      self.refs.toast.show('評論失敗，網絡問題');
      //  self.refs.toast.show(e.response);
    }
  }


  async getComment(productId, pageValue, self) {
    this.loadingHandler(true);
    var url = api.getAllProducts + productId + '/reviews';
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: {
          page: pageValue,
          per_page: 10,
          orderby: 'date',
          //reviewer_email: 'ronny1@gmail.com',
        },
        timeout: 5000,
      });
      console.log(response);
      this.loadingHandler(false);
      var newArray = [];
      response.data.content.map((items, index) => {
        newArray.push(_.cloneDeep(items));
      });
      self.productComment = self.productComment.concat(response.data.content);
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getOrders() {
    this.orderList = [];
    this.loadingHandler(true);
    var url = api.order;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);

      this.orderList = response.data.sort((a, b) =>
        a.date_created < b.date_created
          ? 1
          : b.date_created < a.date_created
            ? -1
            : 0,
      );
      // this.orderList = response.data;
      console.log(response.data);
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async getRegions() {
    this.regions = [];
    // this.loadingHandler(true);
    var url = api.regions;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      console.log(response);
      //  this.loadingHandler(false);
      this.regions = response.data;
    } catch (error) {
      //   this.loadingHandler(false);
      console.log(error);
    }
  }


  async getAddress() {
    this.getRegions();
    this.addresses = [];
    this.loadingHandler(true);
    var url = api.address;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      console.log(response);
      this.loadingHandler(false);
      this.addresses = response.data;
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }


  async payByWeChat(id, points, self) {
    this.loadingHandler(true);
    var requestURL = api.order + id + '/pay';
    console.log(requestURL);
    var point = 0;
    if (parseInt(points) != 0 || points != '') {
      point = parseInt(points);
    }
    var data = {
      use_points: point,
      payment_method: 'stripe_wechat',
      card_token: this.creditCardinfo.token,
    };
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      Linking.canOpenURL(response.data.wechat.qr_code_url).then(supported => {
        if (supported) {
          Linking.openURL(response.data.wechat.qr_code_url);
        } else {
          console.log(
            "Don't know how to open URI: " + response.data.wechat.qr_code_url,
          );
        }
      });
      // var storeSelf = this;
      // this.startAnimate();
      // setTimeout(function() {
      //   // self.props.navigation.popToTop();
      //   self.props.navigation.navigate('Main');
      // }, 1000);
      // self.props.navigation.navigate('BuyHistory');
    } catch (e) {
      console.log(e.response);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }


  idGenerator() {
    return uuid.v4();
  }

  async loginWithApple(idToken, self, navAction) {
    var requestURL = api.signInWithApple;
    var data = {
      identityToken: idToken,
      device: uuid.v4(),
    };
    // data.device = uuid.v4();
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      // if (response.data.hasOwnProperty('nomember')) {
      //   var min = 0;
      //   var max = 99999999;
      //   var random = Math.floor(Math.random() * (+max - +min)) + +min;
      //   var ans = random.toString();
      //   console.log(ans);

      //   var signupData = {
      //     thirdParty: true,
      //     first_name: '',
      //     last_name: '',
      //     country_code: '+852',
      //     mobile: '',
      //     email: response.data.nomember.email,
      //     ver_code: '',
      //     welcome_code: '',
      //     password: ans,
      //   };
      //   this.loadingHandler(false);
      //   self.props.navigation.navigate('SignUpVerify', {data: signupData});
      // } else {
      this.loadingHandler(false);
      this.logined = true;
      this.loginUserData = response;
      this.userData = data;
      var saveData = {
        token: response.data.es_login_token,
        device: data.device,
      };
      this.saveDataToLocal('logindata', saveData);

      self.props.navigation.popToTop();

      this.token = response.data.es_login_token;
      this.uuid = data.device;
      this.getAddress();
      this.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      this.getPaymentMethods();
      //   }
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loadingHandler(false);
      //connectFail.fail();
      console.log(e);
    }
  }


  async thirdPartyLogin(data, self, navAction) {
    //  this.loadingHandler(true);
    var requestURL = api.thirdPartyLogin;
    data.device = uuid.v4();
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
      // if (response.data.hasOwnProperty('nomember')) {
      //   var min = 0;
      //   var max = 99999999;
      //   var random = Math.floor(Math.random() * (+max - +min)) + +min;
      //   var ans = random.toString();
      //   console.log(ans);

      //   var signupData = {
      //     thirdParty: true,
      //     first_name: '',
      //     last_name: response.data.nomember.name,
      //     country_code: '+852',
      //     mobile: '',
      //     email: response.data.nomember.email,
      //     ver_code: '',
      //     welcome_code: '',
      //     password: ans,
      //   };
      //   this.loadingHandler(false);
      //   self.props.navigation.navigate('SignUpVerify', {data: signupData});
      //  } else {
      this.loadingHandler(false);
      this.logined = true;
      this.loginUserData = response;
      this.userData = data;
      var saveData = {
        token: response.data.es_login_token,
        device: data.device,
      };
      this.saveDataToLocal('logindata', saveData);

      self.props.navigation.popToTop();

      this.token = response.data.es_login_token;
      this.uuid = data.device;
      this.getAddress();
      this.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      this.getPaymentMethods()
      // }
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loadingHandler(false);
      //connectFail.fail();
      console.log(e);
    }
  }

  async payBycash(id, paymentId, points, self) {
    self.payDisable = true;
    this.loadingHandler(true);
    var requestURL = api.order + id + '/pay';
    console.log(requestURL);
    var point = 0;
    if (parseInt(points) != 0 || points != '') {
      point = parseInt(points);
    }
    var data = {
      use_points: point,
      payment_method: 'cod',
      use_ppc: 0,
    };
    if (paymentId == 2) {
      data.payment_method = 'fps'
    } else if (paymentId == 3) {
      data.payment_method = 'payme'
    }
    console.log(data);
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      var storeSelf = this;
      this.startAnimate();
      setTimeout(function () {
        self.payDisable = false;
        self.props.navigation.navigate('BuyHistory');
      }, 1000);
      // self.props.navigation.navigate('BuyHistory');
    } catch (e) {
      self.refs.toast.show('下單失敗');
      setTimeout(function () {
        // self.props.navigation.popToTop();
        self.payDisable = false;
        self.props.navigation.navigate('BuyHistory');
      }, 1000);
      console.log(e.response);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }


  async payByCreditCard(id, points, self) {
    console.log(points)
    self.payDisable = true;
    this.loadingHandler(true);
    var requestURL = api.order + id + '/pay';
    console.log(requestURL);
    var point = 0;
    if (parseInt(points) != 0 || points != '') {
      point = parseInt(points);
    }
    var data = {
      use_points: point,
      payment_method: 'stripe',
      creditcard: this.creditCardinfo.id,
      use_ppc: 0,
      //card_token: this.creditCardinfo.token,
    };
    console.log(requestURL);
    console.log(data);
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      var storeSelf = this;
      this.startAnimate();
      setTimeout(function () {
        self.payDisable = false;
        self.props.navigation.navigate('BuyHistory');
      }, 1000);
      // self.props.navigation.navigate('BuyHistory');
    } catch (e) {
      self.refs.toast.show('付款失敗');
      setTimeout(function () {
        // self.props.navigation.popToTop();
        self.payDisable = false;
        self.props.navigation.navigate('BuyHistory');
      }, 1000);
      console.log(e.response);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }


  async orderProducts() { }

  async removeValue(key) {
    try {
      await AsyncStorage.removeItem(key);
    } catch (e) {
      // remove error
    }

    console.log('Done.');
  }


  async getFcmToken() {
    messaging()
      .getToken()
      .then(token => {
        console.log(token);
        if (this.logined) {
          this.postFcmToken(token);
        }
      });
  }

  async requestUserPermission() {
    const authorizationStatus = await messaging().requestPermission();
    if (authorizationStatus) {
      console.log('Permission status:', authorizationStatus);
      if (authorizationStatus === messaging.AuthorizationStatus.AUTHORIZED) {
        console.log('User has notification permissions enabled.');
        this.getFcmToken();
      }
    }
  }


  async notificationInit() {
    console.log('ddd')
    const authorizationStatus = await messaging().requestPermission();
    console.log(authorizationStatus);
    if (authorizationStatus === messaging.AuthorizationStatus.AUTHORIZED) {
      console.log('User has notification permissions enabled.');
      this.getFcmToken();
    } else if (
      authorizationStatus === messaging.AuthorizationStatus.PROVISIONAL
    ) {
      console.log('User has provisional notification permissions.');
    } else if (
      authorizationStatus === messaging.AuthorizationStatus.NOT_DETERMINED
    ) {
      console.log(
        'Permission has not yet been requested for your application.',
      );
      this.requestUserPermission();
    } else {
      console.log('User has notification permissions disabled');
    }
  }


  async postFcmToken(fcmtoken) {
    this.loadingHandler(true);
    var url = api.fcmToken;
    var data = {
      mid: this.loginUserData.data.id,
      token: fcmtoken,
    };
    console.log(data);
    try {
      const response = await axios.put(url, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
        timeout: 5000,
      });
      this.loadingHandler(false);
      console.log(response);
    } catch (error) {
      this.loadingHandler(false);
      console.log(error.response);
    }
  }


  async logoutPost(self) {
    this.postFcmToken('');
    this.logined = false;
    await this.removeValue('logindata');
    self.props.navigation.navigate('Main');
  }


  async getCoupons(self) {
    this.coupons = [];
    this.loadingHandler(true);
    var url = api.getCoupons;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        params: { page: 1, per_page: 100 },
        timeout: 5000,
      });
      console.log(response);
      console.log(moment.utc(response.headers.date).local().format('MM/DD/YYYY hh:mm'))
      this.loadingHandler(false);
      await response.data.map((items, index) => {
        // if (items.date_expires != null) {
        //   console.log(
        //     'date: ' + moment(items.date_expires).format('DD/MM/YYYY'),
        //   );
        //   if (moment() < moment(items.date_expires)) {
        //     this.coupons.push(items);
        //   }
        // } else {
        //   this.coupons.push(items);
        // }
        if (items.status === 'A') {
          this.coupons.push(items);
        }
      });
      console.log(this.coupons);
    } catch (error) {
      this.loadingHandler(false);
      console.log(error);
    }
  }



  async loginPost(self, data, nav) {
    data.device = uuid.v4();
    this.loadingHandler(true);
    var url = api.login;
    var loginData = _.cloneDeep(data);
    console.log(loginData);
    try {
      const response = await axios.post(url, loginData, {
        headers: {

          'Content-Type': 'application/json',

        },
        timeout: 5000,
      });
      this.loadingHandler(false);
      this.logined = true;
      console.log(response)
      this.loginUserData = response.data;
      this.userData = data;
      var saveData = {
        token: response.data.es_login_token,
        device: data.device,
      };
      this.saveDataToLocal('logindata', saveData);
      if (nav) {
        self.props.navigation.popToTop();
      }
      console.log(response);
      this.token = response.data.es_login_token;
      this.uuid = data.device;

      this.notificationInit();

      this.getPoints();

    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loadingHandler(false);
      //connectFail.fail();
      console.log(e.response);
    }
  }


  async getUserData(self, data, nav) {
    console.log('Basic ' + base64.encode(`${this.uuid}:${this.token}`))
    this.loadingHandler(true);
    var url = api.editAddress;

    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
        timeout: 5000,
      });
      this.loadingHandler(false);
      this.logined = true;
      this.loginUserData = response.data;
      if (nav) {
        self.props.navigation.popToTop();
      }
      console.log(response);
      // this.getAddress();
      // this.getShoppingCart();
      // this.notificationInit();
      // this.getCreditCard();
      // this.getPaymentMethods();
    } catch (e) {
      //self.refs.toast.show('Login Fail');
      this.loadingHandler(false);
      //connectFail.fail();
      console.log(JSON.stringify(e));
    }
  }


  async signupPost(self, data) {
    var jsonData = _.cloneDeep(data);
    this.loadingHandler(true);
    var requestURL = api.signup;
    try {
      const response = await axios.post(requestURL, jsonData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      this.loadingHandler(false);
      // transaction(() => {
      //   this.loadingHandler(false);
      //   this.logined = true;
      //   this.loginUserData = response;
      // });

      console.log(response);
      var loginUserData = {
        username: data.email,
        password: data.password,
      };
      this.loginPost(self, loginUserData, true);
      // self.navigatieAction("menu");
      // var data = {id: response.data.member.id, token: response.data.token};

      //this.loginPost(data, self, true);
    } catch (e) {
      console.log(e.response);
      self.refs.toast.show('SignUp Fail: ' + e.response.data);
      this.loadingHandler(false);
    }
  }


  async addAddress(data, self) {
    this.addresses = [];
    this.loadingHandler(true);
    var requestURL = api.address;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      //this.loginUserData.data.address = response.data.address;
      await this.addresses.push(response.data);
      console.log(this.addresses);
      self.props.navigation.goBack();
    } catch (e) {
      console.log(e);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }


  countdownHandler(sec) {
    let minutes = Math.floor(sec / 60);
    let seconds = sec % 60;
    minutes = String(minutes).padStart(2, "0");
    seconds = String(seconds).padStart(2, "0");
    return (minutes + ":" + seconds)
  }


  async editAddress(data, id, self) {
    this.loadingHandler(true);
    var requestURL = api.address + id;
    data.id = id;
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      this.addresses[0] = response.data;
      self.props.navigation.goBack();
    } catch (e) {
      console.log(e);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }


  async editName(data, self) {
    this.loadingHandler(true);
    var requestURL = api.editAddress;

    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      this.loadingHandler(false);
      console.log(response);
      this.loginUserData.data.last_name = response.data.last_name;
      this.loginUserData.data.first_name = response.data.first_name;
      self.props.navigation.goBack();
    } catch (e) {
      console.log(e);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }


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

      this.logoutPost(self);
      console.log(response);
    } catch (e) {
      console.log(e.response.data);
      self.refs.toast.show('Reset Password Fail');
      this.loadingHandler(false);
    }
  }


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

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

      this.loadingHandler(false);
      console.log(response);
    } catch (e) {
      console.log(e);
      this.loadingHandler(false);
      //  self.refs.toast.show(e.response);
    }
  }
}
export default new Stores();
