<template>
    <div id="CommonForm">
        <el-form ref="form" size="small" :model="form" :rules="rules" class="demo-ruleForm">
            <el-form-item v-for="(item, index) in formArr" :key="`formItems${index}`" :label="item.label" :prop="item.prop" :label-position="item.labelPosition || 'right'">
                <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>
                    <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]" :props="{ checkStrictly: true }" class="full-width" :options="item.options" :show-all-levels="false" clearable @change="formItemChange($event, item)" />
                <DatePicker
                    v-else-if="item.dateType === 'datePicker'"
                    ref="DatePicker"
                    class="full-width"
                    :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)"
                />
                <!-- 多选 -->
                <el-checkbox-group v-else-if="item.type === 'checkbox'" v-model="model[item.prop]" class="full-width" size="mini" @change="formItemChange($event, item)">
                    <el-checkbox v-for="(cItem, cIndex) in item.options" :key="`options${item.prop}${cIndex}`" :label="cItem.value" :disabled="cItem.disabled">{{ cItem.name }}</el-checkbox>
                </el-checkbox-group>
                <el-input v-else-if="item.type === 'textarea'" v-model="model[item.prop]" clearable type="textarea" rows="1" />
            </el-form-item>
            <div class="flex-center">
                <el-button type="primary" size="small" @click="submitForm()">提 交</el-button>
                <el-button size="small" @click="cancel()">取 消</el-button>
            </div>
        </el-form>
    </div>
</template>

<script>
import DatePicker from './DatePicker';
import TooltipOver from './TooltipOver.vue';
export default {
    name: 'CommonForm',
    components: {
        DatePicker,
        TooltipOver
    },
    props: {
        model: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            tempModel: {},
            valid: false,
            form: {},
            formArr: [],
            rules: {}
        };
    },
    watch: {
        model: {
            handler(val) {
                this.tempModel = this.deepClone(val);
                this.handleData();
            },
            deep: true,
            immediate: true
        },
        formArr: {
            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.formArr = this.model['formArr'] || [];
            this.rules = this.model['rules'] || {};
        },
        // 提交
        submitForm() {
            const valid = this.validateForm();
            if (valid) {
                this.$emit('submitForm');
            }
        },
        // 重置
        cancel() {
            this.$emit('cancel');
        },
        resetFormValidate() {
            this.$nextTick(() => {
                this.$refs['form'].clearValidate();
            });
        },
        // 对部分进行校验
        formItemChange(val, item) {
            // 改变值
            const formObj = {
                prop: item.prop,
                val: val
            };
            this.$emit('changeFormItem', formObj);
        },
        // 数据提交校验
        validateForm() {
            let flag = false;
            this.$refs['form'].validate(valid => {
                flag = valid;
            });
            return flag;
        },
        resetForm() {
            this.$nextTick(() => {
                this.$refs['form'].clearValidate();
                this.$refs['form'].resetFields();
            });
        }
    }
};
</script>

<style lang="less" scoped>
#CommonForm {
	.demo-ruleForm {
		margin-right: 20px;
	}
	overflow: auto;
	.full-width {
		width: 100%;
	}
}
</style>
