import { inject, observer } from "mobx-react"
import { makeAutoObservable, action, observable, transaction, runInAction } from "mobx";
import AsyncStorage from '@react-native-community/async-storage';
import axios from 'axios';
import { Alert, Platform, Animated, Easing, Linking } from 'react-native';
import base64 from 'react-native-base64';
import language from '../services/language';
import moment from 'moment';
import api from '../services/api'
const qs = require('qs');
var _ = require('lodash');
var uuid = require('react-native-uuid');
var underscore = require('underscore');
var RNFS = require('react-native-fs');
import RNFetchBlob from "rn-fetch-blob";
class Stores {
  routerRef;
  animateStatus = {
    progress: new Animated.Value(0),
    show: false,
  };
  splash = false;
  loading = false
  text = language.hk;
  products = [];
  languageSelection = 'hk';
  orderData = [];
  user = null
  customer = null
  orderRecord = []

  constructor(rootStore) {
    makeAutoObservable(this, {
      routerRef: observable,
      animateStatus: observable,
      splash: observable,
      loading: observable,
      text: observable,
      products: observable,
      languageSelection: observable,
      orderData: observable,
      user: observable,
      customer: observable,
      orderRecord: observable,
    })
  }


  setRouterState = state => {
    this.routerState = state;
  };
   setRouterRef = ref => {
    this.routerRef = ref;
  };

  
  changeLanguage(lang) {

    if (lang == 'en') {

      this.text = language.en;
      this.languageSelection = 'en';
      this.products.lang = 'en'
    } else {

      this.text = language.hk;
      this.languageSelection = 'hk';
      this.products.lang = 'hk'
    }
  }

  async readDownloadImageFiles(url){
    const file=await RNFS.readFile(url);
    console.log(file);
  }
  
  languageHandler(lang, data) {
    if (data != null && data.hasOwnProperty('name')) {
      if (this.languageSelection == 'hk') {

        return data.name
      } else {

        return data.nameEn
      }
    } else {
      return 'N/A'
    }
  }
  
  async login(data, self) {
    this.loading = true
    var url = api.login
    try {
      var response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;


      console.log(response);
      this.user = response.data
      self.props.navigation.navigate('Main')

    } catch (error) {
      this.loading = false;
      console.log(error);
    }
  }
  
  async logout(self) {
    this.user = null
    self.props.navigation.navigate('Login')
  }

  
  async regMember(data, self) {
    this.loading = true
    var url = api.member
    data.birthday = moment(data.birthday).format('YYYY-MM-DD')
    switch (data.age) {
      case '15-20':
        data.age = 0
        break;
      case '21-30':
        data.age = 1
        break;
      case '31-40':
        data.age = 2
        break;
      case 'over 41':
        data.age = 3
        break;
    }
    try {
      var response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': this.user.token
        },
        timeout: 5000,
      });
      this.loading = false;


      console.log(response);
      this.customer = response.data
      self.props.navigation.navigate('Select')

    } catch (error) {
      this.loading = false;
      console.log(error.response);
      self.refs.toast.show(error.response.data[0])
      if (error.response.data[0] == "mobile_exists") {
        this.checkAndLogin('+852' + data.mobile, self)
      }
    }
  }

  
  async getOrder() {
    this.loading = true
    var url = api.order
    try {
      var response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': this.user.token
        },
        timeout: 5000,
      });

      this.loading = false;
      console.log(response)
      this.orderRecord = response.data.content.sort((a, b) => b.created - a.created);

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

    }
  }

  
  clone(data) {
    return JSON.parse(JSON.stringify(data))
  }

  
  currencyFormat(num) {
    return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
    // return num
  }

  
  async editPost(data, additionalItems, orderId, self) {
    var postData = {
      items: []
    }
    await Promise.all(data.map(async (items, index) => {
      this.loading = true;
      var suitObj = {
        qty: items.qty,
        discount: parseInt(items.discount),
        charges: parseInt(items.charges),
        id: items.id,
        optionValues: [],
      }
      await items.options.map(async (item, i) => {
        var optionsData = {
          option: '',
          value: '',
        }
        optionsData.option = item.id,
          optionsData.value = "" + item.value,
          await suitObj.optionValues.push(optionsData)
      })
      await postData.items.push(suitObj)
    }))
    await Promise.all(additionalItems.map(async (addItems, addIndex) => {
      var addObj = {
        id: addItems.id,
        name: addItems.name,
        price: addItems.price,
        qty: addItems.qty,
      }
      await postData.items.push(addObj)
    }))
    console.log(postData)
    var url = api.order + orderId + '/'
    try {
      var response = await axios.put(url, postData, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': this.user.token
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response)
      self.props.navigation.goBack();
      this.orderData = []
      this.getOrder()
    } catch (error) {
      this.loading = false;
      console.log(error.response);

    }
  }

  
  async orderPost(data, additionalItems, self) {
    var postData = {
      member: this.customer.id,
      items: [],
    }
    await data.map(async (items, index) => {
      this.loading = true;
      var suitObj = {
        type: 0,
        qty: items.qty,
        imageFrontData: items.frontImage == null ? '' : items.frontImage.base64,
        imageBackData: items.backImage == null ? '' : items.backImage.base64,
        discount: parseInt(items.discount),
        charges: parseInt(items.charges),
        suit: items.id,
        optionValues: [],
      }
      await items.options.map(async (item, i) => {
        var optionsData = {
          option: '',
          value: '',
        }
        optionsData.option = item.id,
          optionsData.value = "" + item.value,
          await suitObj.optionValues.push(optionsData)
      })
      await postData.items.push(suitObj)
    })
    await additionalItems.map(async (addItems, addIndex) => {
      var addObj = {
        type: 1,
        name: addItems.name,
        price: (parseInt(addItems.allPrice) * (1 - (parseInt(addItems.discount) / 100))) + parseInt(addItems.charges),
        qty: addItems.qty,
      }
      await postData.items.push(addObj)
    })
    console.log(postData)

    var url = api.order
    try {
      var response = await axios.post(url, postData, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': this.user.token
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response)
      self.props.navigation.navigate('Main');
      this.orderData = []

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

    }
  }

  
  async checkAndLogin(mobile, self) {

    var url = api.check
    var data = {
      email: '',
      mobileWithCountryCode: mobile
    }

    try {
      var response = await axios.post(url, data, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': this.user.token
        },
        timeout: 5000,
      });
      this.loading = false;
      console.log(response)
      if (response.data[mobile] != null) {
        this.customer = response.data[mobile]
        self.props.navigation.navigate('Select')
        console.log(this.customer)
      }

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

    }
  }
  
  async getProductsDetails() {
    this.loading = true;
    var url = api.suit;
    this.products = []
    try {
      var response = await axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });
      this.loading = false;

      await response.data.content.map(async (items, index) => {
        const data = items.options.sort((a, b) => a.previewIndex - b.previewIndex);
        response.data.content[index].options = data
      })
      console.log(response);
      this.products = response.data.content;

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

}
export default new Stores();
