import { inject, observer } from "mobx-react"
import { makeAutoObservable, action, observable, transaction } from "mobx";
import language from '../services/language';
import AsyncStorage from '@react-native-community/async-storage';
import messaging from '@react-native-firebase/messaging';
import axios from 'axios';
import { Alert, Platform, Animated, Easing, Linking } from 'react-native';
import base64 from 'react-native-base64';
import api from '../services/api';
import moment from 'moment';
import queryString from 'query-string';
var _ = require('lodash');
import uuid from 'react-native-uuid';
var underscore = require('underscore');

class Stores {
  routerRef;

  animateStatus = {
    progress: new Animated.Value(0),
    show: false,
  };

  token = '';
  footerLoading = false
  uuid = '';

  addedCard = false;
  page = {
    categoryProduct: 0
  }
  flatlistEnd = false
  searchHistory = [];
  routerState;
  userData = {};
  currentScene = 'Main';
  splash = false;
  logined = false;
  groupBuyList = [];
  loginUserData = null;
  saleProduct = [];
  allProducts = [];
  categoriesProducts = [];
  topSale = [];
  categories = [];
  categoriesForSearch = [];
  youMayLikeList = [];
  tagForSearch = [];
  favorite = [];
  shoppingCartList = [];
  shoppingCartIds = [];
  orderList = [];
  banners = [];
  coupons = [];
  shippingMethods = [];
  searchResult = [];
  loading = false;

  creditCardinfo = null;
  timer = 60;

  text = language.hk;

  languageSelection = 'hk';

  points = 0;

  pointsMemony = 0;

  constructor(rootStore) {
    makeAutoObservable(this, {
      flatlistEnd: observable,
      routerRef: observable,
      categoriesProducts: observable,
      animateStatus: observable,
      token: observable,
      footerLoading: observable,
      uuid: observable,
      addedCard: observable,
      searchHistory: observable,
      routerState: observable,
      userData: observable,
      currentScene: observable,
      splash: observable,
      logined: observable,
      groupBuyList: observable,
      loginUserData: observable,
      saleProduct: observable,
      allProducts: observable,
      topSale: observable,
      categories: observable,
      categoriesForSearch: observable,
      youMayLikeList: observable,
      tagForSearch: observable,
      favorite: observable,
      shoppingCartList: observable,
      shoppingCartIds: observable,
      orderList: observable,
      banners: observable,
      coupons: observable,
      shippingMethods: observable,
      searchResult: observable,
      loading: observable,
      page: observable,
      creditCardinfo: observable,
      timer: observable,

      text: observable,

      languageSelection: observable,

      points: observable,

      pointsMemony: observable,
    })
  }

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

  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);
  };

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


  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.loading = true;
    this.favorite = [];
    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: 20000,
      });
      this.loading = 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(ids, false);
      }
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }


  async modifyShoppingCart(index, self, itemsQty) {
    var data = [
      {
        product_id: this.shoppingCartList[index].id,
        qty: itemsQty,
        status: 1,
      },
    ];

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

        timeout: 20000,
      });
      this.loading = false;
      self.refs.toast.show('已更改數量');
      console.log(response);

      this.shoppingCartList[index].buyCount = itemsQty;

      self.modifyQuantityVisable = false;
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('更改數量失敗');
      console.log(error);
    }
  }


  async addSingleItemToShoppingCart(items, self) {

    if (this.loginUserData == null) {
      self.refs.toast.show('Please login')
    } else {
      var itemIndex = await this.shoppingCartList.findIndex(
        element => element.id === items.id,
      );
      if (itemIndex != -1) {
        items.buyCount =
          parseInt(items.buyCount) +
          parseInt(this.shoppingCartList[itemIndex].buyCount);
      }
      var data = [
        {
          product_id: items.id,
          qty: items.buyCount,
          status: 1,
        },
      ];
      var originData = [items];

      this.addShoppingCart(data, self, originData);
    }
  }


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

        timeout: 20000,
      });
      this.loading = false;
      self.refs.toast.show('已加入購物車');
      console.log(response);
      await originData.map(async (data, index) => {
        var itemIndex = await this.shoppingCartList.findIndex(
          element => element.id === data.id,
        );
        if (itemIndex == -1) {
          this.shoppingCartList.push(_.cloneDeep(data));
        } else {
          this.shoppingCartList[itemIndex].buyCount = data.buyCount;
        }
      });
      console.log(this.shoppingCartList);
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('加入失敗');

      console.log(error);
    }
  }


  async getCategories() {
    this.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);
      transaction(() => {
        // var count = 0;
        // var matrix = [];
        response.data.map((items, index) => {
          if (items.name !== 'none') {
            this.categories.push(items);
          }
        });
      });
      this.getFavouriteProducts(response.data[Math.floor(Math.random() * response.data.length)].id)
      //this.allProducts = response.data;
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      console.log(error);
    }
  }

  async getFavouriteProducts(Categoryid) {
    this.youMayLikeList = [];
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: 1, per_page: 10, category: Categoryid },
        timeout: 20000,
      });
      console.log(response);
      response.data.map((item, index) => {
        this.youMayLikeList.push(item)
      })

    } catch (error) {
      console.log(error.response);
    }
  }


  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: 20000,
      });
      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);
    var searchIndex = await this.searchHistory.findIndex(
      element => element === value,
    );
    if (searchIndex === -1) {
      this.searchHistory.push(value);
      this.saveDataToLocal('searchHistory', _.cloneDeep(this.searchHistory));
    }
  }


  async deleteShoppingCartItem(index, self) {
    var deleteId = [this.shoppingCartList[index].id];
    this.loading = true;
    var url = api.shoppingCart;
    try {
      const response = await axios.delete(url, {
        data: deleteId,
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 20000,
      });
      this.loading = false;
      console.log(response);
      self.refs.toast.show('刪除成功');
      this.shoppingCartList.splice(index, 1);
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('刪除失敗');
      console.log(error);
    }
  }


  async deleteAllShoppingCartItem() {
    var deleteId = [];
    this.shoppingCartList.map((items, index) => {
      deleteId.push(items.id);
    });
    this.loading = true;
    var url = api.shoppingCart;
    try {
      const response = await axios.delete(url, {
        data: deleteId,
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 20000,
      });
      this.loading = false;
      console.log(response);

      this.shoppingCartList = [];
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }


  async getPoints() {
    this.loading = 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: 20000,
      });

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


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

        timeout: 20000,
      });

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

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


  async getCreditCard() {
    this.loading = 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: 20000,
      });

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


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

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


  async postCreditCard(self, data) {
    console.log(data);
    this.loading = 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: 20000,
      });
      this.loading = false;
      transaction(() => {
        this.creditCardinfo = response.data;
        this.loading = false;
        this.addedCard = true;
      });
      console.log(response);
      self.addCard = false;
      self.cardData = null;
      //navigation.goBack();
      // self.navigatieAction("menu");
    } catch (e) {
      this.loading = 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 getProductsByCategory(categoryId, newCategory) {
    console.log(categoryId)
    this.footerLoading = true
    if (newCategory) {
      this.page.categoryProduct = 0
      this.categoriesProducts = [];
      this.flatlistEnd = false
    }
    console.log(newCategory)
    var url = api.getAllProducts;

    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: this.page.categoryProduct += 1, per_page: 10, category: categoryId },
        timeout: 20000,
      });

      this.footerLoading = false;
      console.log(response);

      response.data.map((item, index) => {
        this.categoriesProducts.push(item)
      })

      if (response.data.length === 0) {
        this.flatlistEnd = true
      }

    } catch (error) {
      this.footerLoading = false;
      console.log(error.response);
    }
  }


  async getProductById(ids, which, list) {
    console.log(
      'ids: ' + ids + '   ' + 'which: ' + which + '    ' + 'list: ' + list,
    );
    this.loading = true;
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: 1, per_page: 100, include: ids },
        timeout: 20000,
      });
      this.loading = false;
      console.log(response);
      if (which) {
        await response.data.map((items, index) => {
          items.selected = false;
          items.buyCount = 1;
          this.favorite.push(items);
        });
      } else {
        this.shoppingCartList = [];
        await response.data.map(async (items, index) => {
          console.log(items.id);
          console.log(this.shoppingCartIds);
          items.selected = false;
          var itemsIndex = await this.shoppingCartIds.findIndex(
            element => parseInt(element.product_id) == items.id,
          );
          if (itemsIndex != -1) {
            items.buyCount = this.shoppingCartIds[itemsIndex].qty;
          }
          this.shoppingCartList.push(items);
        });
      }
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }


  async getFavourite() {
    this.loading = true;
    this.favorite = [];
    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: 20000,
      });
      this.loading = false;

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


  async deleteFavourite(deleteIndex, deleteId, self) {
    console.log(deleteIndex);
    console.log(deleteId);
    this.loading = 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: 20000,
      });
      this.loading = false;
      console.log(response);
      self.refs.toast.show('刪除成功');
      const indexSet = new Set(deleteIndex);
      this.favorite = this.favorite.filter((value, i) => !indexSet.has(i));
      self.deleteAble = false;
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('刪除失敗');
      console.log(error);
    }
  }

  async addFavouritePost(data, self) {
    var uploadData = [
      {
        product_id: '' + data.id,
      },
    ];
    this.loading = 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: 20000,
      });
      this.loading = false;
      self.refs.toast.show('已加入我的清單');
      var newData = _.cloneDeep(data);
      newData.selected = false;
      newData.buyCount = 1;
      this.favorite.push(newData);
      console.log(response);
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('加入失敗');
      console.log(error);
    }
  }


  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 getRandamFavourite() {
    var count = 0;
    // new array to push random item in
    var n = 8;
    var randomItems = [];
    var newProductList = _.cloneDeep(this.allProducts);
    do {
      var item = this.getRandomItem(newProductList);
      randomItems.push(item);
      // update the original array and remove the recently pushed item
      newProductList.splice(newProductList.indexOf(item), 1);
      count++;
    } while (count < n);

    console.log(randomItems);
    this.youMayLikeList = randomItems;
  }


  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) => {

        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.loading = 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 getOnSaleProducts() {
    this.saleProduct = [];
    this.topSale = [];
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { page: 1, per_page: 5, on_sale: true },
        timeout: 20000,
      });
      console.log(response);
      response.data.map((item, index) => {
        this.topSale.push(item)
        // 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);
        //   }
        // }
      })

    } catch (error) {
      console.log(error.response);
    }
  }


  async getAllProductFromStart(self) {
    this.groupBuyList = [];
    this.saleProduct = [];
    this.topSale = [];
    this.loading = 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: 5 },
        timeout: 20000,
      });
      this.loading = false;
      console.log(response);
      response.data.map((items, index) => {
        // if (items.purchasable) {
        //   this.allProducts.push(items);
        // }
        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.getRandamFavourite();
        this.getbanners();
        this.sortTopSale();
        if (this.logined) {
          this.getFavourite();
          this.getShoppingCart();
          this.getOrders();
        }
      });
      this.splash = true;
      //  self.props.navigation.navigate('BottomTabScreen');
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }


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


  async getbanners() {
    this.banners = [];
    var url = api.banner;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      this.banners = response.data;
    } catch (error) {
      this.loading = 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.loading = 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: 20000,
      });
      this.loading = false;
      console.log(response);
      this.deleteAllShoppingCartItem();
      if (paymentMethod == 0) {
        this.payByCreditCard(response.data.id, points, self);
      } else {
        //this.payByWeChat(response.data.id, points, self);
        this.payBycash(response.data.id, points, self);
      }
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('下單失敗');
      console.log(error);
    }
  }


  async searchItems(value, which) {
    this.loading = 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.loading = 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.loading = 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.loading = true;
    var url = api.getShippingMethods;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        auth: {
          username: 'ck_b874a329485c224afcd520cb3c1e838f79367210',
          password: 'cs_f207f21e02f7ce5b5141925e2693c4527ce987df',
        },
        params: { page: 1, per_page: 100 },
        timeout: 20000,
      });
      console.log(response);

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


  async bindMobile(data, self) {
    this.loading = 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.loading = 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.loading = false;
      self.refs.toast.show('add mobile fail: ');
      console.log(e);
    }
  }


  async checkMember(data, self) {
    this.loading = 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.loading = 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.loading = false;
      }
    } catch (e) {
      self.refs.toast.show('SignUp Fail');
      this.loading = 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.loading = true;
    var url = api.review;
    try {
      const response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 20000,
      });
      this.loading = false;
      console.log(response);
      if (response.data.verified) {
        this.checkCommentRepeat(data, response.data.id, self);
      } else {
        self.refs.toast.show('需要購買過此産品才能評論');
      }
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('評論失敗，網絡問題');
      console.log(error);
    }
  }


  async checkCommentRepeat(data, commentId, self) {
    this.loading = 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: 20000,
      });
      console.log(response);
      if (response.data.length > 0) {
        self.refs.toast.show('已在此產品評論過');
      } else {
        this.commentStatusChange(commentId, data.product_id, self);
      }
      this.loading = false;
    } catch (error) {
      this.loading = false;
      console.log(error);
      self.refs.toast.show('評論失敗，網絡問題');
    }
  }


  async commentStatusChange(commentId, product_id, self) {
    this.loading = 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: 20000,
      });

      this.loading = 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.loading = false;
      self.refs.toast.show('評論失敗，網絡問題');
      //  self.refs.toast.show(e.response);
    }
  }


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


  async getOrders() {
    this.orderList = [];
    this.loading = true;
    var url = 'https://www.hosunsin.com/wp-json/es/v1/orders/';
    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: 20,
          orderby: 'date',
          status: [
            'pending',
            'processing',
            'on-hold',
            'completed',
            'cancelled',
            'shipped',
            'refunded',
          ],
        },
        paramsSerializer: params => {
          return queryString.stringify(params);
        },
        timeout: 20000,
      });

      this.loading = false;
      this.orderList = response.data;
      console.log(response.data);
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }


  async payByWeChat(id, points, self) {
    this.loading = 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: 20000,
      });

      this.loading = 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.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }

  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: 20000,
      });
      this.loading = 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.loading = false;
      //   self.props.navigation.navigate('SignUpVerify', {data: signupData});
      // } else {
      this.loading = 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.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      //   }
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e);
    }
  }


  async thirdPartyLogin(data, self, navAction) {
    //  this.loading = true;
    var requestURL = api.thirdPartyLogin;
    data.device = uuid.v4();
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      this.loading = 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.loading = false;
      //   self.props.navigation.navigate('SignUpVerify', {data: signupData});
      //  } else {
      this.loading = 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.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      // }
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e);
    }
  }

  async payBycash(id, points, self) {
    self.payDisable = true;
    this.loading = 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',
    };
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 20000,
      });

      this.loading = 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.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }


  async payByCreditCard(id, points, self) {
    self.payDisable = true;
    this.loading = 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',
      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: 20000,
      });

      this.loading = 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.loading = 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() {
    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.loading = true;
    var url = api.fcmToken;
    var data = {
      token: fcmtoken,
    };
    try {
      const response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 20000,
      });
      this.loading = false;
      console.log(response);
    } catch (error) {
      this.loading = false;

      console.log(error);
    }
  }


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


  async getCoupons(self) {
    this.coupons = [];
    this.loading = 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: 20000,
      });
      console.log(response);
      this.loading = 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);
        }
      });
      console.log(this.coupons);
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }


  async loginPost(self, data, nav) {
    data.device = uuid.v4();
    this.loading = true;
    var url = api.login;
    var loginData = _.cloneDeep(data);
    try {
      const response = await axios.post(url, loginData, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      this.loading = 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);
      if (nav) {
        self.props.navigation.popToTop();
      }
      console.log(response);
      this.token = response.data.es_login_token;
      this.uuid = data.device;
      this.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      this.getPoints();
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e);
    }
  }

  async init(logined) {
    if (logined) {
      this.getShoppingCart();
      this.getCreditCard();
      this.getFavourite();
      this.getShoppingCart();
      this.getOrders();
    }
    this.getCategories();
    this.getAllTag();
    this.getOnSaleProducts()
    //this.getRandamFavourite();
    this.getbanners();
    this.sortTopSale();
    this.splash = true;

  }


  async getUserData(self, data, nav) {
    this.loading = 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: 20000,
      });
      this.loading = false;
      this.logined = true;
      this.loginUserData = response;
      if (nav) {
        self.props.navigation.popToTop();
      }
      console.log(response);

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


  async signupPost(self, data) {
    var jsonData = _.cloneDeep(data);
    this.loading = true;
    var requestURL = api.signup;
    try {
      const response = await axios.post(requestURL, jsonData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
      this.loading = false;
      // transaction(() => {
      //   this.loading = 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.loading = false;
    }
  }


  async editAddress(data, self) {
    this.loading = 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: 20000,
      });

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


  async editName(data, self) {
    this.loading = 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: 20000,
      });

      this.loading = 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.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }


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

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


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

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

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