import { observable, action, runInAction } from 'mobx';
import * as req from '@/utils/request';
import { HOST_NAME } from '@/utils/common';

const emptyPassenger = {
    fullname: '',
    idNumber: '',
    ageType: 1,
    idType: 'Passport No.'
};

class BookStore {
    @observable bookReturn = {
        payment_now: 'false',
        paid: 'false',
        total_price: 0
    };
    // @observable bookReturn = {
    //     "paid": "true1",
    //     "show_wxpay": 'true',
    //     "payment_now": "true",
    //     "payment_link": "https://secure.chinahighlights.com/pay/paymentservice/?b3JkZXJfaWQ9c3lzMDAxJnN1YmplY3Q9SXBob25lNiZ0b3RhbF9hbW91bnQ9MC4wMSZjdXJyZW5jeT1VU0QmYm9keT10ZXN0IHdlY2hhdCBwYXkgc3lzMDAxJnJtYl9hbW91bnQ9MC4xJnd4X2FjY291bnQ9dHJpcHBlc3Qmc2lnbj02ODAyNzAwNGIzNTY5ZTA4ZGMxODc4MmFhNjg5OGQ3Yg==",
    //     "web_code": "TP-GZH",
    //     "tour_external_id": "7137P5",
    //     "tour_id": "108038",
    //     "start_date": "2019/10/27",
    //     "adult_num": "1",
    //     "child_num": "0",
    //     "fullname": "ot ot",
    //     "email": "lyt@hainatravel.com",
    //     "mobile": "131 2222 3333",
    //     "passenger": "[{\"fullname\":\"ot ot\",\"idNumber\":\"123456\",\"ageType\":1,\"idType\":\"Passport No.\"}]",
    //     "pickup": "{\"label\":\"I don't need pick-up, I will meet you on location\",\"value\":\"meetingpoint\",\"pickupAddress\":\"Regent Hotel Beijing (Closed to Tian'anmen Square)\",\"hotelAddress\":\"\",\"hotelName\":\"\",\"checkInName\":\"\"}",
    //     "country": "China",
    //     "country_id": "1",
    //     "country_code": "86",
    //     "total_price": "250",
    //     "travelers": "{\"ADULT\":2,\"CHILD\":0,\"INFANT\":0}",
    //     "coli_id": "191025001",
    //     "order_qrcode": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQHA7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyN1Z5Wmw4WHdkbWsxU2ZNa051Y2EAAgQPNsteAwSAOgkA",
    //     "coli_sn": "475000773"
    //     };
    @observable rateId = null;
    @observable price = null;
    @observable rate = {};
    @observable travelers = {};
    @observable totalPrice = 0;
    @observable tieredPrices = null;
    @observable adultNum = 1;
    @observable childNum = 0;
    @observable startDate = null;
    @observable passengerList = [emptyPassenger];
    @observable fullname = '';
    @observable email = '';
    @observable mobile = '';
    @observable requests = '';
    @observable formValidResult = {
        nameError: false,
        nameRequired: '',
        emailError: false,
        emailRequired: '',
        mobileError: false,
        mobileRequired: '',
        pickupError: false,
        pickupRequired: ''
    };
    @observable pickupOption = {
        label: 'I will write down the address',
        value: 'custom',
        pickupAddress: '',
        hotelAddress: '',
        hotelName: '',
        checkInName: ''
    };
    @observable country = {
        name: 'United States',
        id: 3,
        code: 1
    }
    constructor(appStore) {
        this.appStore = appStore;
        // console.log(this.appStore.cityStore.tourObj.activity)
    }
    @action selectCountry(country) {
        this.country.name = country.label;
        this.country.code = country.code;
        this.country.id = country.value;
    }
    @action setDate(date) {
        this.startDate = date;
    }
    @action setTravelers(key, v, amount) {
        this.travelers[key] = v;
        this.travelers[`${key}_p`] = amount;
        this.totalPrice = 0;
        for (const key in this.travelers) {
            if (key === 'person') {
                this.totalPrice = this.travelers[`${key}_p`];
                continue;
            }
            if (this.travelers.hasOwnProperty(`${key}_p`) && Array.isArray(this.travelers[`${key}_p`])) {
                this.travelers[`${key}_tieredPrices`] = this.travelers[`${key}_p`].find(
                    ({ maxPassengersRequired, minPassengersRequired }) => {
                        if (this.travelers[key] === 0) {
                            return (1 === minPassengersRequired || 1 === maxPassengersRequired);
                        } else if (undefined !== maxPassengersRequired) {
                            return (this.travelers[key] >= minPassengersRequired && this.travelers[key] <= maxPassengersRequired);
                        } else {
                            return this.travelers[key] >= minPassengersRequired;
                        }
                    });
                if (this.travelers[`${key}_tieredPrices`] !== undefined
                    && this.travelers[`${key}_tieredPrices`].priceNotFound !== true
                ) {
                    this.totalPrice += this.travelers[key] * this.travelers[`${key}_tieredPrices`].amount;
                }
                continue;
            }
            if (this.travelers.hasOwnProperty(key) && this.travelers.hasOwnProperty(`${key}_p`)
            ) {
                this.totalPrice += this.travelers[key] * this.travelers[`${key}_p`];
            }
        }
    }
    @action setAdultNum(num, init = true) {
        if (init === true && num > this.adultNum) {
            let newPassenger = emptyPassenger;
            this.passengerList.push(newPassenger);
        }
        this.adultNum = num;
    }
    @action setChildNum(num, init = true) {
        if (init === true && num > this.childNum) {
            let newPassenger = emptyPassenger;
            newPassenger.ageType = 2;
            this.passengerList.push(newPassenger);
        }
        this.childNum = num;
    }
    @action addPassenger(ageType) {
        let newPassenger = emptyPassenger;
        newPassenger.ageType = ageType;
        this.passengerList.push(newPassenger);
        // this.calPassengerNum();
    }
    @action deletePassenger(index) {
        this.passengerList.splice(index, 1);
        // this.calPassengerNum();
    }
    @action calPassengerNum() {
        let calAsult = 0;
        let calChild = 0;
        for (let i = 0; i < this.passengerList.length; i++) {
            if (this.passengerList[i].ageType === 1) {
                calAsult += 1;
            } else {
                calChild += 1;
            }
        }
        this.adultNum = calAsult;
        this.childNum = calChild;
    }
    @action fillFullname(value) {
        this.fullname = value;
    }
    @action fillEmail(value) {
        this.email = value;
    }
    @action fillMobile(value) {
        this.mobile = value;
    }
    @action fillRequests(value) {
        this.requests = value;
    }
    @action fillPassengerName(index, value) {
        this.passengerList[index].fullname = value;
    }
    @action fillPassengerId(index, value) {
        this.passengerList[index].idNumber = value;
    }
    @action setRate(value) {
        this.rate = {};
        this.rateId = value;
        this.rate = this.appStore.cityStore.tourObj.activity.rates.find(
            ({ id }) => id === value
        );
        this.price = this.appStore.cityStore.tourObj.pricesByDateRange.rates.find(
            ({ rateId }) => rateId === value
        );
        this.parsePrice();
        Object.assign(this.rate, this.price);
        // console.log(toJS(this.rate));
        // this.adultNum = this.adultNum >= this.rate.maxPerBooking ? this.rate.maxPerBooking
        // : (this.adultNum <= this.rate.minPerBooking ? this.rate.minPerBooking : this.adultNum);
        this.travelers = {}; this.tieredPrices = null;
        this.rate.passengers ? this.rate.passengers.map((p, i) => {
            let tmpkey = ('person' in this.travelers) ? 'person' : p.ticketCategory;
            let tmpV = i === 0 ? this.rate.minPerBooking : 0;
            runInAction(() => {
                const amount = p.price ? p.price.amount : p.tieredPrices;
                this.setTravelers(tmpkey, tmpV, amount);
            });
            return true;
        }) : this.setTravelers('person', this.rate.minPerBooking, this.price.price.amount);
    }
    @action setPickup(value, label = '') {
        this.pickupOption.value = value;
        if (label !== '') {
            this.pickupOption.label = label;
        }
    }
    @action fillPickupAddress(value) {
        this.pickupOption.pickupAddress = value;
    }
    @action fillHotelAddress(value) {
        this.pickupOption.hotelAddress = value;
    }
    @action fillHotelName(value) {
        this.pickupOption.hotelName = value;
    }
    @action fillCheckinName(value) {
        this.pickupOption.checkInName = value;
    }
    @action parsePrice() {
        let priceObj = {};
        if (this.price.price) {
            priceObj.amount = this.price.price;
        }
        if (this.price.passengers) {
            priceObj = this.price.passengers;
            priceObj.map(p => {
                const priceCat = this.appStore.cityStore.tourObj.activity.pricingCategories.find(
                    ({ id }) => id === p.pricingCategoryId
                );
                Object.assign(p, priceCat);
                return true;
            })
        }
    }
    @action calPrice() {
        const dataBody = this.bookFormData();
        const fetchUrl = HOST_NAME + '/wechat-order/save';
        const validFaild = this.formValid();
        return new Promise((resolve, reject) => {
            // resolve(this.bookReturn) // test:
            if (validFaild === true) {
                reject(this.formValidResult.nameRequired
                    || this.formValidResult.emailRequired
                    || this.formValidResult.mobileRequired
                    || this.formValidResult.pickupRequired
                );
            } else {
                req.postForm(fetchUrl, dataBody)
                    .then(json => {
                        runInAction(() => {
                            this.bookReturn = json;
                        })
                        console.log(json);
                        resolve(json);
                    }).catch(ex => {
                        reject("Something wrong, Please try again.");
                    }).finally(() => {
                    });
            }
        });
    }
    @action formValid() {
        this.formValidResult.nameError = (this.fullname === '');
        this.formValidResult.nameRequired = (this.fullname === '') ? 'Please fill in your fullname.' : '';
        this.formValidResult.mobileError = (this.mobile === '');
        this.formValidResult.mobileRequired = (this.mobile === '') ? 'Please fill in your mobile.' : '';

        let emailFormat = true; let emailRequired = true;
        emailRequired = (this.email !== '');
        this.formValidResult.emailRequired = (emailRequired === false) ? 'Please fill in your email.' : '';
        emailFormat = /[\w.]+@[\w.]+/.test(this.email);
        this.formValidResult.emailRequired = (emailFormat === false && emailRequired === true) ? 'Please fill in your email correctly.' : this.formValidResult.emailRequired;
        this.formValidResult.emailError = !(emailRequired && emailFormat);

        this.formValidResult.pickupError = (this.pickupOption.pickupAddress === '' && this.pickupOption.value === 'meetingpoint');
        this.formValidResult.pickupRequired = (this.formValidResult.pickupError === true) ? 'Please select/fill in a pick up address.' : '';

        return (this.formValidResult.nameError
            || this.formValidResult.emailError
            || this.formValidResult.mobileError
            || this.formValidResult.pickupError
        );
    }
    bookFormData() {
        let bookData = new FormData();
        bookData.append('requests', this.requests);
        bookData.append('userid', this.appStore.userid);
        bookData.append('web_code', 'TP-GZH');
        bookData.append('tour_external_id', this.appStore.cityStore.tourObj.activity.externalId);
        bookData.append('tour_id', this.appStore.cityStore.tourObj.activity.id);
        bookData.append('start_date', this.startDate.toLocaleDateString());
        bookData.append('adult_num', this.adultNum);
        bookData.append('child_num', this.childNum);
        bookData.append('fullname', this.fullname);
        bookData.append('email', this.email);
        bookData.append('mobile', this.mobile);
        bookData.append('passenger', JSON.stringify(this.passengerList));
        bookData.append('pickup', JSON.stringify(this.pickupOption));
        bookData.append('country', this.country.name);
        bookData.append('country_id', this.country.id);
        bookData.append('country_code', this.country.code);
        bookData.append('total_price', this.totalPrice);

        for (const key in this.travelers) {
            if (/_+/.test(key) === true) {
                delete this.travelers[key];
            }
        }
        bookData.append('travelers', JSON.stringify(this.travelers));

        // for (var pair of bookData.entries()) {
            // console.log(pair[0] + ':: ' + pair[1]);
        // }

        return bookData;
    }
    @action updatePaid() {
        this.bookReturn.paid = 'true';
    }
    @action resetPaid() {
        this.bookReturn.paid = 'false';
    }
}
export default BookStore;
