<template>
    <el-row :gutter="20" class="data-form">
        <el-form label-position="top" ref="form" label-width="300px" :model="form" :rules="rules">
            <template v-if="Object.keys(header).length > 0">
                <p class="title">基础信息</p>
                <el-row :gutter="18">
                    <el-col :span="8" :key="item.path" v-for="item in header.basicInfos.data">
                        <el-form-item
                            :prop="item.path"
                            :label="item.aliasName">
                            <el-input v-model="form[item.path]" :disabled="!item.editable"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="content">
                    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                        <el-tab-pane v-for="(item,index) in paneMsg" :key="index" :label="item"
                                     :name="index.toString()"/>
                    </el-tabs>
                    <div class="table" style="height: 194px;overflow: auto">
                        <el-row :gutter="18">
                            <el-col :span="item.dataType == 'ATTACHMENT'? 24:8"
                                    :key="item.path"
                                    v-for="item in header.dictStages.data"
                                    :style="{ 'height':item.dataType == 'ATTACHMENT'? 'auto':'93px' }"
                            >
                                <el-form-item
                                    :label="item.unit ? item.aliasName + ' (' + item.unit + ')' : item.aliasName">
                                    <el-input
                                        :disabled="!item.editable"
                                        v-if="item.dataType == 'STRING'"
                                        v-model="form[item.path]"/>

                                    <el-input
                                        v-else-if="item.dataType == 'DOUBLE' || item.dataType == 'INTEGER'"
                                        type="number"
                                        v-model="form[item.path]">
                                        <template slot="append" v-if="item.unit">{{ item.unit }}</template>
                                    </el-input>

                                    <el-select
                                        v-else-if="item.dataType == 'MENUM'"
                                        placeholder="请选择"
                                        v-model="form[item.path]"
                                        multiple
                                        collapse-tags>
                                        <el-option :key="index" :label="op.name" :value="op.code"
                                                   v-for="(op,index) in item.dataSource"></el-option>
                                    </el-select>

                                    <el-select
                                        v-else-if="item.dataType == 'ENUM' || item.dataType == 'BOOLEAN'"
                                        placeholder="请选择"
                                        v-model="form[item.path]">
                                        <el-option :key="index" :label="op.name" :value="op.code"
                                                   v-for="(op,index) in item.dataSource"></el-option>
                                    </el-select>
                                    <el-date-picker
                                        v-else-if="item.dataType == 'DATETIME'"
                                        v-model="form[item.path]"
                                        placeholder="选择日期"
                                        format="yyyy 年 MM 月 dd 日"
                                        value-format="yyyy-MM-dd"
                                        type="date">
                                    </el-date-picker>
                                    <uploadImgs
                                        v-else-if="item.dataType == 'ATTACHMENT'&& item.path === 'infos.Pic'"
                                        :readOnly="false"
                                        v-model="form[item.path]"
                                        :keysArr="Array.isArray(form[item.path]) ? form[item.path]:[]"
                                        :context-key="item.path"
                                        :isShow="1"
                                        @change="changeItem"/>

                                    <uploadFiles
                                        v-else-if="item.dataType == 'ATTACHMENT'"
                                        v-model="form[item.path]"
                                        :readOnly="false"
                                        :isShow="1"
                                        :keys-arr="Array.isArray(form[item.path]) ? form[item.path]:[] "
                                        :show-file-list="false"
                                        :context-key="item.path"
                                        @change="changeItem"/>
                                </el-form-item>

                            </el-col>

                        </el-row>
                    </div>
                </div>
            </template>
        </el-form>
    </el-row>
</template>

<script lang="ts">

import {Component, Prop, Vue, Watch} from 'vue-property-decorator'
import uploadFiles from "@/components/public/uploadFiles.vue";
import uploadImgs from "@/components/public/uploadImgs.vue";

function flattenKeys(obj: any) {
    let res = {}

    function isObject(val: any) {
        return typeof val === 'object' && !Array.isArray(val)
    }

    function digKeys(prev: any, obj: any) {
        Object.entries(obj).forEach(([key, value]) => {
            const currentKey = prev ? `${prev}.${key}` : key
            if (isObject(value)) {
                digKeys(currentKey, value)
            } else {
                res[currentKey] = value
            }
        })
    }

    digKeys('', obj)

    return res
}

@Component({
    name: "dataForm",
    components: {uploadFiles, uploadImgs}
})
export default class extends Vue {
    rules = {
        bimTypeId: [{required: true, message: "请填写BIM构件编码", trigger: 'blur'}],
        systemCategory: [{required: true, message: "请填写系统分类", trigger: 'blur'}],
        codeName: [{required: true, message: "请填写设备类型名称", trigger: 'blur'}],
        localId: [{required: true, message: "请填写本地编码", trigger: 'blur'}],
    }
    // tabs数据
    activeName = 0
    header = {}
    form = {}
    paneMsg = []
    // 默认当前阶段
    currentHeader = ''
    @Prop({default: Object}) deviceHeaders ?: {}
    @Prop({default: Object}) currRowContent ?: {}

    @Watch('currRowContent', {immediate: true, deep: true})
    handleRow() {
        this.$nextTick(() => {
            // string =>array key
            this.form = {}
            this.form = Object.keys(this.currRowContent).length > 0 ? flattenKeys(this.currRowContent) : {}
        })

    }

    @Watch('deviceHeaders', {immediate: true, deep: true})
    changeHeaders() {
        this.$nextTick(() => {
            let pic = [], base = []
            if (typeof this.deviceHeaders == 'object' && Object.keys(this.deviceHeaders).length > 0) {
                this.paneMsg = this.deviceHeaders.dictStages.map(i => i.name)
                let currentHeader = this.paneMsg[0]
                this.currentHeader = this.currentHeader || currentHeader
                this.deviceHeaders.dictStages.length > 0 && this.deviceHeaders.dictStages.forEach(item => {
                    if (this.currentHeader == item.name) {
                        item.infos && item.infos.forEach(val => {
                            this.addFormData(val);
                            if (val.dataType == 'ATTACHMENT') {
                                pic.push(val)
                            } else {
                                base.push(val)
                            }
                        })
                    }
                })
                this.deviceHeaders.basicInfos.length > 0 && this.deviceHeaders.basicInfos.forEach(item => {
                    this.addFormData(item)
                })
            }
            this.header = {
                basicInfos: {
                    name: '基础信息台账',
                    data: this.deviceHeaders.basicInfos
                },
                dictStages: {
                    name: this.currentHeader,
                    data: pic.length > 0 ? [...base, ...pic] : [...base]
                }
            }
        })
    }

    addFormData(headerItem: any) {
        if (headerItem.render) {
            const val = headerItem.render(this.currRowContent)
            this.form[headerItem.path] = val
        }
    }

    changeItem(val) {
        console.log(val)
        let _key = Object.keys(val)[0] + '';
        this.form[_key] = val[_key];

    }

    handleClick(val) {
        this.currentHeader = val.label
        this.changeHeaders()
    }

    submitForm(callback) {
        this.$refs.form.validate((valid) => {
            if (valid) {
                callback()
            } else {
                return false;
            }
        });
    }
}

</script>

<style scoped lang="scss">
$border: 1px solid #E1E7EA;
.data-form {
    //.el-upload-dragger {
    //    width: auto;
    //    height: auto;
    //}

    .title {
        border-left: 7px solid;
        text-indent: 10px;
        color: #646C73;
        margin-bottom: 10px;
    }

    .content {
        .table {
            border-left: $border;
            border-right: $border;
            border-bottom: $border;
            height: calc(100% - 41px);
            padding: 12px;
        }
    }
}

</style>
