<template>
    <div class="searchFilterWrap" ref="searchFilterWrap" v-show="showSearch">
        <el-form
            @submit.native.prevent
            :model="searchFormParam.queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            class="row"
        >
            <!-- 这里循环 dataSource -->
            <el-form-item
                v-for="(formData, index) in searchFormParam.dataSource"
                :key="formData.key"
                :label="formData.label"
                :prop="formData.key"
                v-show="isShowField(index)"
                :class="{'col': true, 'col-6': fixedColumn === 4, 'col-8': fixedColumn === 3, 'col-12': fixedColumn === 2, 'col-24': fixedColumn === 1}"
            >
                <el-input
                    v-if="formData.itemType === 'input'"
                    v-model="searchFormParam.queryParams[formData.key]"
                    :placeholder="formData.placeholder" clearable
                    @keyup.enter.native="formData.onEnterKeyUp"
                />
                <el-date-picker
                    v-if="formData.itemType === 'datePicker'"
                    v-model="searchFormParam.queryParams[formData.key]"
                    value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                    :default-time="['00:00:00', '23:59:59']"
                    :style="{width: '100%'}"
                />
                <el-select
                    v-if="formData.itemType === 'select'"
                    v-model="searchFormParam.queryParams[formData.key]"
                    :placeholder="formData.placeholder"
                    filterable clearable
                    :multiple="formData.multiple"
                    :style="{width: '100%'}"
                    @change="selectChage($event,formData)"
                >
                    <el-option
                        v-for="(option, i) in formData.options"
                        :key="i"
                        :label="option.label"
                        :value="option.value"
                        :disabled="option.disabled"
                    />
                </el-select>
            </el-form-item>

            <!-- 填充物 为保证搜索栏一直在最右边 -->
            <el-form-item
                v-for="fillItem in fillItems"
                :key="fillItem.key"
                :class="{'col': true, 'primaryOptions':true, 'col-6': fixedColumn === 4, 'col-8': fixedColumn === 3, 'col-12': fixedColumn === 2, 'col-24': fixedColumn === 1}"
            />

            <!-- 搜索栏 -->
            <el-form-item
                :class="{'col': true, 'primaryOptions':true, 'col-6': fixedColumn === 4, 'col-8': fixedColumn === 3, 'col-12': fixedColumn === 2, 'col-24': fixedColumn === 1}"
            >
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                <a v-show="isShowExpand" v-if="expandForm" class="expand" v-on:click="toggleForm"> 收起 ∧ </a>
                <a v-show="isShowExpand" v-if="!expandForm" class="expand" v-on:click="toggleForm"> 展开 ∨ </a>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
// 获取col宽度
function getLayout (width, defaultCols) {
    let layout = {
        span: 24,
        type: "xs"
    };

    if (width >= 1350) {
        // xxl
        layout = {
            span: 6,
            type: "xxl"
        }
    } else if (width >= 1050) {
        // xl
        layout = {
            span: 8,
            type: "xl"
        }

    }
    else if (width >= 645) {
        // md
        layout = {
            span: 12,
            type: "md"
        }
    } else {
        // xs 手机
        layout = {
            span: 24,
            type: "xs"
        }
    }

    if (defaultCols || defaultCols > 0) {
        const curSpan = 24 / (defaultCols <= 4 ? defaultCols : 4);
        layout = {
            span: curSpan > layout.span ? curSpan : layout.span,
            type: `custom_${layout.type}`
        };
    }

    return layout;
}

export default {
    name: "SearchForm",
    props: {
        // dataSource: Array<SearchFormDataSource>,
        searchFormParam: {
            queryParams: {
                type: Object,
                default: {},
            },
            dataSource: {
                type: Array,
                default: [],
            },
        },
        showSearch: {
            type: Boolean,
            default: true,
        },
    },
    data() {
        return {
            fixedColumn: 4,  // 固定列 0 ~ 4，这里默认为4
            // fixedColumn: 24 / layout,
            isShowExpand : this.searchFormParam.dataSource.length > 3, // 是否显示展开列表按钮
            expandForm: false, // 搜索表单是否展开
            fillItems: [], // 填充物, 用于补位
        };
    },

    mounted() {
        const _this = this;
        // 给列数初始化数值
        this.fixedColumn = 24 / getLayout(this.$refs.searchFilterWrap.offsetWidth || 0).span;
        this.isShowExpand = this.searchFormParam.dataSource.length - this.fixedColumn > -1;
        this.setFillItems();

        // 监听窗口变化
        window.onresize = () => {
            return (() => {
                this.$nextTick(() => {
                    // console.log('this.$refs.wrapper', this.$refs)
                    const layout = getLayout(this.$refs.searchFilterWrap.offsetWidth || 0);
                    _this.fixedColumn = 24 / layout.span;
                    _this.isShowExpand = _this.searchFormParam.dataSource.length - _this.fixedColumn > -1;
                    _this.setFillItems();
                })
            })()
        }
    },
    methods: {
        /** 搜索 */
        handleQuery(...prop) {
            let _this = this;
            // 判断父组件是否自定义handleQuery方法
            if(_this.$listeners['handleQuery']) {
                this.$emit('handleQuery', prop);
                return;
            }
            // 通用搜索流程（目前未定义）
        },

        /** 选择 */
        selectChage(e,params){
          console.log('选择',e,params);
          this.$emit('selectChage',{
            value:e,
            type: params.key,
            book: params.isNet,
          });
          this.$forceUpdate();
        },

        /** 重置 */
        resetQuery(...prop) {
            let _this = this;
            // 判断父组件是否自定义resetQuery方法
            if(_this.$listeners['resetQuery']) {
                this.$emit('resetQuery', prop);
                return;
            }
            this.resetForm("queryForm");
        },

        /** 展开按钮点击 */
        toggleForm() {
            this.expandForm = !this.expandForm;
            this.setFillItems();
        },

        /**
         * 判断该表单元素是否显示
         * @param {} index
         */
        isShowField(index) {
            // 第一条数据默认显示
            if(index === 0) {
                return true;
            }
            // 如果是固定显示的行(指第一行)
            if(index < this.fixedColumn && this.showSearch) {
                // 判断是否等于列数 并且此时列表未展开状态
                if(index === this.fixedColumn - 1 && !this.expandForm) {
                    return false;
                }
                return true;
            }

            // 如果不是固定显示的行
            // 判断是否展开状态
            if(this.expandForm) {
                return true;
            }

            return false;
        },

        setFillItems() {
            //fixedColumn - searchFormParam.dataSource.length % fixedColumn - 1
            let itemLength = 0;
            const itemList = new Array();
            if(this.needFillItem()) {
                itemLength = this.fixedColumn - this.searchFormParam.dataSource.length % this.fixedColumn - 1;
            }
            for(let i=0; i<itemLength; i++) {
                itemList.push({key: i});
            }
            this.fillItems = itemList;
        },

        /**
         * 判断是否需要填充
         */
        needFillItem() {
            const column = this.fixedColumn;
            const dataLength = this.searchFormParam.dataSource.length;
            // 如果只显示1列 或者刚好1行能显示完
            if(column === 1 || dataLength === column -1) {
                return false;
            }

            // 判断表单数量是否超过显示列
            if(dataLength > column -1) {
                // 如果没显示更多
                if(!this.expandForm) {
                    return false;
                }
                // 显示更多
                // 判断如果多余的空格待填充
                if(dataLength % column + 1 < column) {
                    return true;
                }
                return false;
            }
            // 没有超过时
            return true;
        },

    },
}
</script>

<style scoped lang="scss">
.searchFilterWrap {
    margin-bottom: 5px;

    .row {
        display: flex;
        flex-flow: row wrap;
    }

    .row::before, .row::after {
        display: flex;
    }

    .col {
        display: flex;
        position: relative;
        max-width: 100%;
        min-height: 1px;
        margin: 0;
        padding: 0px 5px 18px 0px;
        box-sizing: border-box;
    }

    .col-6 {
        flex: 0 0 25%;
        max-width: 25%;
    }

    .col-8 {
        flex: 0 0 33.333333%;
        max-width: 33.333333%;
    }

    // 双行样式
    .col-12 {
        flex: 0 0 50%;
        max-width: 50%;
    }

    .col-24 {
        flex: 0 0 100%;
        max-width: 100%;
    }


    ::v-deep .el-form-item__label {
        width: 95px;
        white-space: nowrap;
        flex: 0 0 auto;
    }

    ::v-deep .el-form-item__label::after {
        content: ":";
        position: relative;
        top: -0.5px;
        margin: 0px 8px 0px 2px;
    }

    ::v-deep .el-form-item__content {
        position: relative;
        padding: 0 20px 0 0;
        max-width: 100%;
        min-height: 1px;
        // display: inline-block;
        // vertical-align: top;
        flex: 100%;
    }

    .primaryOptions {
        text-align: right;
        .expand {
            margin: 0 5px;
            color: #1890ff;
            text-decoration: none;
            background-color: transparent;
            outline: none;
            cursor: pointer;
            transition: color .3s;
        }
    }
}
</style>


