import { observable, runInAction, action } from "mobx";
import CityStore from "@/stores/CityStore";
import UserStore from '@/stores/UserStore';
import BookStore from '@/stores/BookStore';
import CountryStore from '@/stores/CountryStore';
import { fetchJSON } from '@/utils/request';
import { HOST_NAME, getPathPart } from '@/utils/common';
import * as Skeleton from '@/stores/Skeleton';

class AppStore {
    userid=0;
    @observable tourdataShouldUpdate = false;
    @observable userinfo=Skeleton.userinfo;
    @observable selectedMenu;
    @observable pathname;
    @observable activeCityName='';
    @observable pageTitle;
    constructor(history) {
        this.cityStore = new CityStore(this);
        this.userStore = new UserStore(this);
        this.bookStore = new BookStore(this);
        this.countryStore = new CountryStore(this);

        this.history = history;
        this.pathname = history.location.pathname;
        // this.cityIndexPattern = new RegExp('/\/tours\/(?<city>[\w\']*)/');
        // this.cityIndexPattern = /\/tours\/(?<city>[\w']*)/;
        // let parsePath = this.cityIndexPattern.exec(history.location.pathname);
        // this.pageTitle = parsePath === null ? 'My Bookings' : parsePath.groups.city.toUpperCase();
        // this.activeCityName = parsePath === null ? '' : parsePath.groups.city.toUpperCase();
        let parsePath = getPathPart(history.location.pathname, 2);
        this.pageTitle = (parsePath==='' || getPathPart(history.location.pathname, 1)!=='tours') ? 'My Bookings' : parsePath.toUpperCase();
        this.activeCityName = (parsePath==='' || getPathPart(history.location.pathname, 1)!=='tours') ? '' : parsePath.toUpperCase();
        if (this.getLocal('APP_USER_ID') !== null) {
            this.userid = parseInt(this.getLocal('APP_USER_ID'), 10);
            this.userinfo = JSON.parse(this.getLocal('APP_USER_INFO'));
        }
        this.refreshLogin(history.location.search, history.location.pathname);
        // this.noAccount(history.location);
        history.listen((location, actionName) => {
            this.pathname = location.pathname;
            this.noAccount(location);
            parsePath = getPathPart(location.pathname, 2);
            runInAction(() => {
                this.selectedMenu = location.pathname;
                // this.pageTitle = parsePath === null ? 'My Bookings' : parsePath.groups.city.toUpperCase();
                this.pageTitle = (parsePath==='' || getPathPart(history.location.pathname, 1)!=='tours') ? 'My Bookings' : parsePath.toUpperCase();
                // console.log(parsePath)
                if (parsePath !== '' && getPathPart(location.pathname, 1)==='tours') {
                    this.activeCityName = parsePath.toUpperCase();
                    this.cityStore.setCity(parsePath)
                }
            });
        });
    }
    @action pushHistory(route) {
        this.pathname = route;
        this.history.push(route);
    }
    @action noAccount(location) {
        if (undefined === this.userid
            && true === /\/account\.*/.test(location.pathname)
            && "" === location.search
        ) {
            this.pushHistory('/');
        }
    }
    @action refreshLogin(str, pathname) {
        let params = new URLSearchParams(str);
        let uid = parseInt(params.get("userid"), 10);
        // if (this.userid === undefined && isNaN(uid) === true && /MicroMessenger/i.test(navigator.userAgent)) {
            // console.log('redirect', location)
            // return;
            // return this.userid = 0;
            // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7e605820faf98a05&redirect_uri=http%3A%2F%2Ftrippest.mycht.cn%2Fapi%2Findex.php%2Fwechat-mp%2Flogin-now%2Ftrippest%3Fl%3D' + encodeURIComponent(pathname) + '&response_type=code&scope=snsapi_userinfo&state=guest#wechat_redirect';
            // window.location = 'http://localhost/api/index.php/wechat-mp/login-now/trippest?state=guest&l='+ encodeURIComponent(pathname) ;
            // return false;
        // }
        this.userid = isNaN(uid) ? 0 : uid;
        str = str || '?userid=' + this.userid;
        if (str !== '' && undefined !== this.userid) {
        // if (this.userid !== undefined) {
            // if (this.getStorage('APP_USER_ID') === null) {
            const url = HOST_NAME + '/wechat-mp/page-login/trippest' + str;
            fetchJSON(url).then(json => {
                runInAction(() => {
                    json.isWechat = /MicroMessenger/i.test(navigator.userAgent);
                    this.login(json);
                })
            })
            // }
        }
    }
    @action login(json) {
        this.putLocal('APP_USER_ID', json.user_id);
        this.putLocal('APP_USER_INFO', JSON.stringify(json));
        this.userid = parseInt(this.getLocal('APP_USER_ID'), 10);
        runInAction(() => {
            this.userinfo = JSON.parse(this.getLocal('APP_USER_INFO'));
        })
    }
    @action goBack() {
        this.history.goBack();
    }
    setDocumentTitle(title) {
        document.title = title;
    }
    clearTourStorage() {
        window.sessionStorage.clear();
    }
    putStorage(key, value) {
        if (window.sessionStorage) {
            const sessionStorage = window.sessionStorage;
            // return sessionStorage.setItem(key, value);
            try {
                return sessionStorage.setItem(key, value);
            } catch (e) {
                return e instanceof DOMException && (
                    // everything except Firefox
                    e.code === 22 ||
                    // Firefox
                    e.code === 1014 ||
                    // test name field too, because code might not be present
                    // everything except Firefox
                    e.name === 'QuotaExceededError' ||
                    // Firefox
                    e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
                    // acknowledge QuotaExceededError only if there's something already stored
                    (sessionStorage && sessionStorage.length !== 0);
            }
        } else {
            console.error('browser not support sessionStorage!');
        }
    }
    getStorage(key) {
        if (window.sessionStorage) {
            const sessionStorage = window.sessionStorage;
            return sessionStorage.getItem(key);
        } else {
            return null;
        }
    }
    putLocal(key, value) {
        if (window.localStorage) {
            const localStorage = window.localStorage;
            return localStorage.setItem(key, value);
        } else {
            console.error('browser not support localStorage!');
        }
    }
    getLocal(key) {
        if (window.localStorage) {
            const localStorage = window.localStorage;
            return localStorage.getItem(key);
        } else {
            return null;
        }
    }
}

export default AppStore;
