<!--高级筛选条件操作块-->
<!--events-->
<!--搜索按钮点击事件on-query-submit，参数为当前设置的值(value)-->
<!--选择框点击事件field-click，参数({property})，需要调用树形选择时使用-->
<!--条件值改变field-change，参数({property,vale})，一般为checkbox或选择框使用-->
<!--methods-->
<!--直接设置条件的值setQueryParam(property, value)-->

<template>
    <div>
        <template v-for="field in queryFields">
            <lj-select v-if="field.selectOptions" :title="field.title" v-model="currentQueryParams[field.property]"
                       full-width
                       class="row"
                       :disabled="field.disabled"
                       :options="field.selectOptions.options"
                       :value-map="field.selectOptions.valueMap"
                       :options-api="field.selectOptions.optionsApi"
                       :extra-options="field.selectOptions.extraOptions"
                       @click.native="$emit('field-click',{property:field.property})"
                       @change="handleFieldChange(field,$event)"
                       @change-get-label="handleFieldChangeLabel(field, $event)"/>
            <mu-date-input v-else-if="field.type === 'date'" :label="field.title"
                           v-model="currentQueryParams[field.property]"
                           full-width
                           class="row"
                           :disabled="field.disabled"
                           :type="field.ctype || 'date'"
                           :format="field.format"
                           :value-format="field.format || 'YYYY-MM-DD'" container="dialog"/>
            <mu-switch v-else-if="field.type === 'checkbox'"
                       :label="field.title"
                       label-left
                       v-model="currentQueryParams[field.property]"
                       full-width
                       class="row"
                       style="width: 100%;"
                       :disabled="field.disabled"
                       @change="handleFieldChange(field,$event)"/>
            <mu-text-field v-else :label="field.title" v-model="currentQueryParams[field.property]" class="row"
                           full-width
                           :placeholder="field.hint"
                           :disabled="field.disabled"/>
        </template>
        <div v-if="showScan">
            <mu-button icon @click="handleScan">
                <i class="iconfont icon-qrcode-scan"></i>
            </mu-button>
        </div>
        
        <div style="text-align: center">
            <!-- <mu-button color="info" @click="resetQueryParms">重置</mu-button> -->
            <mu-button color="primary" @click="submitQueryParams">搜索</mu-button>
        </div>
    </div>
</template>

<script>
    import LjSelect from "components/lj-select";

    export default {
        name: "lj-query-list",
        props: {
            queryFields: {
                type: Array
                // {
                //     title: 字段描述
                //     property：字段属性名
                //     type: 默认为文字input，可选项 checkbox/date
                //     selectOptions：不为空时，显示为选择控件，详细参数见lj-select
                //     hint：输入框提示信息
                //     disabled： 是否不可用
                //     initValue：初始值
                //     initDateAdd：初始日期递推，如-7，默认值为当前时间前7日
                //     staticDateInit: 初始日期，只用于用户没有用户习惯之前的值
                //     valueMap： 用于条件值输出时，checkbox类型的值转换，默认[0,1]，如需输出boolean类型，需声明为[false,true]
                // }
                // 示例↓↓↓↓
                // [
                //     {title: "单号", property: "ordercode"},
                //     {
                //         title: "状态",
                //         property: "status",
                //         selectOptions: {options: [{status: 0, dscrp: "待审核"},{status: 1, dscrp: "在进行"}], valueMap: ["status", "dscrp"]},
                //         disabled: true
                //     },
                //     {title: "开始时间", property: "begindate", type: "date", initValue: "2018-10-08"},
                //     {title: "结束时间", property: "enddate", type: "date", initDateAdd: -7}
                // ]
            },
            // 用于读写用户习惯，此筛选条件对应的key
            habitKey: {
                type: String
            },
            // 不可修改的强制条件，会集成在on-query-submit事件的参数输出
            // （如包含在queryFields中，则显示为不可用状态，否则不显示）
            hardParms: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            // 绑定外部数据源，当外部数据发生改变，相应筛选条件的值也会同步
            bindingParms: {
                type: Object
            },
            showScan: {
                type: Boolean,
                default:false
            },
            // 是否自动刷新
            autoRefresh: {
                type: Boolean,
                default: false
            },
        },
        mounted() {
            this.hardProperties = "";
            for (let prop in this.hardParms) {
                this.hardProperties += "," + prop;
            }
            this.initQueryParams();
            if (this.autoRefresh) {
                this.submitQueryParams();
            }
        },
        data() {
            return {
                initParams: {},
                currentQueryParams: {},
                habitFields: [],
                hardProperties: "",
                fieldMap: {}
            }
        },
        methods: {
            resetQueryParms() {
                this.currentQueryParams = Object.assign({}, this.initParams, this.hardParms);
            },
            initQueryParams() {
                let self = this;
                let thisHabit = {};
                if (this.habitKey) {
                    let userhabit = $lj.getStorage("userQueryHabit") || {};
                    thisHabit = userhabit[this.habitKey] || thisHabit;
                }
                let result = {};
                this.queryFields.forEach((field) => {
                    self.fieldMap[field.property] = field;
                    if (self.isHardField(field.property)) {
                        field.disabled = true;
                    }
                    let thisValue = field.initValue;
                    if (typeof thisValue !== "undefined") {
                        result[field.property] = thisValue;
                    } else if (typeof field.initDateAdd !== "undefined") {
                        result[field.property] = $lj.dateAdd(new Date(), 0, 0, field.initDateAdd);
                    } else if (!self.isHardField(field.property)) {
                        if (field.selectOptions) {
                            self.habitFields.push(field);
                            if (typeof thisHabit[field.property] !== "undefined") {
                                result[field.property] = thisHabit[field.property];
                            } else {
                                result[field.property] = undefined;
                            }
                        } else if (field.type === 'checkbox') {
                            if (!field.valueMap) {
                                field.valueMap = [0, 1];
                            }
                            self.habitFields.push(field);
                            if (typeof thisHabit[field.property] !== "undefined") {
                                result[field.property] = thisHabit[field.property];
                            } else {
                                result[field.property] = false;
                            }
                        } else if (field.type === 'date') {
                            if (typeof thisHabit[field.property] !== "undefined") {
                                result[field.property] = $lj.dateAdd(new Date(), 0, 0, thisHabit[field.property]);
                            } else {
                                result[field.property] = field.staticDateInit ? $lj.dateAdd(new Date(), 0, 0, field.staticDateInit) : new Date();
                            }
                            self.habitFields.push(field);
                        }
                    }
                    self.handleFieldChange(field, result[field.property]);
                });
                this.initParams = result;
                this.resetQueryParms();
            },
            submitQueryParams() {
                if (this.habitKey) {
                    if (this.habitFields.length > 0) {
                        let self = this;
                        let userhabit = $lj.getStorage("userQueryHabit") || {};
                        let thisHabit = userhabit[this.habitKey] || {};
                        this.habitFields.forEach((field) => {
                            if (field.type === 'date') {
                                thisHabit[field.property] = $lj.getDiffDays(new Date(), self.currentQueryParams[field.property]);
                            } else {
                                thisHabit[field.property] = self.currentQueryParams[field.property];
                            }
                        });
                        userhabit[this.habitKey] = thisHabit;
                        $lj.setStorage("userQueryHabit", userhabit);
                    }
                }
                let filtedResult = Object.assign({}, this.currentQueryParams);
                for (let prop in filtedResult) {
                    if (this.fieldMap[prop]) {
                        if (this.fieldMap[prop].type === 'checkbox') {
                            let valueMap = this.fieldMap[prop].valueMap;
                            if (filtedResult[prop]) {
                                filtedResult[prop] = valueMap[1];
                            } else {
                                filtedResult[prop] = valueMap[0];
                            }
                        }
                    }
                }
                this.$emit('on-query-submit', filtedResult);
            },
            isHardField(property) {
                if (property) {
                    return this.hardProperties.indexOf(',' + property) >= 0;
                }
                return false;
            },
            setQueryParam(property, value) {
                this.$set(this.currentQueryParams, property, value);
            },
            handleFieldChange(field, value) {
                this.$emit("field-change",{property: field.property, value: value});
            },
            handleFieldChangeLabel(field, label) {
                this.$emit("change-label", {property: field.property, label: label});
            },
            handleScan(){
                this.$emit("scan-click");
            }
        },
        watch: {
            bindingParms: {
                handler(newVal, oldVal) {
                    if (newVal) {
                        for (let prop in newVal) {
                            this.setQueryParam(prop, newVal[prop]);
                        }
                    }
                },
                deep: true
            }
        },
        components: {
            LjSelect
        }
    }
</script>

<style scoped>
    .row {
        margin-bottom: 0;
    }
</style>
