import { observable, transaction, action, computed } from "mobx";
import api from "./api";
import axios from "axios";
import Toast, { DURATION } from "react-native-easy-toast";
import AsyncStorageHelper from "../config/asyncStorageHelper";
import moment from "moment";
import language from '../config/language'
import { Alert,Platform } from "react-native";
const asyncStorageHelper = new AsyncStorageHelper();
class menu_store {
  @observable menu = [];
  @observable
  date = {
    days: 0,
    hours: 0,
    min: 0,
    sec: 0
  };
  @observable errorMessage = "";
  @observable loading = false;
  @observable flatListWidth = 0;
  @observable selected = false;
  @observable orderHistory = { data: { content: [] } };
  @observable currentOrder = [];
  @observable passOrder = [];
  @observable coupons = {};
  @observable
  cutoffDateTime = new Date();
  @observable
  timestamp = new Date();
  @observable
  menuDetails = {
    id: 0,
    tel: "",
    count: 0,
    price: 0,
    tags: [],
    name: "",
    nameEn: "",
    imageURL: "",
    intro_ch: "",
    intro_en: "",
    restaurant: {
      name: "",
      nameEn: "",
      addrEn: "",
      addr: ""
    }
  };
  orderList = [];
  items = [];
  orderReturn = {};
  pageNo = 1;
  totalPage = 0;
  @observable
  pickupPointId = null;
  @observable
  sharemessage = {}
  couponLabel = []
  //for test
  date1 = new Date(Date.UTC(2018, 9, 31, 3, 0, 0));
  pickupDate = "?date=today";
  constructor() {}

  @action
  async getMenuItem(self) {
    this.selected = false;
    this.loading = true;
    this.pageNo = 1;
    var requestURL = api.getMenu;
    asyncStorageHelper.getData("pickupPointId", pickupPointId => {
      let num = parseInt(pickupPointId);
      this.pickupPointId = num;
      pickupPointId = num.toString();
      requestURL =
        requestURL +
        this.pickupDate +
        "&pick-up-location-id=" +
        pickupPointId.toString();
      console.log("request:" + pickupPointId);
      this.getMenu(self, requestURL, pickupPointId);
    });
  }

  async updateMenu() {
    this.selected = false;
    this.loading = true;
    this.pageNo = 1;
    var requestURL = api.getMenu;
    requestURL =
      requestURL +
      this.pickupDate +
      "&pick-up-location-id=" +
      this.pickupPointId.toString();
    this.getMenuByUpdate(requestURL, this.pickupPointId);
  }

  @action
  async updateMenuByMap(self, id) {
    this.selected = false;
    this.loading = true;
    this.pageNo = 1;
    var requestURL = api.getMenu;
    let num = parseInt(id);
    pickupPointId = num.toString();
    requestURL =
      requestURL +
      this.pickupDate +
      "&pick-up-location-id=" +
      pickupPointId.toString();
    console.log("request:" + pickupPointId);
    self.autoPlaceFocus = false;
    this.getMenu(self, requestURL, num);
  }
  @action
  async getOrder(self, token) {
    try {
      var passOrder = [];
      var currentOrder = [];
      this.loading = true;
     var nowDate = new Date();
     nowDate.setDate(nowDate.getDate()-30)
      //nowDate.format('yyyy-mm-dd')
      console.log(nowDate.toISOString().substring(0, 10))
     apiLink = api.order+'created-start='+nowDate.toISOString().substring(0, 10)
      const response = await axios.get(api.order, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      console.log(response);
      response.data.content.reverse();
      response.data.content.forEach(e => console.log(e.status));
      var content = response.data.content;
      for (var i = 0; i < content.length; i++) {
        if (content[i].status == "P" || content[i].status == "D") {
          currentOrder.push(content[i]);
        } else if (content[i].status == "F" || content[i].status == "V") {
          passOrder.push(content[i]);
        }
      }
      transaction(() => {
        this.passOrder = passOrder;
        this.currentOrder = currentOrder;
        this.loading = false;
        this.orderHistory = response;
      });
    } catch (error) {
      this.loading = false;
      console.log(error.response);
    }
  }

  @action
  async goOrderDetail(data, self) {
    this.loading = true;
    try {
      this.loading = false;
      const response = await axios.get(api.sysTime, { timeout: 5000 });
      console.log(response);
      var momentDate = moment(response.data.timestamp);
      var timestamp = momentDate.toDate();
      
      var momentCancelDate = moment(data.items[0].cancellation)
      var cancelDate = momentCancelDate.toDate();
      console.log(timestamp)
      console.log(cancelDate);

      if (timestamp >= cancelDate) {
        self.go(data, true);
      } else {
        console.log("false");
        self.go(data, false);
      }
    } catch (error) {
      this.loading = false;
      console.log(error);

      Alert.alert("", error.response.data, [
        { text: "Ok", onPress: () => console.log("Cancel") }
      ]);
    }
  }

  @action
  async getMenuByUpdate(requestURL, id) {
    this.loading = true;
    try {
      console.log("request:" + requestURL);
      const response = await axios.get(requestURL, { timeout: 5000 });
      response.data.content.forEach(e => (e.count = 0));
      var newMenu = this.menuHandler(response, id);
      transaction(() => {
        this.menu = newMenu;
        this.totalPage = response.totalPages;
        this.loading = false;
      });
      // self.navigatieAction('menu')
      console.log(this.menu);
    } catch (error) {
      this.loading = false;
      console.log(error.response);
      //  self.refs.toast.show(error);
    }
  }

  @action
  async getMenu(self, requestURL, id) {
    try {
      console.log("request:" + requestURL);
      const response = await axios.get(requestURL, { timeout: 5000 });
      this.sharemessage = response.data.promotions;
      //language.en.referFriendContent = response.data.promotions[0].contentEn
     // language.zh.referFriendContent = response.data.promotions[0].content
      //console.log(language.en.referFriendContent)
      response.data.content.forEach(e => (e.count = 0));
      console.log(response);
      var newMenu = this.menuHandler(response, id);
      transaction(() => {
        this.menu = newMenu;
        this.totalPage = response.totalPages;
        this.loading = false;
      });
      self.navigatieAction("menu");
      console.log(response);
    } catch (error) {
      this.loading = false;
      console.log(error);
      self.refs.toast.show(error);
    }
  }
  @action
  menuHandler(menu, id) {
    console.log(menu.data.content);
    var momentDate = moment(menu.data.timestamp);
    var timestamp = momentDate.toDate();
    this.timestamp = timestamp;
    var newContent = [];
    if (menu.data.content.length <= 0) {
      return menu;
    } else {
      for (var i = 0; i < menu.data.content.length; i++) {
        var index = menu.data.content[i].locations.findIndex(
          x => x.location.id == id
        );
        var momentOrderEndDate = moment(
          menu.data.content[i].locations[index].orderEnd
        );
        var orderEndDate = momentOrderEndDate.toDate();
        console.log(timestamp.getDate() + "  " + orderEndDate.getDate());
        if (timestamp < orderEndDate) {
          if (timestamp.getHours() < orderEndDate.getHours()) {
            console.log(timestamp.getUTCDate()+"   "+orderEndDate.getUTCDate())
            if (timestamp.getDate() == orderEndDate.getDate()) {
              newContent.push(menu.data.content[i]);
            }
          } else {
            if (timestamp.getDate() < orderEndDate.getDate()) {
              newContent.push(menu.data.content[i]);
            }
          }
        }
      }
      console.log(newContent);
      if (newContent.length > 0) {
        menu.data.content = newContent;
        var indexOfLocation = newContent[0].locations.findIndex(
          x => x.location.id == id
        );
        var momentCutoffDateTime = moment(
          newContent[0].locations[indexOfLocation].orderEnd
        );
        this.cutoffDateTime = momentCutoffDateTime.toDate();
        console.log(this.cutoffDateTime);
      } else {
        var indexOfLocation = menu.data.content[0].locations.findIndex(
          x => x.location.id == id
        );
        var momentCutoffDateTime = moment(
          menu.data.content[0].locations[indexOfLocation].orderEnd
        );
        this.cutoffDateTime = momentCutoffDateTime.toDate();
        menu.data.content = newContent;
        console.log(this.cutoffDateTime);
      }

      // console.log(this.cutoffDateTime)
      return menu;
    }
  }
  @action
  async menuloadmore(self) {
    this.loading = true;
    try {
      const requestURL =
        api.getMenu + "?page_no=" + toString(this.pageNo) + "&page_size=10";
      const response = await axios.get(requestURL, { timeout: 5000 });
      response.data.content.forEach(e => (e.count = 0));
      transaction(() => {
        //this.menu.content = this.menu.content.concat(response.content);
        this.loading = false;
      });

      console.log(response);
    } catch (error) {
      this.loading = false;
      console.log(error);
      self.refs.toast.show(error);
    }
  }

  @action
  async order(token, data, self) {
    this.loading = true;
    var requestURL = api.order;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      this.loading = false;
      console.log(this.loading);
      console.log(response);
      this.orderReturn = response;
      setTimeout(function() {
        self.pay();
      }, 200);
    } catch (e) {
      this.loading = false;
      self.refs.toast.show(e.response.data);
      console.log(e)
    }
  }

  @action
  async cancelOrder(token) {
    console.log(token);
    var requestURL =
      "http://takeawayapp.nirons.com:8080/order/" +
      this.orderReturn.data.id +
      "/cancel/";
    try {
      const response = await axios.put(requestURL, null, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      console.log(response);
    } catch (e) {
      console.log(e.response);
    }
  }

  @action
  async voidOrder(token, id, self) {
    this.loading = true;
    var requestURL =
      "http://takeawayapp.nirons.com:8080/order/" + id + "/void/";
    console.log(requestURL);
    console.log(token);
    try {
      const response = await axios.put(requestURL, null, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      this.loading = false;
      console.log(response);
      self.back();
    } catch (e) {
      this.loading = false;
      console.log(e.response);
      self.refs.toast.show(e.response.data[0]);
    }
  }

  @action
  async userCoupon(self,token,check){
    this.loading = true
    var requestURL = api.coupon
    try {
      const response = await axios.get(requestURL, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      this.loading = false
      this.couponLabel = []
      response.data.content.forEach(item => {
        if (item.used) {
          var value = {value:item.id}
             // this.couponLabel.push(value)
        } else {
          if (item.hasOwnProperty("expiry")) {
            var nowDatemoment = moment(response.data.timestamp);
            var nowDate = nowDatemoment.toDate();
            var expiryDatemoment = moment(item.expiry);
            var expiryDate = expiryDatemoment.toDate();
            if (nowDate < expiryDate) {
             var value = {value:item.id}
              this.couponLabel.push(value)
            } else {
            
            }
          } else {
           
          }
        }
      });
      this.coupons = response
      console.log('userCoupon')
      if(!check){
      self.navigatieAction("ConfirmOrder");
      }else{
        self.navigatieAction("myCoupons");
      }
      console.log(response);
    } catch (e) {
      this.loading = false
      console.log(e.response);
      // self.refs.toast.show(e.response.data)
    }
  }

  @action
  async coupon(token, self, coupon) {
    var requestURL = api.coupon + coupon;
    console.log("token: " + token + "  coupon: " + coupon);
    var data = {};
    try {
      const response = await axios.get(requestURL, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      console.log(response);
      self.discountAction(response.data);
    } catch (e) {
      console.log(e.response);
      // self.refs.toast.show(e.response.data)
    }
  }

  @action
  async pay(token, self, creditCardId) {
    this.loading = true;
    let data = { creditCardId: creditCardId };
    console.log(data);
    var requestURL =
      "http://takeawayapp.nirons.com:8080/order/" +
      this.orderReturn.data.id +
      "/pay/";
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      this.loading = false;
      console.log(response);
      if(Platform.OS === 'ios'){
        self.navigatieAction("myOrders");
      }else{
      self.navigatieAction("menu");
      }
    } catch (e) {
      this.loading = false;
      console.log(e.response);
      self.refs.toast.show(e.response.data);
    }
  }

  @action
  getCount(id) {
    index = this.menu.data.content.findIndex(obj => obj.id == id);
    return this.menu.data.content[index].count;
  }

  @action
  addCount(id) {
    index = this.menu.data.content.findIndex(obj => obj.id == id);
    this.menu.data.content[index].count += 1;
    this.check();
  }

  @action
  sumCount(id) {
    index = this.menu.data.content.findIndex(obj => obj.id == id);
    if (this.menu.data.content[index].count > 0)
      this.menu.data.content[index].count -= 1;
    this.check();
  }

  @action
  check() {
    var index = this.menu.data.content.findIndex(obj => obj.count > 0);
    if (index != -1) {
      this.selected = true;
    } else {
      this.selected = false;
    }
  }

  @action
  cancel() {
    this.menu.data.content.forEach(e => (e.count = 0));
    this.selected = false;
  }



  @action
  getOrderedItems(self,token) {
    this.orderList = [];
    this.items = [];
    for (var i = 0; i < this.menu.data.content.length; i++) {
      if (this.menu.data.content[i].count > 0) {
        this.orderList.push(this.menu.data.content[i]);
        var data = {
          menu: {
            id: this.menu.data.content[i].id
          },
          qty: this.menu.data.content[i].count
        };
        this.items.push(data);
      }
    }
    this.userCoupon(self,token,false)
   // self.navigatieAction("ConfirmOrder");
    console.log(this.orderList);
  }

  @action
  cleanAll() {
    transaction(() => {
      this.menu.data.content.forEach(e => (e.count = 0));
      this.selected = false;
    });
  }

  @computed get totalMoney() {
    let money = 0;
    this.menu.data.content.forEach(e => (money += e.price * e.count));
    return money;
  }
}

const menuStore = new menu_store();

export default menuStore;
