const WxParse = require('../../wxParse/wxParse.js');
const $ = global;

new $.Page({
    data: {
        options: [],
        api: ''
    },
    onLoad(options) {
        if (!options.id) {
            return $.wx.showToast({
                title: '找不到对应id'
            });
        }
        $.request(`classify/${options.id}`, 'GET', {}).then((res) => {
            var article = res.data && res.data.content || '';
            const fields = res.data.fields || [];
            const options = [];
            WxParse.wxParse('article', 'html', article, this, 5);
            for (let item of fields) {
                const group = item.input_group;
                options.push({
                    value: item.type === 'checkbox' ? ([]) : (group[0].value || ''),
                    key: item.name_cn
                });
            }
            this.setData({
                banner: res.data.photo.split(';') || [],
                fields,
                options,
                api: res.data.api,
                type: res.data.type
            });
        });
    },
    bookServer() {
        const {
            name,
            phone,
            address,
            notes,
            options,
            api,
            type
        } = this.data;
        if (!name || !phone || !address) {
            return $.wx.showToast({
                title: '请把信息填写完整'
            });
        }
        if (!this._isPhone(phone)) {
            return $.wx.showToast({
                title: '请输入正确的手机号码'
            });
        }
        $.wx.showToast({
            title: '加载中'
        }, 'loading');
        const data = {
            contact: name,
            phone,
            address,
            notes,
            type,
            options: ''
        }
        for (let option of options) {
            let val = '';
            if (Array.isArray(option.value)) {
                if (option.value.length > 0) {
                    val = `${option.key}:${option.value.join(',')}`;
                }
            } else {
                val = `${option.key}:${option.value}`;
            }
            data.options += (!data.options ? val : ('；' + val));
            // data[`${option.key}`] = option.value;
        }
        $.request(api, 'POST', data).then(() => {
            $.wx.hideToast('loading');
            $.router.goto({
                path: '/pages/order/index',
                type: $.ROUTER_TYPE.SWITCH_TAB
            });
        });
    },
    inputChange(e) {
        const { index } = e.currentTarget.dataset || 0;
        const { value } = e.detail;
        const { options } = this.data;
        options[index].value = value;
        this.setData({
            options
        });
    }
});