/*
 * @author 张志成
 * @description 新增/删除表单组件
 * @create 20181225
 */ 

<template>
    <div class="form-copy-wrapper">
        <template v-if="Array.isArray(formCopyConfigs.data)">
            <div v-for="(formCopyItem, index) in formCopyConfigs.data"
                 :key="formCopyItem.timestamp"
                 class="form-copy-item">
                <!-- title -->
                <div v-if="formCopyItem.formConfig.data[0].titles"
                     class="title-wrapper">
                    <span class="title-text">
                        {{ `${formCopyItem.formConfig.data[0].titles} ${index+1}` }}
                    </span>
                    <i v-if="formCopyConfigs.data.length > 1 && !formCopyConfigs.readonly"
                       @click="() => handleFormDelete(index)"
                       class="btn-delete el-icon-close" />
                </div>
                <bk-form ref="formGroupItem"
                         :formConfig="formCopyItem.formConfig"
                         @change="(params) => pushFormParamsToFormResults(params, index)" />
            </div>

            <!-- 新增按钮 -->
            <div v-if="!formCopyConfigs.readonly
                     && formCopyConfig.button
                     && Array.isArray(formCopyConfig.button.data)"
                 class="btn-content-wrapper">
                <template v-for="btn of formCopyConfig.button.data">
                    <el-button :icon="btn.icon"
                               v-if="btn.limit ? formCopyConfig.data.length < btn.limit : true"
                               @click="() => handleBtnClick(btn)"
                               class="btn-save">
                        {{ btn.label }}
                    </el-button>
                </template>
            </div>
        </template>
    </div>
</template>

<script>
import Lodash from 'lodash';

export default {
    name: 'BkFormCopy',
    props: {
        formCopyConfig: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            formResults: [], // 所有的表单参数集合
            formCopyConfigs: {} // 格式化后的组件配置
        };
    },
    watch: {
        // 监听表单集合的变化，回传父组件
        formResults: {
            handler(val) {
                this.$emit('change', val);
            },
            deep: true
        },
        formCopyConfig: {
            handler() {
                this.formatConfig();
            },
            deep: true
        }
    },
    created() {
        this.formatConfig();
    },
    methods: {
        /**
         * 拷贝一份新的表单
         */
        handleFormCopy() {
            const timestamp = new Date().getTime();
            const formCopyItem = Lodash.cloneDeep(this.formCopyConfigs.data[0]);
            // 清空initParams，避免连带初始化数据也一起拷贝
            formCopyItem.formConfig.initParams = {};
            // bk-form的数据结构添加了一层data,不能直接获取data
            formCopyItem.formConfig.data[0].data.forEach(item => {
                const node = item;
                if (node.name === 'timestamp') {
                    node.default = timestamp;
                }
            });
            formCopyItem.timestamp = timestamp;
            this.formCopyConfigs.data.push(formCopyItem);
        },

        /**
         * 格式化父组件的配置
         */
        formatConfig() {
            // 深度拷贝一份父组件配置，避免源数据污染引起数据混乱
            const formCopyConfigsBak = Lodash.cloneDeep(this.formCopyConfig);
            this.$set(this, 'formCopyConfigs', formCopyConfigsBak);
            const { formCopyConfigs } = this;
            // 1、配置是否存在只读状态，如果存在，则给子组件自动补上只读状态
            if (formCopyConfigs.readonly) {
                formCopyConfigs.data.forEach(item => {
                    const formCopyItem = item;
                    formCopyItem.formConfig.readonly = true;
                });
            }
            // 2、配置是否存在标识时间戳，如果有则继承，没有则取当前时间戳作为标识
            formCopyConfigs.data = formCopyConfigs.data.map(item => {
                const config = Lodash.cloneDeep(item);
                const { formConfig } = config;
                let time = new Date().getTime();
                // 判断每个group组件中是否有初始化值，如果有，说明是编辑状态，反之是新增状态
                if (formConfig.results && formConfig.results.timestamp) {
                    time = formConfig.results.timestamp;
                }
                // 判断是否有时间戳字段，没有则添加，有则不添加
                let hasTimestamp = false;
                formConfig.data[0].data.forEach(key => {
                    if (key.name === 'timestamp') {
                        hasTimestamp = true;
                    }
                });
                if (!hasTimestamp) {
                    formConfig.data[0].data.push({
                        name: 'timestamp',
                        value: time
                    });
                }

                // bk-form的数据结构添加了一层group,不能直接获取data
                formConfig.data[0].data.forEach(key => {
                    if (key.name === 'timestamp') {
                        hasTimestamp = true;
                    }
                });
                if (!hasTimestamp) {
                    formConfig.data[0].data.push({
                        name: 'timestamp',
                        value: time
                    });
                }

                config.timestamp = time;
                return config;
            });
        },

        /**
         * 往formResults中插入表单集合
         * @params [Array] data 单个表单集合属性
         * @params [Array] index 表单索引
         */
        pushFormParamsToFormResults(data, index) {
            this.$set(this.formResults, index, data);
        },

        /**
         * 删除某个表单
         */
        handleFormDelete(i) {
            this.formCopyConfigs.data.splice(i, 1);
            this.formResults.splice(i, 1);
        },

        /**
         * 按钮点击事件
         */
        handleBtnClick(btn) {
            if (typeof btn.click === 'function') {
                btn.click(this);
            } else {
                this.handleFormCopy();
            }
        }
    }
};
</script>
