// pages/address-edit/address-edit.js

/**
 * Project: WooCommerce微信小程序
 * Description: 将WooCommerce商城接入微信小程序
 * Author: 幻想小籽
 * Organization: QwqOffice (https://www.qwqoffice.com)
 */

const Zan = require('../../vendor/ZanUI/index');
const app = getApp();

Page(Object.assign({}, Zan.TopTips, app.Methods, {
    data: Object.assign({}, app.Variables, {
        /* W2W Extension, Name: w2w-advanced-address, Code: addressEditData */
        NAV_HEIGHT: wx.STATUS_BAR_HEIGHT + wx.DEFAULT_HEADER_HEIGHT + 'px',
        NAV_BAR_HEIGHT: wx.DEFAULT_HEADER_HEIGHT + 'px',
        pageTitle: '编辑地址',
		address: null,
        fields: {
            billing_first_name: {
                type: 'text',
                label: '收货人',
                placeholder: '姓名'
            },
            billing_phone: {
                type: 'number',
                label: '手机号码'
            },
            billing_country: {
                type: 'select',
                label: '国家/地区'
            },
            billing_state: {
                type: 'select',
                label: '省份'
            },
            billing_city: {
                type: 'text',
                label: '城市'
            },
            billing_address_1: {
                type: 'text',
                label: '详细地址'
            },
            billing_postcode: {
                type: 'number',
                label: '邮政编码'
            }
        },
        selectedCountryIndex: 0,
        selectedStateIndex: 0
        /* W2W Extension, Name: w2w-advanced-address, Code: addressEditData */
    }),
    /* W2W Extension, Name: w2w-advanced-address, Code: addressEditEvents */
    inputFocus(e) {
        var name = e.currentTarget.dataset.name;
        this.setData({
            focusing: name
        });
    },
    // 国家选择
    countryChange(e) {
        var countryIndex = e.detail.value;
        this.setData({
            selectedCountryIndex: parseInt(countryIndex)
        });
        this.getStates(this.data.countries[countryIndex].id);
    },
    // 获取指定国家省份
    getStates(country, callback = function() {}) {
        app.Util.network.GET({
            url: app.API('states'),
            params: {
                country: country
            },
            success: data => {
                this.setData({
                    states: data
                });
                callback(data);
            }
        });
    },
    // 省份选择
    stateChange(e) {
        this.setData({
            selectedStateIndex: parseInt(e.detail.value)
        });
    },
    // 保存地址
    saveAddress(e) {
        var address = e.detail.value;
        address.billing_country = this.data.countries[address.billing_country];
        if (typeof address.billing_state == 'number') {
            address.billing_state = this.data.states[address.billing_state];
        }
        var postAddress = app.Util.addressTransform(address, 'post');
        var params = postAddress;
        params.w2w_session = app.data.w2w_session;
        if (this.data.mode == 'edit') {
            params.id = this.data.id;
        }
        app.Util.network.POST({
            url: app.API('save_address'),
            params: params,
            success: data => {
                if (data.success == true) {
                    wx.showToast({
                        title: '保存成功',
                        duration: 1000
                    })
                    setTimeout(() => {
                        wx.navigateBack()
                    }, 1000)
                } else {
                    this.showZanTopTips(data.errors);
                }
            }
        });
    },
    findIndexByID(arr, id) {
        for (var i in arr) {
            if (arr[i].id == id) {
                return parseInt(i);
            }
        }
        return undefined;
    },
    onLoad: function(options) {
        this.setData({
            currentPages: getCurrentPages().length
        });
        app.Util.network.GET({
            url: app.API('get_address'),
            params: {
                w2w_session: app.data.w2w_session
            },
            success: data => {

                var params = {},
                    id = options.id || null,
                    addressList = data.addresses;
                addressList = addressList || [];

                if (id != null) {
                    var ognAddress = addressList[id],
                        address = app.Util.addressTransform(ognAddress);
                    params.country = address.billing_country;
                }

                app.Util.network.GET({
                    url: app.API('countries'),
                    params: params,
                    success: countriesData => {
                        var d = {
                            addressList: addressList,
                            mode: options.mode || 'add',
                            id: options.id || null
                        };
                        if (id != null) {
                            d.address = address;
                            d.selectedCountryIndex = this.findIndexByID(countriesData.countries, address.billing_country) || 0;
                            d.selectedStateIndex = this.findIndexByID(countriesData.states, address.billing_state) || 0;
                        }
                        this.setData(Object.assign({}, countriesData, d));
                    }
                });
            }
        });
    },
    /* W2W Extension, Name: w2w-advanced-address, Code: addressEditEvents */
}))