const $ = global;

new $.Page({
    data: {
        tabs: [],
        goods: [],
        selected: 0,
        list: []
    },
    onLoad() {
        this.init();
    },
    init() {
        $.request('product/home', 'GET', {}).then((res) => {
            const list = res.data;
            if (list && list.length > 0) {
                this.setData({
                    list
                });
            }
        });
        $.request('products', 'GET', {}).then((res) => {
            if (res.data) {
                const tabs = [];
                for (let key in res.data) {
                    tabs.push(key);
                }
                this.setData({
                    products: res.data,
                    tabs,
                    goods: tabs.length > 0 ? res.data[tabs[0]] : []
                });
            }
        });
    },
    changeTab(e) {
        const {
            name
        } = e.target.dataset;
        if (name) {
            let selected = 0;
            const products = this.data.products;
            for (let key in products) {
                if (key == name) {
                    break;
                } else {
                    selected++;
                }
            }
            this.setData({
                selected,
                goods: products[name]
            })
        }
    },
    toDetail(e) {
        const {
            id
        } = e.target.dataset;
        if (id) {
            $.router.goto({
                path: `/pages/detail/index`,
                query: {
                    id
                }
            });
        }
    },
    toProduct(e) {
        const {
            id
        } = e.currentTarget.dataset;
        if (id || id == 0) {
            $.router.goto({
                path: '/pages/goodsDetail/index',
                query: {
                    id
                }
            })
        }
    }
});