import { observable, computed, action, 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';
const qs = require('qs');
var _ = require('lodash');
var uuid = require('react-native-uuid');
var underscore = require('underscore');


class Stores {
  routerRef;
  @observable
  animateStatus = {
    progress: new Animated.Value(0),
    show: false,
  };

  @observable
  token = '';
  @observable
  uuid = '';
  @observable
  addedCard = false;
  @observable
  searchHistory = [];
  @observable
  discountItems = [];
  @observable shoppingGroupIntro = ''
  @observable dateWithoutHoliday = []
  @observable routerState;
  @observable userData = {};
  @observable regions = [];
  @observable regionsArray = [];
  @observable addresses = [];
  @observable currentScene = 'Main';
  @observable splash = false;
  @observable logined = false;
  @observable groupBuyList = [];
  @observable loginUserData = null;
  @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 news = [];
  @observable coupons = [];
  @observable discount = [];
  @observable shippingMethods = [];
  @observable searchResult = [];
  @observable recommendShoppingGroup = [];
  @observable nowDate = null;
  @observable loading = false;
  @observable
  creditCardinfo = null;
  @observable timer = 60;
  @observable
  text = language.hk;
  @observable
  languageSelection = 'hk';
  @observable
  points = 0;
  @observable
  pointsMemony = 0;
  @observable
  shippingOrderDate = null;
  @observable
  redeemHistory = [];
  @observable
  notificationRecord = null
  @observable
  catalogueSelected = null

  @observable
  gift = []

  async descHandler(desc) {
    var pToBr = ''
    pToBr = await desc.replaceAll('<p>', '<br>')
    pToBr = await desc.replaceAll('</p>', '</br>')

    return pToBr
  }

  @action
  async editUserName(name, self) {
    this.loading = true;
    var url = api.editAddress;
    var data = this.loginUserData.data.hasOwnProperty('member')
      ? this.loginUserData.data.member
      : this.loginUserData.data;
    data.name = name
    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.loading = false;
      self.editNameVisable = false
    } catch (error) {
      console.log(error.response);
      this.loading = false;
    }
  }

  @action
  async getShoppingGroupIntro() {
    const url = api.getShoppingGroupAgreement
    try {
      const response = await axios.get(url, {
        params: {
          keys: 'shopping_group_intro'
        },
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      console.log(response);
      this.shoppingGroupIntro = response.data[0].value


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

    }
  }

  @action
  async allRead() {
    this.notificationRecord.unread = 0;
    try {
      const saveItem = JSON.stringify(this.notificationRecord)
      await AsyncStorage.setItem('notification', saveItem)
    } catch (e) {
      // saving error
    }
  }

  @action
  async deleteNotifications() {
    this.notificationRecord = {
      notifications: [],
      unread: 0,
    }
    try {
      const saveItem = JSON.stringify(this.notificationRecord)
      await AsyncStorage.setItem('notification', saveItem)
    } catch (e) {
      // saving error
    }
  }

  @action
  async saveNotification(notif) {
    var notificationRecord = {
      notifications: [],
      unread: 0,
    }
    const data = {
      id: notif.messageId,
      date: moment(),
      title: notif.notification.title,
      message: notif.notification.body,
      read: false,
    }
    try {
      const jsonValue = await AsyncStorage.getItem('notification')
      if (jsonValue != null) {
        notificationRecord = JSON.parse(jsonValue)
      }
      console.log(jsonValue)
    } catch (e) {
      console.log(e)
    }
    console.log(notificationRecord)
    await notificationRecord.notifications.push(data);
    notificationRecord.unread += 1;
    try {
      const saveItem = JSON.stringify(notificationRecord)
      await AsyncStorage.setItem('notification', saveItem)
    } catch (e) {
      // saving error
    }

    this.notificationRecord = notificationRecord
    console.log(this.notificationRecord)

  }

  @action
  async getNotificationsMessage() {
    var notificationRecord = {
      notifications: [],
      unread: 0,
    }
    try {
      const jsonValue = await AsyncStorage.getItem('notification')
      if (jsonValue != null) {
        notificationRecord = JSON.parse(jsonValue)
      }
      console.log(jsonValue)
    } catch (e) {
      console.log(e)
    }
    this.notificationRecord = notificationRecord
    console.log(this.notificationRecord)

  }


  @action
  async getGiftList() {
    this.gift = []
    var url = api.gift;
    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);
      var gift = []
      await response.data.content.map(async (items, index) => {
        items.qty = 0
        await gift.push(items)
      })
      this.gift = gift

    } catch (error) {
      console.log(error.response);
      self.shoppingGroup = null;
    }
  }

  @action async quitShoppingGroup(self) {
    this.loading = true;
    var url = api.quitShoppingGroup;
    var 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.loading = false;
      this.loginUserData = response;
      console.log(response);
      self.refs.toast.show('已離開購物團');
    } catch (error) {
      console.log(error.response);
      this.loading = false;
    }
  }

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

        timeout: 5000,
      });
      this.loading = false;
      this.loginUserData = response;
      this.getOwnShoppingGroup(self, true, true);
      console.log(response);
      self.refs.toast.show('已加入購物團');
    } catch (error) {
      console.log(error.response);
      this.loading = false;
    }
  }


  @action async getOwnShoppingGroup(self, isOrder, join) {
    var url = api.getOwnShoppingGroup;
    console.log('Basic ' + base64.encode(`${this.uuid}:${this.token}`))
    try {
      const response = await axios.get(url, {

        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 20000,
      });
      console.log(response);
      if (isOrder) {
        if (join) {
          self.data = response.data.shoppingGroup;
          self.otherData = response.data;
          self.isRecommend = false;
          self.findThisMonthTotalAmount()
        } else {
          self.shoppingGroup = response.data;
        }
      } else {
        var otherData = response.data;
        self.props.navigation.navigate('GroupDetails', {
          data: response.data.shoppingGroup,
          isRecommend: false,
          otherShoppingGroupData: otherData,
        });
      }
    } catch (error) {
      console.log(JSON.stringify(error));
      self.shoppingGroup = null;
    }
  }

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

        timeout: 5000,
      });
      this.getShipppingMethods()
      console.log(response);
      if (this.addresses.length > 0) {
        this.recommendShoppingGroup = await response.data.content.filter(e => this.addresses[0].district.id === e.district.id);
      }
    } catch (error) {
      console.log(error);
    }
  }


  @action async redeemGift(data, self) {

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

        timeout: 5000,
      });
      this.loading = false;
      console.log(response);
      this.loginUserData.data.shoppingGroupPoints -= response.data.itemsTotalPrice
      self.props.navigation.goBack()

    } catch (error) {
      this.loading = false;

      console.log(error.response);
      self.refs.toast.show(error.response.data[0])
    }
  }

  @action async getRedeemHistory() {
    var url = api.redeem;
    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.redeemHistory = response.data.content

    } catch (error) {

      console.log(error);
    }
  }

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

        timeout: 5000,
      });
      this.loading = false;

      console.log(response);
      this.shippingOrderDate = response.data;
      this.nowDate = (moment(response.headers.date).toDate())
      console.log(moment(response.headers.date).format('DD-MM-YYYY HH:mm'))
      this.dateWithoutHoliday = await this.shippingOrderDate.available_delivery_dates.filter(
        function (item) {
          return item.holiday == false;
        },
      );
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

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

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

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

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

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

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

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

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

  @action
  async addMemberToGroup(phone, self) {

    this.loading = true;
    var url = api.check;
    var checkData = {
      countryCode: '852',
      mobile: phone
    }
    try {
      const checkresponse = await axios.post(url, checkData, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loading = false;

      console.log(checkresponse.data);
      const data = checkresponse.data[Object.keys(checkresponse.data)[0]]
      console.log(data);
      if (data == true) {
        self.refs.toast.show('Member no exist')
      } else {
        if (data.hasOwnProperty('shoppingGroup')) {
          self.refs.toast.show('This member have shopping group already')
        } else {
          this.loading = true
          memberId = {
            id: data.id
          }
          console.log(memberId)
          try {
            const addresponse = await axios.put(api.addMemberToMyGroup, memberId, {
              headers: {
                'Content-Type': 'application/json',
                Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
              },

              timeout: 5000,
            });
            this.loading = false;
            console.log(addresponse)
            self.refs.toast.show('Add group member success')

            try {

              const response = await axios.get(api.getOwnShoppingGroup, {

                headers: {
                  'Content-Type': 'application/json',
                  Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
                },

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

              self.otherData = response.data;
              self.data = response.data.shoppingGroup;

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

            }

          } catch (error) {
            this.loading = false;
            self.refs.toast.show('加入失敗');
            console.log(error.response);
          }
        }
      }
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('加入失敗');
      console.log(error.response);
    }
  }

  @action
  priceFormatReturn(price) {
    var floatPrice = parseFloat(price);
    return 'HKD ' + floatPrice.toFixed(1);
  }

  @action async discountHandler(self) {
    console.log(this.discount[0])
    if (this.discount.length > 0) {
      switch (this.discount[0].type) {
        case 3:
          var newArray = []
          this.discount[0].items1.map(async (items, index) => {
            const findProductIndex = await this.shoppingCartList.findIndex((element) => element.id === items.id);
            if (findProductIndex > -1) {
              this.shoppingCartList[findProductIndex].on_sale = true
              this.shoppingCartList[findProductIndex].originalPrice = this.shoppingCartList[findProductIndex].price
              this.shoppingCartList[findProductIndex].price = await this.discountPriceHandler(this.discount[0].discount, this.discount[0].value, this.shoppingCartList[findProductIndex].price)
            }
          })
          console.log(this.shoppingCartList)
          break;
        case 2:
          //handle in shoppingCart page, checkItems1Exist()
          this.discountItems = [];
          break;

        case 1:
          var newArray = []
          var item1index = -1
          await this.discount[0].items1.map(async (items, index) => {
            item1index = await this.shoppingCartList.findIndex((element) => element.id === items.id);
          })
          console.log(item1index)
          if (item1index >= 0) {
            this.discount[0].items2.map(async (items, index) => {
              const findProductIndex = await this.shoppingCartList.findIndex((element) => element.id === items.id);
              if (findProductIndex > -1) {
                this.shoppingCartList[findProductIndex].on_sale = true
                this.shoppingCartList[findProductIndex].originalPrice = this.shoppingCartList[findProductIndex].price
                this.shoppingCartList[findProductIndex].price = await this.discountPriceHandler(this.discount[0].discount, this.discount[0].value, this.shoppingCartList[findProductIndex].price)
              }

            })
          }
          console.log(this.shoppingCartList)
          break;
        case 0:
          this.discountTypeZeroHandler();
          break;

        default:
          break;
      }
    }
  }


  @action async discountTypeZeroHandler() {

    if (this.discount.length > 0) {
      if (this.discount[0].type == 0) {
        var totalPrice = 0
        await this.discount[0].items1.map(async (items, index) => {
          const findProductIndex = await this.shoppingCartList.findIndex((element) => element.id === items.id);
          if (findProductIndex > -1) {
            if (this.shoppingCartList[findProductIndex].on_sale) {
              totalPrice += this.shoppingCartList[findProductIndex].originalPrice * this.shoppingCartList[findProductIndex].buyCount
            } else {
              totalPrice += this.shoppingCartList[findProductIndex].price * this.shoppingCartList[findProductIndex].buyCount
            }
          }
        })
        console.log(totalPrice)
        if (totalPrice >= this.discount[0].minAmount) {

          this.discount[0].items1.map(async (items, index) => {
            const findProductIndex = await this.shoppingCartList.findIndex((element) => element.id === items.id);
            if (findProductIndex > -1) {
              if (!this.shoppingCartList[findProductIndex].on_sale) {
                this.shoppingCartList[findProductIndex].on_sale = true
                this.shoppingCartList[findProductIndex].originalPrice = this.shoppingCartList[findProductIndex].price
                this.shoppingCartList[findProductIndex].price = await this.discountPriceHandler(this.discount[0].discount, this.discount[0].value, this.shoppingCartList[findProductIndex].price)
              }
            }
          })
        } else {
          this.discount[0].items1.map(async (items, index) => {
            const findProductIndex = await this.shoppingCartList.findIndex((element) => element.id === items.id);
            if (findProductIndex > -1) {
              if (this.shoppingCartList[findProductIndex].on_sale) {
                this.shoppingCartList[findProductIndex].on_sale = false
                //this.shoppingCartList[findProductIndex].originalPrice = this.shoppingCartList[findProductIndex].price
                this.shoppingCartList[findProductIndex].price = this.shoppingCartList[findProductIndex].originalPrice
              }
            }
          })
        }
      }
    }
  }

  @action async discountPriceHandler(type, value, price) {
    var itemPrice = 0
    switch (type) {
      case 0:
        itemPrice = price * (100 - value) / 100
        console.log(itemPrice)
        return itemPrice
        break;

      case 1:
        itemPrice = price - value
        console.log(itemPrice)
        return itemPrice

      case 2:
        itemPrice = value
        console.log(itemPrice)
        return itemPrice
      default:
        break;
    }
  }

  @action
  async cancelOrderRequest(id, reasonData, self) {
    this.loading = true;
    var url = api.order + id + "/void-req/";
    var data = {
      reason: reasonData
    }
    console.log(data)
    try {
      const response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });
      this.loading = false;
      self.refs.toast.show(this.text.sentRequest);
    } catch (error) {
      this.loading = false;
      if (error.response.data[0] == "req_exists") {
        self.refs.toast.show(this.text.alreadyRequest);

      } else {
        self.refs.toast.show(this.text.sendRequestFail);
      }
      console.log(error.response);
    }
  }

  @action
  async cancelOrderRequestWithNotPay(id, self) {
    this.loading = true;
    var url = api.order + id + "/cancel/";
    var data = {

    }
    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.loading = false;
      self.refs.toast.show(this.text.sentRequest);
    } catch (error) {
      this.loading = false;
      if (error.response.data[0] == "invalid_order_status") {
        self.refs.toast.show(this.text.alreadyRequest);

      } else {
        self.refs.toast.show(this.text.sendRequestFail);
      }
      console.log(error.response);
    }
  }

  @action
  async getShoppingCart() {
    this.shoppingCartIds = [];
    this.shoppingCartList = [];
    console.log(this.token);
    this.loading = 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.loading = false;

      console.log(response.data);
      // this.shoppingCartIds = response.data;
      // await response.data.map((items, index) => {
      //   items.selected = false;
      //   items.buyCount = 1;
      //   this.favorite.push(items);
      // });
      var products = await this.productPriceHandler(response.data, true)

      transaction(() => {
        if (products.length > 0) {
          products.map((items, index) => {
            items.item.selected = false;
            items.item.buyCount = items.qty;
            this.shoppingCartList.push(items.item);
            var ids = {
              itemId: items.item.id,
              qty: items.qty,
            };
            this.shoppingCartIds.push(ids);
          });
        }
      });
      console.log(this.shoppingCartList)
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

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

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

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

    this.loading = 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.loading = false;
      self.refs.toast.show('已更改數量');
      this.shoppingCartList[index].buyCount = itemsQty;
      this.discountTypeZeroHandler()
    } catch (error) {
      this.loading = 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);
    }
  }

  @action
  async addSingleItemToShoppingCart(items, self) {
    if (this.loginUserData != null) {
      if (items.inventory > 0) {
        var itemIndex = await this.shoppingCartList.findIndex(
          element => element.id === items.id,
        );
        var shoppcartIdIndex = await this.shoppingCartIds.findIndex(
          element => element.itemId === items.id,
        );
        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 = {
            itemId: items.id,
            qty: items.buyCount,
          };
          this.shoppingCartIds.push(data);
        }

        this.addShoppingCart(self);
      } else {
        self.refs.toast.show(this.text.outOfStock)
      }
    } else {
      Alert.alert(
        this.text.pleaseLogin,
        this.text.pleaseLogin,
        [
          {
            text: this.text.cancel,
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          { text: this.text.login, onPress: () => self.props.navigation.navigate('Signin') },
        ],
        { cancelable: false },
      );
    }
  }

  @action
  async addRedeemItemAction(data, self) {
    console.log('Redeem')
    var itemIndex = await this.shoppingCartList.findIndex(
      element => element.id === data.id,
    );
    if (itemIndex != -1) {
      this.shoppingCartList[itemIndex].buyCount = 1
      this.shoppingCartList[itemIndex].redeem = true
      this.shoppingCartList[itemIndex].on_sale = true
      this.shoppingCartList[itemIndex].originalPrice = this.shoppingCartList[itemIndex].price
      this.shoppingCartList[itemIndex].price = this.discount[0].value
    } else {
      data.buyCount = 1
      data.redeem = true
      data.on_sale = true
      data.originalPrice = data.price
      data.price = this.discount[0].value
      this.shoppingCartList.push(data);
    }
    self.addItemsVisable = false
  }

  @action
  async addShoppingCart(self) {
    this.loading = 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.loading = false;
      self.refs.toast.show('已加入購物車');
      console.log(response)
    } catch (error) {
      this.loading = 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);
    }
  }

  @action
  async getCategories() {
    this.loading = 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.loading = false;
      this.splash = true;
      await transaction(() => {
        Promise.all(response.data.content.map(async (items, index) => {
          if (items.status == 'A') {
            await this.allCategories.push(items)
          }
        })
        )

        this.allCategories = this.allCategories.sort((a, b) =>
          a.ordering > b.ordering ? 1 : b.ordering > a.ordering ? -1 : 0,
        );
      })

      //this.getRandamFavourite(categories.length);

      this.getbanners();
      this.getNews();
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async getNews() {
    this.news = [];
    var url = api.news;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 20000,
      });
      console.log(response);
      this.news = response.data.content;
    } catch (error) {
      this.loading = false;
      console.log(error);
      return 0;
    }
  }

  @action
  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;
    }
  }
  @action
  async getAllTag() {
    var page = 1;
    this.tagForSearch = [];

    while ((await this.getTags(page)) == 100) {
      page += 1;
    }
    console.log(this.tagForSearch);
  }
  @action
  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');
    }
  }
  @action
  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');
    }
  }

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

  @action
  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.loading = 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.loading = false;
      console.log(response);
      self.refs.toast.show('刪除成功');
      this.shoppingCartIds = delectShoppingCartIds;
      this.shoppingCartList = deletedShoppingcartList;
      self.deleteAble = false;
      self.checkItems1Exist()
      this.discountTypeZeroHandler()
      if (this.discount.length > 0) {
        if (this.discount[0].type == 1) {
          //herehere
          var item1index = -1
          await this.discount[0].items1.map(async (items, index) => {
            item1index = await this.shoppingCartList.findIndex((element) => element.id === items.id);
          })
          if (item1index == -1) {
            self.init()
          }
        }
      }
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('刪除失敗');

      console.log(error.response);
    }

    //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: 5000,
    //   });
    //   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);
    // }
  }

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

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

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

      console.log(error.response);
    }
  }

  @action
  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: 5000,
      });

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

  @action
  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: 5000,
      });

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

  @action
  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: 5000,
      });

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

  @action
  async deleCreditCard(self) {
    this.loading = 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.loading = false;
      this.addedCard = false;
      console.log(response);
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }

  @action
  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: 5000,
      });
      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(JSON.stringify(e));
      //  self.refs.toast.show(e.message);
    }
  }

  @action
  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('此産品己在我的清單');
    }
  }

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

  @action
  async getProductById(which) {
    this.loading = true;
    var url = api.getAllProducts;
    var ids = [];
    var productsId = '';
    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.item.id);
        if (index > 0) {
          productsId += '&id=' + items.item.id;
        } else {
          productsId += 'id=' + items.item.id;
        }
      });
    }
    console.log(ids);
    console.log(productsId);
    url = url + '?' + productsId;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },

        params: {
          //  'id[]': ids
          //id: productsId,
        },
        // paramsSerializer: function(params) {
        //   return qs.stringify(params, {arrayFormat: 'repeat'});
        // },
        timeout: 5000,
      });
      this.loading = 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.loading = false;
      console.log(error);
    }
  }

  @action
  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: 5000,
      });
      this.loading = false;

      console.log(response.data);

      if (response.data.length > 0) {
        // this.favoriteIds = response.data;
        // this.getProductById(false);
        var products = await this.productPriceHandler(response.data, true)

        await products.map(async (items, index) => {
          items.item.buyCount = 1;
          items.item.selected = false;
          this.favorite.push(items.item);
        });
      }
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async deleteFavourite(deleteIndex, deleteId, self) {
    console.log(deleteIndex);

    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: 5000,
      });
      this.loading = 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.loading = false;
      self.refs.toast.show('刪除失敗');
      console.log(error);
    }
  }
  @action
  async addFavouritePost(data, self) {
    if (this.loginUserData != null) {
      var uploadData = {
        itemId: '' + data.id,
      };
      console.log(uploadData);
      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: 5000,
        });
        this.loading = 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.loading = false;
        self.refs.toast.show('加入失敗');
        console.log(error.response);
      }
    } else {
      Alert.alert(
        this.text.pleaseLogin,
        this.text.pleaseLogin,
        [
          {
            text: this.text.cancel,
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          { text: this.text.login, onPress: () => self.props.navigation.navigate('Signin') },
        ],
        { cancelable: false },
      );
    }
  }

  @action
  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)];
  }

  @action
  async getRandamFavourite(catIndex) {
    this.youMayLikeList = [];
    var randomNumbers = [];
    for (var i = 0; i < 2; i++) {
      // randomNumbers.push(Math.random() * (catIndex - 0) + 0);
      randomNumbers.push(Math.floor(Math.random() * catIndex) + 0);
    }
    console.log(catIndex);
    console.log(randomNumbers);
    randomNumbers.map((value, index) => {
      this.getRandamFavouriteResult(this.mainCategories[value].id);
    });
  }

  @action
  async getRandamFavouriteResult(categoryID) {
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { category: categoryID, page_no: 1, page_size: 15 },
        timeout: 20000,
      });
      console.log(response);
      response.data.map((items, index) => {
        this.youMayLikeList.push(items);
      });
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async getcategoriesProducts(categoryID, self) {
    this.loading = 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.loading = false;
      this.allProducts = await this.productPriceHandler(response.data.content, false);
      // self.productItems = [...this.allProducts];
      var newArray = [...this.allProducts];
      self.productItems = newArray.sort((a, b) =>
        a.price > b.price ? 1 : b.price > a.price ? -1 : 0,
      );
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async productPriceHandler(products, shoppingCart) {
    console.log(this.loginUserData)

    var newProducts = []
    if (this.loginUserData != null) {
      if (this.loginUserData.data.hasOwnProperty('shoppingGroup')) {
        if (shoppingCart) {
          await products.map(async (items, index) => {
            if (items.item.clazzPrices.length > 0) {
              items.item.clazzPrices.map(async (price, priceIndex) => {
                if (price.clazz == this.loginUserData.data.shoppingGroup.priceClazz) {
                  items.item.price = price.price
                }
              })
              if (items.item.status == 'A') {

                await newProducts.push(items)
              }
            } else {
              if (items.item.status == 'A') {

                await newProducts.push(items)
              }
            }
          })
        } else {
          await products.map(async (items, index) => {
            if (items.clazzPrices.length > 0) {
              items.clazzPrices.map(async (price, priceIndex) => {
                if (price.clazz == this.loginUserData.data.shoppingGroup.priceClazz) {
                  items.price = price.price
                }
              })
              if (items.status == 'A') {

                await newProducts.push(items)
              }
            } else {
              if (items.status == 'A') {

                await newProducts.push(items)
              }
            }
          })
        } console.log(newProducts)
        return newProducts
      } else {
        await products.map(async (items, index) => {

          if (shoppingCart) {
            if (items.item.status == 'A') {

              await newProducts.push(items)
            }
          } else {
            if (items.status == 'A') {

              await newProducts.push(items)
            }
          }
        })

        return newProducts
      }
    } else {
      await products.map(async (items, index) => {
        if (items.status == 'A') {

          await newProducts.push(items)
        }
      })
      return newProducts
    }
  }

  @action
  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.loading = false;
      console.log(error);
      return 0;
    }
  }

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

  @action
  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: 100 },
        timeout: 5000,
      });
      this.loading = 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.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);
    }
  }

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

  @action
  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.content;
      response.data.content.map((item, index) => {
        if (item.status == 'A') {
          this.banners.push(item)
        }
      })
    } catch (error) {
      this.loading = false;
      console.log(error);
      return 0;
    }
  }

  @action
  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;
  }

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

  @action
  async postOrder(data, 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: 5000,
      });
      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);
      // }

      await this.startAnimate();
      setTimeout(async function () {
        self.payDisable = false;
        self.coupon2Index = null
        // self.props.navigation.navigate('BuyHistory');
        await self.props.navigation.replace('Order', {
          order: false,
          data: _.cloneDeep(response.data),
        })
      }, 1000);
    } catch (error) {
      this.loading = false;
      self.refs.toast.show('下單失敗');
      console.log(error.response);
    }
  }

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

  @action
  async SearchTag(value, self) {
    this.loading = true;
    var url = api.getAllProducts;
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        params: { keyword: value },
        timeout: 20000,
      });
      this.loading = false;
      console.log(response);
      this.allProducts = await this.productPriceHandler(response.data.content, false);
      // self.productItems = [...this.allProducts];
      var newArray = [...this.allProducts];
      self.productItems = newArray.sort((a, b) =>
        a.price > b.price ? 1 : b.price > a.price ? -1 : 0,
      );
      console.log()
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }


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

  @action
  convertLocalIdentifierToAssetLibrary(localIdentifier, ext) {
    const hash = localIdentifier.split('/')[0];
    return `assets-library://asset/asset.${ext}?id=${hash}&ext=${ext}`;
    //return 'photos://asset/' + localIdentifier;
  }

  @action
  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);
    }
  }
  @action
  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,
            ),
          },
        ];
      }
    }
  }

  @action
  async getShipppingMethods(self) {
    this.loading = 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.loading = false;
      this.shippingMethods = response.data;
      self.shippingPriceReturn();
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async bindMobile(data, self) {
    this.loading = true;
    var requestURL = api.bindMobile;
    console.log(data)

    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.countryCode = 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.response);
    }
  }

  @action
  async checkMember(data, self) {
    this.loading = true;
    var requestURL = api.check;
    var checkData = {
      email: data.email,
      mobile: data.mobile,
      countryCode: data.countryCode,
    };
    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);
    }
  }

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

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

  @action
  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: 5000,
      });
      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('評論失敗，網絡問題');
    }
  }

  @action
  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: 5000,
      });

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

  @action
  async getComment(productId, pageValue, self) {
    this.loading = true;
    var url = api.item + productId + "/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: 5000,
      });
      console.log(pageValue)
      console.log(response);
      this.loading = false;
      var newArray = [];
      response.data.content.map((items, index) => {
        newArray.push(_.cloneDeep(items));
      });
      if (response.data.totalPages > 1) {
        self.productComment = self.productComment.concat(response.data.content);
      } else {
        if (pageValue == 1) {
          self.productComment = self.productComment.concat(response.data.content);
        }
      }
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async getOrders() {
    this.orderList = [];
    this.loading = 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}`),
        },
        params: {
          page: 1,
          per_page: 20,
          orderby: 'date',
        },
        paramsSerializer: params => {
          return qs.stringify(params);
        },
        timeout: 5000,
      });

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

  getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
      console.log(i)
      if (!obj.hasOwnProperty(i)) continue;
      if (typeof obj[i] == 'object') {
        objects = objects.concat(this.getObjects(obj[i], key, val));
      } else
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
          objects.push(obj);
        } else if (obj[i] == val && key == '') {
          //only add if the object is not already in the array
          if (objects.lastIndexOf(obj) == -1) {
            objects.push(obj);
          }
        }
    }
    return objects;
  }

  @action
  async getRegions() {

    this.regions = [];
    // this.loading = 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);
      // console.log(this.getObjects(response.data.content, 'id', 1))
      //  this.loading = false;
      this.regions = await response.data.content.filter(e => e.status == "A");
      console.log(this.regions)
      console.log(this.regions.filter(e => !e.hasOwnProperty('parent')))
      var level0 = await this.regions.filter(e => !e.hasOwnProperty('parent'))
      console.log(level0)
      level0.forEach(e => {
        this.find_children(this.regions, e)
      })

      this.regionsArray = _.cloneDeep(this.regions)
      this.regionsArray = this.regionsArray.filter(e => !e.hasOwnProperty('parent'))

    } catch (error) {
      //   this.loading = false;
      console.log(error);
    }
  }
  find_children(arr, obj) {
    try {
      var children = arr.filter(e => e.hasOwnProperty('parent') && e.parent.id == obj.id);
      if (children.length) {
        obj.children = children;
        children.forEach(child => {
          this.find_children(arr, child);
        });
      }
    } catch (e) {
      console.log(e)
    }
  }


  @action
  async getAddress() {
    this.getRegions();
    this.addresses = [];
    this.loading = 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.loading = false;
      this.addresses = response.data;
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  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: 5000,
      });

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

  @action 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.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.token,
        device: data.device,
      };
      this.saveDataToLocal('logindata', saveData);

      self.props.navigation.popToTop();

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

  @action
  async thirdPartyLogin(data, self, navAction) {
    //  this.loading = true;
    var requestURL = api.thirdPartyLogin;
    data.device = uuid.v4();
    console.log(data)
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      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;
      var userdata = { data: null };
      userdata.data = response.data.member
      this.loginUserData = userdata;
      this.userData = data;
      var saveData = {
        token: response.data.token,
        device: data.device,
      };
      this.saveDataToLocal('logindata', saveData);

      self.props.navigation.popToTop();

      this.token = response.data.token;
      this.uuid = data.device;
      await this.getAddress();
      await this.getShoppingCart();
      await this.notificationInit();
      await this.getCreditCard();
      await this.getShoppingGroup();
      await this.getShippingOrderDate();
      // }
    } catch (e) {
      self.refs.toast.show('Login Fail');
      // this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }
  @action
  async payBycash(id, self) {
    self.payDisable = true;
    this.loading = true;
    var requestURL = api.order + id + '/pay';
    console.log(requestURL);
    var data = {
      paymentMethod: 'cod',
    };
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

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

  @action
  async payByBank(id, imageLink, self) {
    self.payDisable = true;
    this.loading = true;
    var requestURL = api.order + id + '/pay';
    var uploadURL = api.order + id + '/upload-receipt';
    console.log(requestURL);
    var data = {
      paymentMethod: 'bank',
    };
    const date = moment().format('DDMMYYYYssmmhh');
    const fileData = new FormData();
    fileData.append('file', {
      uri: imageLink,
      name: 'bank' + date + '.png',
      type: 'image/png',
    });
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },

        timeout: 5000,
      });

      console.log(response);

      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.loading = false;
        console.log(uploadImageResponse);
        this.startAnimate();
        setTimeout(function () {
          self.payDisable = false;
          self.props.navigation.navigate('BuyHistory');
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.log(error.response)
      }


    } catch (e) {
      self.refs.toast.show('下單失敗');
      console.log(e.response);
      this.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }

  @action
  async uploadBankReceipt(id, imageLink, self) {
    this.loading = true;
    var uploadURL = api.order + id + '/upload-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.loading = false;
      console.log(uploadImageResponse);
      this.startAnimate();
      setTimeout(function () {
        self.payDisable = false;
        self.props.navigation.navigate('BuyHistory');
      }, 1000);
    } catch (error) {
      this.loading = false;
      console.log(error.response)
    }

  }
  @action
  async payByCreditCard(id, 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,
      paymentMethod: 'stripe',
      creditcard: this.creditCardinfo.id,
      //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.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);
    }
  }

  @action
  async orderProducts() { }

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

    console.log('Done.');
  }

  @action
  async getFcmToken() {
    messaging()
      .getToken()
      .then(token => {
        console.log(token);
        if (this.logined) {
          this.postFcmToken(token);
        }
      });
  }
  @action
  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();
      }
    }
  }

  @action 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');
    }
  }

  @action
  async postFcmToken(fcmtoken) {

    var url = api.fcmToken;
    var data = {
      memberId: this.loginUserData.data.id,
      token: fcmtoken,
    };
    try {
      const response = await axios.put(url, data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
        timeout: 5000,
      });

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

      console.log(error);
    }
  }

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

  @action
  async getDiscount() {
    this.discount = [];
    var url = api.discount;
    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);
      this.loading = false;
      await response.data.content.map((items, index) => {
        if (moment() > moment(items.start) && items.status == 'A') {
          if (items.end != null) {
            console.log('date: ' + moment(items.end).format('DD/MM/YYYY'));
            if (moment() < moment(items.end)) {
              this.discount.push(items);
            }
          } else {
            this.discount.push(items);
          }
        }
      });
      console.log(this.discount);
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  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: 5000,
      });
      console.log(response);
      this.loading = false;
      await response.data.content.map((items, index) => {
        if (items.expiry != null) {
          console.log('date: ' + moment(items.expiry).format('DD/MM/YYYY'));
          if (moment() < moment(items.expiry)) {
            this.coupons.push(items);
          }
        } else {
          this.coupons.push(items);
        }
      });
      console.log(this.coupons);
    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }

  @action
  async loginPost(self, data, nav) {
    data.device = uuid.v4();
    //this.loading = true;
    var url = api.login;
    var loginData = _.cloneDeep(data);
    console.log(loginData);
    try {
      const response = await axios.post(url, loginData, {
        headers: {
          company: 'calihealthylife',
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      //   this.loading = false;
      this.logined = true;
      var userdata = { data: null };
      userdata.data = response.data.member
      this.loginUserData = userdata;
      this.userData = data;
      var saveData = {
        token: response.data.token,
        device: data.device,
      };
      this.saveDataToLocal('logindata', saveData);
      if (nav) {
        self.props.navigation.popToTop();
      }
      console.log(response);
      this.token = response.data.token;
      this.uuid = data.device;
      this.getAddress();
      this.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      this.getShoppingGroup();
      this.getShippingOrderDate();
      //this.getPoints();
    } catch (e) {
      self.refs.toast.show('Login Fail');
      // this.loading = false;
      //connectFail.fail();
      console.log(e.response);

      self.loginUserData = {
        username: '',
        password: '',
      };
    }
  }

  @action
  async getPointsfromUser() {
    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.points = response.data.points;
    } catch (e) {
      //self.refs.toast.show('Login Fail');

      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action
  async getUserData(self, data, nav) {
    this.loading = true;
    var url = api.editAddress;
    console.log(this.uuid);
    console.log(this.token);
    console.log('Basic ' + base64.encode(`${this.uuid}:${this.token}`));
    try {
      const response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Basic ' + base64.encode(`${this.uuid}:${this.token}`),
        },
        timeout: 5000,
      });

      this.loading = false;
      this.logined = true;
      this.loginUserData = response;
      if (nav) {
        self.props.navigation.popToTop();
      }
      console.log(response);
      this.getAddress();
      this.getShoppingCart();
      this.notificationInit();
      this.getCreditCard();
      this.getShoppingGroup();
      this.getShippingOrderDate();
    } catch (e) {
      //self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e.response);
    }
  }

  @action
  async signupPost(self, data) {
    var jsonData = _.cloneDeep(data);

    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 = {
        email: '852' + data.mobile,
        pwd: data.pwd,
      };
      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;
    }
  }

  @action
  async addAddress(data, self) {
    this.loading = 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.loading = false;
      console.log(response);
      //this.loginUserData.data.address = response.data.address;
      this.addresses.push(response.data);
      this.getAddress()
      this.getShoppingGroup()
      self.props.navigation.goBack();
    } catch (e) {
      console.log(e);
      this.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }

  @action
  async editAddress(data, id, self) {
    this.loading = 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.loading = false;
      console.log(response);
      this.addresses[0] = response.data;
      this.getShoppingGroup()
      self.props.navigation.goBack();
    } catch (e) {
      console.log(e);
      this.loading = false;
      //  self.refs.toast.show(e.response);
    }
  }

  @action
  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: 5000,
      });

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

  @action
  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;
    }
  }

  @action
  async sendsmsVerify(data, self) {
    this.loading = true;
    var requestURL = api.smsVerify;
    console.log(data)
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

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