const _Http = getApp().globalData.http;
Page({
    data: {
        paging: {
            "pageNumber": 1,
            "pageSize": 20,
            "pageTotal": 1,
        },
        result: [],
    },
    onLoad(options) {
        let item = JSON.parse(options.data);
        console.log(item)
        this.setData({
            item,
            result: item.value ? Array.isArray(item.value) ? item.value : [item.value] : []
        })
        this.getList();
    },
    toggle(e) {
        const {
            item
        } = e.currentTarget.dataset;
        let result = this.data.result;
        if (this.data.item.optionType == 'checkbox') {
            let index = result.findIndex(v => v == item.value);
            if (index == -1) {
                result.push(item.value)
            } else {
                result.splice(index, 1)
            }
            this.setData({
                result
            })
        } else {
            this.setData({
                result: [item.value]
            })
            this.submit();
        }
    },
    getList(init = false) {
        let {
            pageNumber,
            pageTotal,
            pageSize
        } = this.data.paging;
        if (init) {
            pageNumber = 1;
            pageTotal = 1;
        };
        if (pageNumber > pageTotal) return;
        _Http.basic({
            "classname": "sysmanage.develop.optiontype.optiontype",
            "method": "optiontypeselect",
            "content": {
                pageNumber,
                pageSize,
                "typename": this.data.item.optionNmae,
                "parameter": {
                    "siteid": wx.getStorageSync('siteP').siteid
                }
            }
        }).then(res => {
            if (res.msg != '成功') {
                wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                return;
            };
            this.setData({
                list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
                "paging.pageNumber": res.pageNumber + 1,
                "paging.pageTotal": res.pageTotal,
                "paging.total": res.total,
            })
            console.log("可选项查询", res)
        })
    },
    submit() {
        let item = this.data.item;
        if (item.optionType == 'checkbox') {
            item.value = this.data.result
        } else {
            item.value = this.data.result[0]
        };
        const pages = getCurrentPages();
        pages[pages.length - 2].selectComponent(item.model || "#Form").setOption(item);
        wx.navigateBack();
        /* item.setFun && getApp().globalData.optionFun && getApp().globalData.optionFun({
            item,
            list: this.data.result.map(v => this.data.list.find(s => s.value == v))
        }); */
    },
    onReachBottom() {
        this.getList();
    },
})