<template>
    <div id="FilterQuery">
        <div class="full-width flex flex-align-end">
            <el-form ref="ruleForm" class="full-width" label-position="right" :model="form" :rules="rules" inline :validate-on-rule-change="false" size="small" :class="model.formClass">
                <el-form-item v-for="(item, index) in filterArr" :key="index" :prop="item.prop" :class="item.formItemClass">
                    <span slot="label">
                        <TooltipOver v-if="judgeEmpty(item.label)" class="label-tooltip-over" :content="`${item.label}`" :ref-name="`label${item.prop}`" />
                    </span>
                    <el-input v-if="item.type === 'input' || !judgeEmpty(item.type)" v-model="form[item.prop]" :class="item.class" :maxlength="item.maxlength" :show-word-limit="item.showWordLimit" clearable autocomplete="off" :placeholder="item.isNoPlaceholder ? '' : '请输入'" @change="formItemChange($event, item)" />
                    <el-input v-else-if="item.type === 'inputNum'" v-model="form[item.prop]" oninput="value=value.replace(/^\.+|[^\d.]/g,'')" :maxlength="item.maxlength" :show-word-limit="item.showWordLimit" clearable :class="item.class" autocomplete="off" :placeholder="item.isNoPlaceholder ? '' : '请输入'" @change="formItemChange($event, item)" />
                    <el-select v-else-if="item.type === 'select'" v-model="form[item.prop]" clearable :class="item.class" :placeholder="item.isNoPlaceholder ? '' : '请选择'" class="full-width" @change="formItemChange($event, item)">
                        <el-option v-for="(cItem, cIndex) in item.options" :key="`options${item.prop}${cIndex}`" :label="cItem.name" :value="cItem.value" />
                    </el-select>
                    <!-- 下拉可搜索 -->
                    <el-select v-else-if="item.type==='selectSearch'" v-model="form[item.prop]" clearable :placeholder="item.isNoPlaceholder ? '' : '请选择'" :filterable="item.filterable">
                        <el-option v-for="(cItem,cIndex) in item.options" :key="`selectSearch${item.prop}${cIndex}`" :label="cItem.name" :value="cItem.value" />
                    </el-select>
                    <el-cascader v-else-if="item.type === 'cascader'" :key="item.refresh" v-model="form[item.prop]" :filterable="item.filterable" :props="item.props || { checkStrictly: true }" class="full-width" :options="item.options" :show-all-levels="item.showAllLevels || true" clearable @change="formItemChange($event, item)" />
                    <DatePicker
                        v-else-if="item.dateType === 'datePicker'"
                        ref="DatePicker"
                        :type="item.type"
                        :select-date-range="item.selectDateRange"
                        :total-date-range="item.totalDateRange"
                        :value-format="item.valueFormat"
                        :default-time="item.defaultTime"
                        :date-range="item.dateRange"
                        :is-limit-date-range="item.isLimitDateRange"
                        :has-date-picker="item.hasDatePicker"
                        :initial-value="item.initialValue"
                        :has-quick-item="item.hasQuickItem"
                        :placeholder="item.isNoPlaceholder ? '' : item.placeholder ? item.placeholder : '请选择'"
                        @getDateRange="formItemChange($event, item)"
                    />
                    <!-- 定制数据框 -->
                    <div v-else-if="item.type === 'specialInput'" class="border flex-center inline-block special-input-box">
                        <el-input v-model="form[item.minProp]" clearable class="border-none min-input" autocomplete="off" :placeholder="item.minPlaceholder || '请输入'" @change="formItemChange($event, item)" />
                        <span>-</span>
                        <el-input v-model="form[item.maxProp]" clearable class="border-none max-input" autocomplete="off" :placeholder="item.maxPlaceholder || '请输入'" @change="formItemChange($event, item)" />
                    </div>
                    <CyTreeSelect
                        v-else-if="item.type === 'treeSelect'"
                        v-model="form[item.prop]"
                        filterable
                        :data="item.options"
                        :filter-able="item.filterable"
                        :multiple="item.multiple"
                        :relate="item.relate"
                        :need-slot="item.needSlot"
                        :node-key="item.nodeKey"
                        :disabled="item.disabled"
                        :need-select="item.needSelect"
                    />
                </el-form-item>
            </el-form>
            <div v-if="judgeEmpty(queryButtons)" :class="model.queryBtnsClass" class="flex mb20 ml48">
                <div v-for="(item, index) in queryButtons" :key="item.key" :class="index < queryButtons.length - 1 ? 'mr10' : ''">
                    <el-button v-preventReClick size="small" :class="item.class" :type="item.type" :disabled="item.isDisabled" :icon="item.icon" @click="handleClick(item)">
                        {{ item.label }}
                    </el-button>
                </div>
            </div>
        </div>
        <div v-if="judgeEmpty(moreFilterArr)" class="more-box border-top mb32 mt12 ps-r">
            <span class="handle-more pointer ft12" @click="handleMore">{{ moreFlag ? '收起' : '展开' }}
                <i class="more-flag-icon" :class="moreFlag ? 'el-icon-arrow-up': 'el-icon-arrow-down'" />
            </span>
        </div>
    </div>
</template>

<script>
import DatePicker from './DatePicker';
import CyTreeSelect from './TreeSelect';
import { commonFilterButtons } from '@/constant';
import { commonFuncMixin } from '@/mixins/commonFuncMixin';
import { isEmpty } from '@/tool/func';
import { TooltipOver } from '@/components';
export default {
    name: 'FilterQuery',
    components: {
        DatePicker,
        TooltipOver,
        CyTreeSelect
    },
    mixins: [commonFuncMixin],
    props: {
        model: {
            type: Object,
            default: () => { }
        }
    },
    data() {
        return {
            // 数据源
            form: {},
            // 初始数据源
            tempModel: {},
            // 重置，搜索等按钮数组,不传默认是重置和搜索
            queryButtons: [],
            // 筛选项的数组
            filterArr: [],
            // 收起的时候筛选数组
            tempFilterArr: [],
            // 展开的筛选数组
            moreFilterArr: [],
            // 是否有展开收起功能
            hasMoreFilter: false,
            // 展开收起
            moreFlag: false,
            rules: {}
        };
    },
    watch: {
        model: {
            handler(val) {
                this.tempModel = this.deepClone(val);
                const moreFilterArr = this.tempModel['moreFilterArr'] || [];
                const tempFilterArr = this.tempModel['filterArr'] || [];
                this.moreFilterArr = this.deepClone(moreFilterArr);
                this.tempFilterArr = this.deepClone(tempFilterArr);
                this.handleData();
            },
            deep: true,
            immediate: true
        },
        filterArr: {
            handler(val) {
                val.forEach(item => {
                    if (item.type === 'date' || item.type === 'week' || item.type === 'month' || item.type === 'year' || item.type === 'dates' || item.type === 'datetime' || item.type === 'daterange' || item.type === 'datetimerange' || item.type === 'time' || item.type === 'monthrange') {
                        item['dateType'] = 'datePicker';
                    }
                });
            },
            deep: true,
            immediate: true
        }

    },
    mounted() {
        this.handleData();
    },
    methods: {
        // 处理数据
        handleData() {
            this.form = this.model.form || {};
            this.rules = this.model['rules'] || {};
            this.filterArr = this.moreFlag ? [...this.tempFilterArr, ...this.moreFilterArr] : [...this.tempFilterArr];
            console.log('filterArr', this.filterArr);
            this.getFilterButtons();
        },
        handleMore() {
            this.moreFlag = !this.moreFlag;
            this.filterArr = this.moreFlag ? [...this.tempFilterArr, ...this.moreFilterArr] : [...this.tempFilterArr];
        },
        // 重置校验
        resetFormValidate() {
            this.$nextTick(() => {
                this.$refs['ruleForm'].clearValidate();
            });
        },
        // 对部分进行校验
        formItemChange(val, item) {
            // 改变值
            if (item.prop) {
                const formObj = {
                    prop: item.prop,
                    val: val
                };
                this.$emit('formItemChange', formObj);
            }
        },
        // 数据提交校验
        validateForm() {
            let flag = false;
            this.$refs['ruleForm'].validate(valid => {
                flag = valid;
            });
            return flag;
        },
        // 按钮点击
        handleClick(item) {
            if (item.click === 'resetClick') {
                if (this.$refs['DatePicker'] && this.$refs['DatePicker'].length) {
                    this.$refs['DatePicker'].forEach(dp => {
                        dp.clear();
                    });
                }
            }
            this.$emit(item.click);
        },
        getFilterButtons() {
            // 是否存在自定义筛选按钮
            // 如果不传isNoFilterButtons为true,默认有 查询和重置按钮document.cre
            if (isEmpty(this.model['filterButtons']) && !this.model['isNotFilterButtons']) {
                this.queryButtons = [...commonFilterButtons];
            } else {
                this.queryButtons = [...this.model['filterButtons']];
            }
        }
    }
};
</script>

<style lang='less' scoped>
#FilterQuery {
	.special-input-box {
		border-radius: 4px;
	}
	.more-box {
		// height: 26px;
		// margin-right: 10px;
		// margin-left: 5px;

		.handle-more {
			display: inline-block;
			width: 80px;
			height: 20px;
			text-align: center;
			color: var(--themeColor);
			position: absolute;
			left: calc(50% - 40px);
			top: -20px;
			background: var(--litterThemeColor);
			border-radius: 12px 12px 0px 0px;
		}
	}
}
</style>
