<template>
    <lj-win-popup
        ref="winPopup"
        :popupStyle="{ 'height': height}"
        round
        position="bottom"
        class="widget-longpress-nav-wrapper"
        @closed="autoClosed"
    >
		<template #title>
            <slot name="longpress-title" :data="mtrlBase">
                <div class="header-title" @click="handleGotoTitle">
                    <i class="iconfont icon-huowu"></i>
                    <div class="title-inner">
                        <div class="name">
                            {{ mtrlBase.mtrlname }}
                            <i class="iconfont icon-right"></i>
                        </div>
                        <div class="code">
                            {{ mtrlBase.mtrlcode }}
                        </div>
                    </div>
                </div>
            </slot>
		</template>
        <template #body>
            <transition name="opacity">
                <header class="navlist" v-show="!widgetLoading && navList.length">
                    <div class="nav-grid">
                        <template v-for="(item, index) in navList">
                            <div v-if="!item.hidden"
                                :key="index"
                                class="lj-grid-item"
                                @click="handleOpenNavList(item)"
                            >
                                <van-badge max="99" :color="'#FF3B30'" :class="{'badge-loading': item.hasOwnProperty('loading') && item.loading}">
                                    <div class="grid-icon">
                                        <i class="iconfont" :class="item.icon"></i>
                                    </div>
                                    <template #content v-if="(item.hasOwnProperty('loading') && item.loading) || (item.hasOwnProperty('badge') && mtrlBase[item.badge] > 0)">    
                                        <template v-if="item.hasOwnProperty('loading') && item.loading">
                                            <van-loading type="spinner" size="12" color="#007AFF"/>
                                        </template>
                                        <template v-else-if="item.hasOwnProperty('badge') && mtrlBase[item.badge] > 0">
                                            {{ mtrlBase[item.badge] }}
                                        </template>
                                    </template>
                                </van-badge>
                                <div class="grid-title">
                                    {{ item.title }}
                                </div>
                            </div>
                        </template>
                    </div>
                </header>
            </transition>
            <transition name="opacity">
                <main class="inputlist" v-show="!widgetLoading">
                    <component
                        v-for="(items, idx) in queryFieldsForWidget"
                        :is="items.type | widgetNameFilter"
                        :title="items.group"
                        :key="idx"
                        :value="currentQueryField"
                        :data="items"
                        model="checkbox"
                        :selecteditem="selectedItem"
                        @input="handleCpInput"
                        @click-checkbox="handleGetCheckbox"
                    ></component>
                </main>
            </transition>
        </template>
        <template #footer>
            <van-button class="btn" round block @click="handleCancel">
                <!-- <i solt="icon"  class="iconfont icon-ic_refresh"></i> -->
                取消
            </van-button>
            <van-button v-if="selectedItem.length > 0" class="btn" type="info" block round @click="handleConfirm">
                筛选
                <i solt="icon"  class="iconfont icon-filter_light"></i>
                {{ `(${selectedItem.length})` }}
            </van-button>
        </template>
    </lj-win-popup>
</template>

<script>
import LjWinPopup from "../lj-win-popup"
import WidgetRadio from "./widget-radio"
// import WidgetCascader from "./widget-cascader"
import WidgetInput from "./widget-input"
import WidgetDate from "./widget-date"
import WidgetSwitch from "./widget-switch"

export default {
    name: 'LjLongpressNav',
    components: {
        LjWinPopup,
        WidgetRadio,
        WidgetInput,
        WidgetDate,
        WidgetSwitch
    },
    data() {
        return {
            widgetLoading: false, // 组件加载
            initParams: {}, // 读取历史参数
            currentQueryField: {}, // 当前筛选的值
            // habitFields: [],
            hardProperties: "", // 强制参数的属性字符串
            // fieldMap: {},
            queryFieldsForWidget: [], // queryFields数据转换
            selectedItem: [], // 长按菜单，长按对象
            mtrlBase: {}, // 基础信息
            navList: []
        };
    },
    props: {
        height: {
            type: String,
            default: 'auto'
        },
        queryFields: {
            type: Array
            // {
            //     title: 字段描述
            //     property：字段属性名
            //     type: 默认为文字input，可选radio： 单选， checkbox：多选；cell：（）;date：日期, switch: 开关
            //     selectOptions：数据源
                        // optionsApi: 动态获取数据接口名称,
                        // valueMap: 自定义 options 结构中的字段, 例如{ text: 'text', value: 'value', children: 'children' },
                        // extraOptions: 额外的数据数组，通常用于网络请求数据，附加“全部”选项用，如[{scid: -1, scname: "全部"}]
                        // options: 已下载数据列表Array
            //     hint：输入框提示信息
            //     disabled： 是否不可用
            //     initValue：初始值
            //     initDateAdd：初始日期递推，如-7，默认值为当前时间前7日
            //     staticDateInit: 初始日期，只用于用户没有用户习惯之前的值
            //     valueMap： 用于条件值输出时，checkbox类型的值转换，默认[0,1]，如需输出boolean类型，需声明为[false,true]
            // }
        },
        // 继承lj-longpress-nav:长按菜单快速入口列表
        longpressList: {
            type: Array,
            default: function () {
                return []
            }
        }
    },
    watch: {
        mtrlBase: {
            handler(newVal) {
                let arr = this.longpressList;
                for (let item of arr) {
                    if (item.hasOwnProperty('fnHidden')) {
                        item.hidden = item.fnHidden(newVal);
                    } else {
                        item.hidden = false;
                    }
                    if (item.hasOwnProperty('loading')) {
                        item.loading = true;
                    }
                }
                this.navList = arr;
            },
            deep: true
        },
        longpressList: {
            handler(newVal) {
                this.navList = newVal;
            },
            deep: true,
        }
    },
    mounted() {
        // this.hardProperties = "";
        // for (let prop in this.hardParms) {
        //     this.hardProperties += "," + prop;
        // }
    },
    methods: {
        /**点击快捷入口 */
        handleOpenNavList(item) {
            if (item.fnCallBack) {
                item.fnCallBack(this.mtrlBase);
            } else if (item.winName) {
                $lj.openWin(item.winName, this.mtrlBase);
            }
            setTimeout(() => {
                this.$refs.winPopup.close();
            }, 200);
        },
        handleGotoTitle() {
            this.$emit('gotoTitle', this.mtrlBase);
        },
        /**自动：关闭后，状态清除 */
        autoClosed() {
            this.currentQueryField = {};
            this.queryFieldsForWidget = [];
            this.selectedItem = [];
        },
        /**读取设置搜索 */
        initSearched(row) {
            for (let i = 0; i < this.queryFields.length; i++) {
                let property = this.queryFields[i].property;
                this.$set(this.currentQueryField, property, row[property]);
            }
            console.log('长按菜单 this.currentQueryField after :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.currentQueryField));
            
            // this.$emit('filter', this._fnCheckIfFilter());
        },
        // /**检测是否需要标记：筛选中 */
        // _fnCheckIfFilter() {
        //     let ifFilter = false;
        //     for (let i = 0; i < this.queryFields.length; i++) {
        //         let property = this.queryFields[i].property;
        //         if (this.currentQueryField[property] != this.queryFields[i].initValue) {
        //             console.log(' this.queryFields[i] :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.queryFields[i]));
        //             ifFilter = true;
        //             break;
        //         }
        //     }
        //     return ifFilter;
        // },
        /**输入监听 */
        handleCpInput(item) {
            console.log(' this.currentQueryField :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.currentQueryField));
        },
        /**初始化：打开筛选组件 */
        open({column, row, index}) {
            this.widgetLoading = true;
            this.$refs.winPopup.open();
            this.updatedMtrl(row);
            this.initQueryField(column);
            this.initSearched(row);
            this.$nextTick(() => {
                this.widgetLoading = false;
            });
        },
        updatedMtrl(row) {
            this.mtrlBase = row;
        },
        /**打开筛选组件 */
        handleCancel() {
            this.$refs.winPopup.close();
        },
        // /**按钮：重置 */
        // handleReset() {
        //     // this.cascaderValue = '';
        //     for (let i = 0; i < this.queryFields.length; i++) {
        //         let property = this.queryFields[i].property;
        //         let value = this.queryFields[i].initValue || '';
        //         if (property.indexOf('if') == 0) {
        //             value = 0;
        //         }
        //         this.$set(this.currentQueryField, property, value);
        //     }
        //     this.$refs.winPopup.close();
        //     setTimeout(() => {
        //         this.$emit('confirm', this.currentQueryField);
        //         this.$emit('reset');
        //     }, 400);
        //     console.log('handleReset this.currentQueryField :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.currentQueryField));
        // },
        // /**按钮：筛选 */
        handleConfirm() {
            console.log('handleConfirm this.currentQueryField :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.currentQueryField));
            let queryField = {};
            for (let i = 0; i < this.selectedItem.length; i++) {
                let property = this.selectedItem[i];
                queryField[property] = this.currentQueryField[property];
            }
            this.$refs.winPopup.close();
            setTimeout(() => {
                this.$emit('confirm', queryField);
                this.$emit('filter');
            }, 400);
        },
        /**转换数据模型 */
        initQueryField(column) {
            let groupArr = [];
            this.queryFields.forEach((field) => {
                if (groupArr.indexOf(field.group) > -1) {
                    let idx = groupArr.indexOf(field.group);
                    this.queryFieldsForWidget[idx].children.push(field);
                } else {
                    let obj = {
                        group: field.group || field.title,
                        type: field.type,
                        children: [field],
                        value: '',
                        title: '',
                        property: field.property
                    }
                    groupArr.push(obj.group);
                    this.queryFieldsForWidget.push(obj);
                }
                if (column.property == field.property) {
                    this.selectedItem.push(column.property);
                }
            });
            console.log(' this.queryFieldsForWidget :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.queryFieldsForWidget));
        },
        /**获取已选列表 */
        handleGetCheckbox(arr) {
            this.selectedItem = arr;
        }
    },
    filters: {
        widgetNameFilter(type) {
            let component = '';
            switch (type) {
                case 'radio1': // 单选，排版：单行
                case 'radio2': // 单选，排版：一行两个
                case 'radio3': // 单选，排版：一行三个
                    component = WidgetRadio;
                    break;
                case 'cascader': // 层级选择
                    // component = WidgetCascader;
                    break;
                case 'checkbox': // 多选
                    
                    break;
                case 'date':  // 日期
                    component = WidgetDate
                    break;
                case 'switch': // 开关
                    component = WidgetSwitch
                    break;
                default: // 默认：input
                    component = WidgetInput
                    break;
            }
            return component
        }
    }
};
</script>

<style lang="less">
    .widget-longpress-nav-wrapper {

        .header-title {
            text-align: left;
            display: flex;
            margin-left: 15px;

            .iconfont {
                font-size: 18px;
                color: #333333;
            }
            .title-inner {
                display: flex;
                flex-direction: column;
                justify-content: center;
                margin-left: 8px;

                .name {
                    color: @musePrimary;
                    display: flex;
                    justify-content: center;
                    font-size: 14px;
                    font-weight: 700;
                    line-height: 20px;
                    .iconfont {
                        color: @musePrimary;
                    }
                }
                .code {
                    font-size: 12px;
                    font-weight: normal;
                    line-height: 12px;
                    color: @secondary;
                }
            }
        }

		.navlist {
			.nav-grid {
				overflow-x: auto;
				margin: 0 15px;
				padding: 5px 0;
				display: flex;

				.lj-grid-item {
					min-width: 60px;
					margin: 5px 2px;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;

					.grid-icon {
						// padding: 10px;
						display: flex;
						justify-content: center;
						align-items: center;

						.iconfont {
							display: flex;
							justify-content: center;
							align-items: center;
							width: 48px;
							height: 48px;
							background-color: #f9f9f9;
							border-radius: 8px;
							font-size: 24px;
                            transition: all 0.05s ease-in-out;
                            box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.04), 0px 0px 3px 0px rgba(0,0,0,0.08);
						}
					}
					.grid-title {
						padding: 3px 0;
						text-align: center;
                        font-size: 12px;
                        color: rgba(60, 60, 67, 0.8);
					}
                    &:active {
                        .grid-icon {
                            .iconfont {
                                background-color: #f1f1f1;
                                transform: scale(0.9);
                            }
                        }
                    }
                    .badge-loading .van-badge {
                        min-width: unset!important;
                        background-color: unset!important;
                        border-color: transparent!important;
                    }
				}
			}
		}
    }
</style>