import { observable, action, runInAction, toJS } from "mobx";
import { fetchJSON } from '@/utils/request';
import * as Skeleton from '@/stores/Skeleton';
import { HOST_NAME } from '@/utils/common';

class CityStore {
    tourdataShouldUpdate = false;
    @observable cityInfo = Skeleton.cityInfo;
    @observable tourObj = Skeleton.tourObj;
    @observable cityTourList = [];
    @observable CityList = { 'Popular China Destinations': [], 'Southest Asia': [] };
    @observable searchResult = [];
    @observable searchKeyword = '';
    @observable cityCategory = [];
    @observable activeTab = 0;
    @observable searching = false;
    constructor(appStore) {
        this.appStore = appStore;
        this.getCityList();
    }
    @action getCategory(cityName) {
        this.cityCategory = [];
        if (this.appStore.getLocal(`${cityName.toLowerCase()}-sublist`) !== null) {
            this.cityCategory = JSON.parse(this.appStore.getLocal(`${cityName.toLowerCase()}-sublist`));
            this.activeTab = 0;
            this.getCategoryItems(this.cityCategory[this.activeTab], this.activeTab);
        }
    }
    @action getCategoryItems(cat, activeTab) {
        this.cityTourList = [];
        this.activeTab = activeTab;
        cat.items.map(a => {
            runInAction(() => {
                if (this.appStore.getStorage(a) !== null) {
                    this.cityTourList.push(JSON.parse(this.appStore.getStorage(a)));
                    return this.cityTourList;
                }
            })
            return true;
        })
    }
    @action setCity(cityName) {
        if (cityName === '') {
            return false;
        }
        this.getCity(cityName.toLowerCase()).then(() => {
            runInAction(() => {
                this.getCategory(cityName.toLowerCase());
            })
        });
    }
    @action getCityList() {
        return new Promise((resolve, reject) => {
            // 文件名不含其他字符
            const url = HOST_NAME + '/wechat-mp/tour-data/city-list';
            fetchJSON(url).then(json => {
                runInAction(() => {
                    this.appStore.putLocal("CITY_LIST", JSON.stringify(toJS(json)));
                    this.CityList = JSON.parse(this.appStore.getLocal("CITY_LIST"));
                    for (const key in this.CityList) {
                        if (this.CityList.hasOwnProperty(key)) {
                            const element = this.CityList[key];
                            if ( ! Array.isArray(element)) {
                                continue;
                            }
                            element.map(ele => {
                                if (ele.sublist.length > 0) {
                                    return this.appStore.putLocal(`${ele.title}-sublist`, JSON.stringify(toJS(ele.sublist)));
                                }
                                return true;
                            })
                        }
                    }
                });
                resolve(json);
            })
                .catch(e => {
                    reject(e);
                })
        });
    }
    @action getCity(city) {
        let cityAllTour = [];
        return new Promise((resolve, reject) => {
            if (this.appStore.getLocal(`${city.replace(/\W/, '')}-list`) !== null) {
                cityAllTour = JSON.parse(this.appStore.getLocal(`${city.replace(/\W/, '')}-list`));
                this.cityTourList = [];
                if (this.appStore.getStorage(cityAllTour[0]) !== null) {
                    cityAllTour.map(code => {
                        runInAction(() => {
                            this.cityTourList.push(JSON.parse(this.appStore.getStorage(code)));
                        })
                        return true;
                    })
                    return resolve();
                }
            }
            if (this.appStore.getLocal(`${city.replace(/\W/, '')}-sublist`) !== null) {
                cityAllTour = JSON.parse(this.appStore.getLocal(`${city.replace(/\W/, '')}-sublist`));
                if (this.appStore.getStorage(cityAllTour[0].items[0]) !== null) {
                    return resolve();
                }
            }
            // 文件名不含其他字符
            const url = HOST_NAME + '/wechat-mp/tour-data/' + city.replace(/\W/, '');
            fetchJSON(url).then(json => {
                cityAllTour = [];
                runInAction(() => {
                    json.items.map(tour => {
                        cityAllTour.push(tour.activity.externalId);
                        this.appStore.putStorage(tour.activity.externalId, JSON.stringify(toJS(tour)));
                        return true;
                    })
                    if (json.children.length===0) {
                        this.appStore.putLocal(`${city.replace(/\W/, '')}-list`, JSON.stringify(toJS(cityAllTour)));
                        this.cityTourList = json.items;
                    }
                });
                return resolve();
            });
        });
    }
    @action getTour(city, tourId) {
        if (this.appStore.getStorage(tourId) === null) {
            this.getCity(city)
                .then(() => {
                    runInAction(() => {
                        this.tourObj = toJS(JSON.parse(this.appStore.getStorage(tourId)));
                    })
                });
        } else {
            this.tourObj = toJS(JSON.parse(this.appStore.getStorage(tourId)));
        }
    }
    @action getSearch(search) {
        this.searchKeyword = search;
        const url = HOST_NAME + '/wechat-mp/search-activity?search=' + search;
        this.searching = true;
        fetchJSON(url).then(json => {
            runInAction(() => {
                this.searchResult = json;
            });
        }).finally(() => {
            runInAction(() => {
                this.searching = false;
            })
        })
        if (this.appStore.pathname !== '/search') {
            this.appStore.pushHistory('/search');
        }
    }
    @action resetSearch() {
        this.searchKeyword = '';
        this.searchResult = [];
    }
}
export default CityStore;
