<template>
    <van-form >
        <van-cell-group v-for="item in basicGroup" :title="item.label" :key="item.label">
            <template v-for="col in item.children">
                <!-- v-if="col | isShowFilter(value)" -->
                <template v-if="isShow(col)">
                    <!-- <van-cell
                        class="base-cell"
                        v-if="editable && col.basicinfo && col.basicinfo.el && col.basicinfo.el.indexOf('selection') > -1"
                        :title="col.title"
                        :value="data[col.field] | valueFilter"
                        is-link
                        @click="handleClick({column: col, row: data})"
                    /> -->
                    <van-cell
                        v-if="col.basicinfo && col.basicinfo.render"
                        class="base-cell"
                        :title="col.title"
                    >
                        <template #default>
                            <content-cell
                                :column="col"
                                :data="data"
                                @input="updateValue"
                                @toSelect="handleClickSelect"
                            ></content-cell>
                        </template>
                    </van-cell>
                    <van-field
                        v-else-if="col.basicinfo && col.basicinfo.el && col.basicinfo.el.indexOf('selection') > -1"
                        :class="{'readonly': !editable}"
                        :disabled="editable | disabledFilter(col, data)"
                        :name="col.title"
                        :label="col.title"
                        :value="data[col.field]"
                        :placeholder="editable ? col.title : ''"
                        v-bind="bingAttrs(col)"
                        :clickable="editable"
                        @click-input="handleClick({column: col, row: data})"
                        @click-right-icon.stop="($event) => handleClear($event, {column: col, row: data})""
                    >
                        <template #input v-if="col.enum || col.basicinfo.el == 'select'">
                            {{data[col.field] | enumFilter(col.enum)}}
                        </template>
                        <template #right-icon v-if="data[col.field] && col.basicinfo.clearable">
                            <div class="flx-center" style="margin-left: 8px;">
                                <van-icon name="cross" color="#8B8B8B" />
                            </div>
                        </template>
                        <template #extra v-if="editable">
                            <div style="margin-left: 8px;">
                                <van-icon name="arrow" color="#8B8B8B" />
                            </div>
                        </template>
                    </van-field>
                    <van-field
                        v-else-if="col.enum || (col.basicinfo && col.basicinfo.el == 'select')"
                        :class="{'readonly': !editable}"
                        :disabled="editable | disabledFilter(col, data)"
                        :name="col.title"
                        :label="col.title"
                        :value="data[col.field]"
                        :placeholder="editable ? col.title : ''"
                        v-bind="bingAttrs(col)"
                        :clickable="editable"
                        @click-input="handleClickSelect(col)"
                    >
                        <template #input v-if="col.enum || col.basicinfo.el == 'select'">
                            {{data[col.field] | enumFilter(col.enum)}}
                        </template>
                        <template #right-icon v-if="data[col.field] && col.basicinfo.clearable">
                            <div class="flx-center" style="margin-left: 8px;" @click.stop="handleClear($event, {column: col, row: data})">
                                <van-icon name="cross" color="#8B8B8B" />
                            </div>
                        </template>
                        <template #extra v-if="editable">
                            <div style="margin-left: 8px;">
                                <van-icon name="arrow" color="#8B8B8B" />
                            </div>
                        </template>
                    </van-field>
                    <van-field
                        v-else
                        :class="{'readonly': !editable}"
                        :disabled="editable | disabledFilter(col, data)"
                        :name="col.title"
                        :label="col.title"
                        :value="data[col.field]"
                        :placeholder="editable ? col.title : ''"
                        v-bind="bingAttrs(col)"
                        @focus="handleFocus"
                        @input="(val) => updateValue(col.field, val)"
                    >
                        <!-- @change="(val) => updateValue(col.field, val)" -->
                        <template #input v-if="col.datatype == 'checkbox'">
                            <LjCheckbox v-model="data[col.field]" :disabled="!editable" ></LjCheckbox>
                        </template>
                        <!-- <template #input v-else-if="col.enum || col.basicinfo.el == 'select'">
                            {{data[col.field] | enumFilter(col.enum)}}
                        </template> -->
                    </van-field>
                </template>
            </template>
        </van-cell-group>

        <van-action-sheet v-model="showActionSheet" :closeable="false">
            <van-picker
                :title="actionColumn.title"
                show-toolbar
                value-key="label"
                :default-index="actionColumn.defaultIndex"
                :columns="actionColumn.enum"
                @confirm="handleActionConfirm"
                @cancel="showActionSheet = false"
            />
        </van-action-sheet>
    </van-form>
</template>

<script>
import LjCheckbox from 'components/lj-checkbox.vue';

export default {
    name: "lj-base-form",
    components: {
        LjCheckbox,
        // 'content-cell': {
        //     props: {
        //         column: Object, 
        //     },
        //     render(h) {
        //         let column = this.column;
        //         return h('div', {
        //             class: {
        //                 'lj-cell-content': true,
        //             },
        //             domProps: {
        //                 innerHTML: 32123123
        //             },
        //         })
        //     }
        // }
        'content-cell': {
            props: {column: Object, data: Object},
            render(h) {
                let renderArr = null;
                let self = this;
                if (this.column.basicinfo && this.column.basicinfo.render !== undefined) {
                    renderArr = this.column.basicinfo.render(h, {column: this.column, data: this.data}, self);
                }
                // return h('div', {}, renderArr);
                return renderArr;
            }
        },
    },
    props: {
        editable: {
            type: Boolean,
            default: false
        },
        group: {
            // 分组顺序
            type: Array,
            default: () => ([])
        },
        columns: {
            // 表格列配置
            type: Array,
            default: () => ([])
        },
        data: {
            type: Object,
            // default: function () {
            //     return {};
            // }
            default: () => ({})
        }
    },
    data() {
        return {
            checkboxValue: {},
            basicGroup: [],
            showActionSheet: false,
            actionColumn: {}, // 当前操作列
            actionData: [], // 当前操作的数据
        };
    },
    watch: {
        // value: {
        //     handler(newVal, oldVal) {
        //         this.data = newVal;
        //     },
        //     deep: true,
        //     immediate: true
        // },
        group: {
            handler(newVal, oldVal) {
                let arr = newVal;
                // console.log('computed !!basicGroup this.group :>> ', JSON.stringify(newVal));
                // console.log('computed !!basicGroup this.this.columns :>> ', JSON.stringify(this.columns));
                arr.forEach(item => {
                    item.children = this.columns.filter(col => col.basicinfo && col.basicinfo.visible !== false && col.basicinfo.group === item.label);
                    item.children.sort((a, b) => a.basicinfo.order - b.basicinfo.order);

                    // this.checkboxValue = {};
                    // item.children.forEach(col => {
                    //     if (col.datatype == 'checkbox') {
                    //         this.checkboxValue[col.field] = [this.value[col.field]];
                    //     }
                    // });
                });
                this.basicGroup = arr;
            },
            deep: true
        },
    },
    methods: {
        bingAttrs(col) {
            let attrs = {};
            if (col.basicinfo) {
                if (col.basicinfo.props) {
                    attrs = { ...attrs, ...col.basicinfo.props }
                }
                // if (col.basicinfo.rules) {
                //     attrs.rules = col.basicinfo.rules
                // }
            }
            // console.log(' attrs :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(attrs));
            return attrs
        },
        isShow(col) {
            if (this.editable) {
                let _editable = false;
                if (col.basicinfo) {
                    if (Object.keys(col.basicinfo).includes("editable")) {
                        if ($lj.isFunction(col.basicinfo.editable)) {
                            _editable = col.basicinfo.editable({searchParam: this.data});
                        } else {
                            _editable = col.basicinfo.editable;
                        }
                    }
                    if (Object.keys(col.basicinfo).includes("editvisible")) {
                        if ($lj.isFunction(col.basicinfo.editvisible)) {
                            _editable = col.basicinfo.editvisible({searchParam: this.data});
                        }
                    }
                }

                return _editable;
            } else {
                if (col.basicinfo && Object.keys(col.basicinfo).includes("editvisible")) {
                    return col.basicinfo.editvisible({searchParam: this.data});
                } else {
                    return true;
                }
            }
        },
		// updateValue(field, val) {
        //     console.log('updateValue :>> ', val, field);
        //     let data = this.value;
        //     data[field] = val;
		// 	this.$emit('update:value', data)
		// }
		updateValue(field, val) {
            console.log('updateValue :>> ', val, typeof val, field);
            // this.data[field] = val;
            this.$set(this.data, field, val)
            // this.$emit('update:value', this.data)
		},
        handleClickSelect(col) {
            if (!this.editable) return
            // this.actionData = col.enum.map(itm => itm.label);
            this.actionColumn = col;

            let result = '';
            let idx = col.enum.findIndex(item => item.value == this.data[col.field]);
            // result = item.length > 0 ? item[0].label : '';

            console.log(' result :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(idx));
            this.actionColumn.defaultIndex = idx;

            this.$nextTick(() => {
                this.showActionSheet = true;
            });
        },
        handleActionConfirm(item) {
            console.log('handleActionConfirm :>> ', item);
            // let item = this.actionColumn.enum.find(itm => itm.label == value);

            this.data[this.actionColumn.field] = item.value;

            this.showActionSheet = false;

            this.$emit('change', {column: this.actionColumn, row: this.data})
        },
        handleFocus(element) {
            element.srcElement.select();
            this.$emit('inputfocus');
        },
        handleClick(data) {
            this.$emit('cell-click',  data)
        },
        handleClear(ev, data) {
            ev.stopPropagation();
            let {column, row} = data
            this.data[column.field] = '';
            this.$emit('cell-clear',  data)
        },
    },
    filters: {
        valueFilter(value) {
            if (value == "" || value == null || typeof value == 'undefined') return "-"
            return value;
        },
        enumFilter(value, enums) {
            console.log('enumFilter :>> ', value, JSON.stringify(enums));
            let result = '';
            if (enums.length > 0) {
                let item = enums.filter(item => item.value == value);
                result = item.length > 0 ? item[0].label : '';
            }
            return result;
        },
        disabledFilter(editable, col, data) {
            let bool = editable;
            if (col.basicinfo && Object.keys(col.basicinfo).includes("editable")) {
                if ($lj.isFunction(col.basicinfo.editable)) {
                    bool = col.basicinfo.editable(data);
                } else {
                    bool = col.basicinfo.editable;
                }
            }
            return !bool;
        },
    },
}
</script>

<style lang="less">
.van-cell {
    // 浏览模式
    &.readonly.van-field--disabled {
        .van-field__label {
            // text-align: right;
            color: @light-label-secondary;
        }
        .van-field__control {
            color: @light-label-primary!important;
            -webkit-text-fill-color:  @light-label-primary!important;

            .van-checkbox__icon .van-icon{
                color: transparent!important;
                -webkit-text-fill-color:  transparent!important;
            }
            .van-checkbox__icon--checked .van-icon{
                color: @light-label-primary!important;
                -webkit-text-fill-color:  @light-label-primary!important;
            }
        }
    }

    // &.base-cell {
    //     .van-cell__title {
    //         margin-right: 12px;
    //         width: 6.2em;
    //         flex-basis: auto;
    //         flex-grow: 0;
    //         flex-shrink: 0;
    //     }
    //     .van-cell__value {
    //         text-align: left;
    //     }
    // }
}
</style>