<template>
    <div id="searchbar-widget">
        <!-- <form action="/"> -->
            <van-popover
                v-model="showPopover"
                class="search-recommend-popover"
                placement="bottom"
                :offset="popoOffset"
                get-container="#searchbar-widget"
            >
                <template #reference>
                    <van-search
                        ref="searchRef"
                        v-model.trim="searchText"
                        :show-action="searching"
                        class="search-widget"
                        clear-trigger="always"
                        :placeholder="keywordList.length ? '' : hint"
                        left-icon="serach"
                        @search="handleSearchbar"
                        @focus="handleSearchFocus(true)"
                        @input="handleSearchInput"
                        @blur="handleSearchBlur"
                        @clear="handleCancel(true)"
                    >
                        <template slot="label">
                            <div class="search-label-box">
                                <i class="iconfont icon-Search_light" style="font-size: 16px"></i>
                                <div class="search-tag" v-if="keywordList.length">
                                    <van-tag
                                        round
                                        size="medium"
                                        color="#2196f3"
                                        @click.stop="handleSearchFocus(true)"
                                    >
                                        <span class="tag-title">
                                            {{ keywordList[0].title | actionTextFilter }}
                                        </span>
                                        {{ keywordList[0].value }}
                                    </van-tag>
                                    <van-tag
                                        v-if="keywordList.length > 1"
                                        round
                                        size="medium"
                                        color="#2196f3"
                                    >
                                        {{`+${keywordList.length - 1}`}}
                                    </van-tag>
                                </div>
                            </div>
                        </template>
                        <template slot="action">
                            <span class="search-cancel" @click="handleCancel(true)">取消</span>
                        </template>
                        <template slot="right-icon" v-if="scanicon">
                            <div class="right-icon-box" @click="handleScan">
                                <i class="iconfont icon-iconfontscan"></i>
                            </div>
                        </template>
                    </van-search>
                </template>
                <van-cell
                    v-for="(item, idx) in actions"
                    :key="idx"
                    :title="item.title"
                    @click="handleSearchbar(item)"
                    class="recommend-list lj-cell-right"
                    :class="{'tobe-search': searchState == item.property || !searchState && idx == 0}"
                >
                    <template #icon>
                        <i class="iconfont icon-Search_light"></i>
                    </template>
                    <template v-if="searchState == item.property || !searchState && idx == 0">
                        <i class="iconfont icon-enter"></i>
                    </template>
                </van-cell>
            </van-popover>
        <!-- </form> -->
        <slot name="right" :clickRightBtn="handleClickRight"></slot>
    </div>
</template>

<script>
export default {
    name: 'L1appLjSearchbarPro',

    data() {
        return {
            showPopover: false,
            searching: false,
            keywordList: [], // 关键字列表
            keywordList_ori: [], // 关键字列表 原始
            // searchState: "keyword", // 记录上一次搜索状态: 记录下拉搜索列表中，property属性；默认第一项
            searchState: "", // 记录上一次搜索状态: 记录下拉搜索列表中，property属性；默认第一项
            timerKL: null // keywordList定时器
        };
    },

    props: {
        // 关键字
        keyword:{
            type: String,
            default: "" 
        },
        // 获取单据列表的接口的接口
        apiName: {
            type: String,
            required: true
        },
        // 是否正在搜索
        // searching: {
        //     type: Boolean,
        //     default: true
        // },
        // 是否显示搜索下拉列表
        // showNav: {
        //     type: Boolean,
        //     default: true
        // },
        // 输入提示
        hint: {
            type: String,
            default: ""
        },
        // 输入框的值，支持v-model双向绑定
        value: {
            type: String
        },
        // 点击后是否把界面拉回到最顶
        actionToTop: {
            type: Boolean,
            default: true
        },
        // 下拉搜索列表
        actions: {
            type: Array,
            default: function() {
                return []
            }
        },
        // 提示文本
        hint: {
            type: String,
            default: "请输入关键字搜索"
        },
        // 是否在搜索框内显示扫描图标
        scanicon: {
            type: Boolean,
            default: false
        },
        // 搜索下拉，出现位置的偏移量[number, number]
        popoOffset: {
            type: Array,
            default: function() {
                return [0, 0]
            }
        },
    },

    computed: {
		searchText: {
			get() {
				return this.keyword
			},
			set(val) {
                this.$emit('update:keyword', val)
			}
		},
    },

    created() {
        if (this.actions.length > 0) {
            this.searchState = this.actions[0].property;
        } else {
            this.searchState = 'keyword';
        }

        console.log("created this.searchState >>> ", this.searchState, JSON.stringify(this.actions));
    },

    methods: {
        /**读取搜索记录 */
        initSearch(obj) {
            if (obj instanceof Array && obj.length > 0) {
                // this.keywordList = Object.assign(this.keywordList, obj);
                // this.$set(this.keywordList, Object.assign(this.keywordList, obj));
                this.keywordList = obj;
                // 读取上一次搜索第一个属性
                this.searchState = this.keywordList[0].property;
                this.searching = true;
            // } else if (Object.prototype.toString.call(obj) == "[object, Object]" && JSON.stringify(obj) != '{}') {
            //     console.log(' Object initSearch :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(obj));
            //     this.keywordList = [];
            //     this.keywordList.push(obj);
            //     this.searching = true;
            } else if (JSON.stringify(obj) == '{}' || JSON.stringify(obj) == '[]') {
                this.keywordList = [];
                this.searching = false;
            }
            console.log(' initSearch  keywordList:>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.keywordList));
        },
        /**搜索 */
        handleSearchbar(item) {
            clearTimeout(this.timerKL);
            console.log(' handleSearchbar 组件searching :item>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(item), this.searchState);
            if (this.actionToTop) {
                document.body.scrollTop = 0;
                document.documentElement.scrollTop = 0;
            }
            this.searching = true;
            this.showPopover = false;
            this.keywordList_ori = [];
            let searchObj = item;
            if (item && typeof item == "string") {
                for (let i = 0; i < this.actions.length; i++) {
                    if (this.actions[i].property == this.searchState) {
                        searchObj = {
                            title: this.actions[i].title,
                            property: this.actions[i].property,
                            value: item
                        }
                        break;
                    }
                }
            }
            this._fnGetKeyword(searchObj);
            console.log(' this.keywordList :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.keywordList));
            // 切换搜索数据
            let searchList = JSON.parse(JSON.stringify(this.actions));
            console.log('BF actions :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.actions));
            for (let i = 0; i < searchList.length; i++) {
                if (this.keywordList.length > 0 && this.keywordList[0].property == searchList[i].property) {
                    searchList[i].title = this.keywordList[0].title;
                    searchList[i].value = this.keywordList[0].value;
                } else {
                    searchList[i].value = '';
                    searchList[i].title = '';
                }
            }
            console.log('AF searchList :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(searchList));
            // // 记录用户数据
            // let keywordObj = $lj.setUserFilterParams(this.apiName, searchList);
            // $lj.setUserFilterTitle(this.apiName, searchList);
            let searchKeyword = {};
            searchList.forEach((field) => {
                searchKeyword[field.property] = field.value;
            });

            this.$emit("search", searchKeyword);
        },
        /**取消搜索 */
        handleCancel(ifOriginate) {
            this.keywordList = [];
            this.keywordList_ori = [];
            this.searching = false;
            this.showPopover = false;

            // 切换搜索数据
            let searchList = JSON.parse(JSON.stringify(this.actions));
            for (let i = 0; i < searchList.length; i++) {
                searchList[i].value = '';
                searchList[i].title = '';
            }
            // 记录用户数据
            // let keywordObj = $lj.setUserFilterParams(this.apiName, searchList);
            // $lj.setUserFilterTitle(this.apiName, searchList);
            let searchKeyword = {};
            searchList.forEach((field) => {
                searchKeyword[field.property] = field.value;
            });

            if (ifOriginate) {
                if (this.actions.length > 0) {
                    this.searchState = this.actions[0].property;
                } else {
                    this.searchState = 'keyword';
                }
                this.$emit("cancel", searchKeyword);
                this.$nextTick(() => {
                    this.$refs.searchRef.blur();
                })
            } else {
                return searchKeyword;
            }
        },
        /**聚焦 */
        handleSearchFocus(initiative) {
            let tgSearch = document.querySelector("input.van-field__control");
            console.log(' handleSearchFocus focus :>>>>>>>>>>>>>>>>>>>>>',this.searchText);
            console.log(' handleSearchFocus initiative :>>>>>>>>>>>>>>>>>>>>>',initiative);
            if (this.keywordList.length) {
                this.searchText = this.keywordList[0].value;
                this.keywordList_ori = this.keywordList;
                this.keywordList = [];
            }
            this.$nextTick(() => {
                tgSearch.select(); // 全选文本
                if (this.searchText) {
                    this.showPopover = true;
                }
                console.log(' handleSearchFocus focus end :>>>>>>>>>>>>>>>>>>>>>',this.searchText);
                this.$emit('focusSearch');
            });
        },
        /**失去聚焦 */
        handleSearchBlur() {
            if (this.keywordList_ori.length) {
                // // 定时返回搜索后的状态
                this.timerKL = setTimeout(() => {
                    this.keywordList = this.keywordList_ori;
                    this.keywordList_ori = [];
                    this.clearText();
                    this.timerKL = null;
                }, 100);
            }
            this.$nextTick(() => {
                this.$emit('blurSearch');
            });
        },
        /**输入进行时 */
        handleSearchInput(val) {
            console.log(' handleSearchInput 组件inputting :>>>>>>>>>>>>>>>>>>>>>', val);
            if (val.trim()) {
                this.showPopover = true;
            } else {
                this.showPopover = false;
            }
            // this.searchText = val;
            // this.$emit('inputSearch');
        },
        _fnGetKeyword(item) {
            if (!this.searchText) {
                return;
            }
            let obj;
            this.keywordList = [];
            if (typeof item == 'object') {
                obj = item;
            } else {
                obj = {
                    title: '全部',
                    property: 'keyword',
                };
            }
            obj.value = this.searchText;
            this.searchState = obj.property;
            this.keywordList.push(obj);
            console.log('_fnGetKeyword this.keywordList :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(this.keywordList));
        },
        clearText() {
            this.searchText = '';
        },
        /**扫码事件 */
        handleScan() {
            this.$emit('scan-click', this.searchState);
            this.showPopover = false;
        },
        /**点击右插槽 */
        handleClickRight() {
            this.$emit('click-right-btn');
        }
    },

    filters: {
        actionTextFilter(title) {
            return title == '全部' ? '任一' : title;
        }
    }
};
</script>

<style lang="less">
@import url("../assets/css/lj-pda");

#searchbar-widget {
    display: flex;
    .search-widget {
        display: flex;
        width: 100%;
        background-color: #fff;
        .van-search__content {
            border-radius: 8px;
        }
        .search-label-box {
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .search-tag {
            margin-left: 5px;

            .tag-title {
                position: relative;
                font-size: 12px;
                padding-right: 4px;
                margin-right: 4px;
                // opacity: 0.8;

                &::before {
                    content: '';
                    position: absolute;
                    right: 0;
                    top: 0;
                    bottom: 0;
                    margin: auto;
                    width: 1px;
                    height: 10px;
                    // background-color: rgba(255, 255, 255, 0.6);
                    background-color: #57b9ff;
                }
            }
            .van-tag + .van-tag {
                margin-left: 2px;
            }
        }
    }
    .search-model {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
        color: @secondary;
    }
    // .search-cancel {
    //     // font-size: 12px;
    //     color: @secondary;
    // }
    .search-recommend-popover {
        display: block;
        flex: 1;
    }
    .van-popover {
        width: -moz-calc(~"100% - 20px");
        width: -webkit-calc(~"100% - 20px");
        width: calc(~"100% - 20px");
        .van-popover__action {
            width: 100%;
        }
    }
    .recommend-list {
        .iconfont {
            font-size: 14px;
            margin-right: 4px;
        }
        &.tobe-search {
            color: @musePrimary;
        }
    }
    .right-icon-box {
        display: flex;
        justify-content: center;
        align-items: center;

        .iconfont {
            color: @primary;
            font-size: 18px;
        }
    }
    .right-part {
        flex-shrink: 0;
        position: relative;
        display: flex;
        justify-content:  center;
        align-items: center;
        margin-right: 10px;
        padding-left: 15px;

        .iconfont {
            font-size: 16px;
        }

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            height: 16px;
            width: 1px;
            background-color: @museTrack;
            opacity: 0.8;
        }
        &.filtering {
            color: @musePrimary;
        }
    }
}
</style>