<template>
    <div class="add-form">
        <el-tabs
            v-model="editableTabsValue"
            type="card"
            :closable="row.closable"
            :addable="row.addable"
            @edit="handleTabsEdit"
            @tab-click="handleClick"
        >
            <el-tab-pane
                v-for="(item, _index) in editableTabs.list"
                :key="item.name"
                :label="item.title"
                :name="item.name"
            >

            </el-tab-pane>
        </el-tabs>
        <template
            v-for="(rule, index) in rules"
            :key="index"
        >
            <el-form-item
                v-if="rule.show === undefined ? true : rule.show(getIndex())"
                :key="itemProp(getIndex() as number, rule)"
                :label="$t(rule.label)"
                :rules="rule.validate"
                :label-width="row.labelWidth"
                :prop="itemProp(getIndex() as number, rule)"
                :test-cy="rule.key + '_' + getIndex()"
            >
                <component
                    :is="rule.type"
                    :row="rule"
                    :modelData="defaultValue.fields"
                    :addIndex="getIndex()"
                />
            </el-form-item>
        </template>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, PropType } from 'vue'
import { ObjectInterface } from '../../../script/index'
import { dynamicInter, EditableTabsInter, AddFormInterface } from './index'
import infoDynamic from '../dynamic/index.vue'
import publicComponent from '../../../script/useComponent'
import { FormRule } from '../formConfig'

export default defineComponent({
    name: 'AddForm',
    components: { infoDynamic, ...publicComponent() },
    props: {
        row: {
            type: Object as PropType<AddFormInterface>,
            default: () => {
            }
        },
        modelData: {
            type: Object,
            default: () => {
            }
        }
    },
    setup (props) {
        const { row, modelData } = props
        const dynamicMap = reactive<ObjectInterface>({})
        const defaultValue = reactive<dynamicInter>({
            fields: []
        })
        const editableTabsValue = ref<string>('1')
        let editableTabs = reactive<EditableTabsInter>({
            list: [{
                title: 'set_1',
                name: '1'
            }]
        })
        const rules = computed(() => {
            const formRule = new FormRule()
            row.rule(formRule)
            return formRule.rule
        })
        const itemProp = computed(() => (index: number, rule: ObjectInterface): string => {
            return `${row.model}[${index}].${rule.model}`
        })
        const addMap = (key: string, data: ObjectInterface): void => {
            dynamicMap[key] = data
        }
        const getIndex = (): string | number => {
            if (row.paneLabel) {
                return Number(editableTabsValue.value)
            } else {
                return (editableTabs.list || []).findIndex(tab => tab.name === editableTabsValue.value)
            }
        }
        const init = (): ObjectInterface => {
            let obj: ObjectInterface = {}
            for (let item of rules.value) {
                obj.rule = 'set_' + editableTabsValue.value
                obj[item.model] = item.type === 'infoSwitch' ? false : item.dynamic ? [] : ''
            }
            return obj
        }
        const handleClick = (panel): void => {
            row.methods?.(panel)
        }
        const handleTabsEdit = (targetName: string, action: string): void => {
            if (action == 'add') {
                // if (modelData.allinputList && editableTabs.list.length >= modelData.allinputList.length) {
                //     return
                // }
                let newTabName = String(Number(editableTabsValue.value) + 1)
                editableTabs.list.push({
                    title: 'set_' + newTabName,
                    name: newTabName
                })
                editableTabsValue.value = newTabName
                let data = init()
                addMap('set_' + editableTabsValue.value, data) // 处理tabs
                defaultValue.fields.push(data)
                row.afterAdd?.(data)
            }
            if (action === 'remove') {
                if (Object.keys(dynamicMap).length === 1 && !row.addable) {
                    return
                }
                let tabs = editableTabs.list
                let activeName = editableTabsValue.value
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1]
                            if (nextTab) {
                                activeName = nextTab.name
                                editableTabsValue.value = activeName
                            }
                        }
                    })
                }
                delete dynamicMap['set_' + targetName]
                let fieldsIndex = (editableTabs.list || []).findIndex((tab) => tab.name === targetName)
                fieldsIndex >= 0 && defaultValue.fields.splice(fieldsIndex, 1)
                editableTabs.list = tabs.filter(tab => tab.name !== targetName)
                row.afterRemove?.(fieldsIndex)
            }
        }
        const setDefaultValue = (): void => {
            let defaultVal = modelData[row.model]
            defaultValue.fields = defaultVal
            editableTabs.list = []
            // if (defaultVal instanceof Array ) {
            //     defaultVal.forEach(item => {
            //         if (item.tabName) {
            //             item.rule = item.tabName.toLowerCase()
            //         }
            //     })
            // }
            if (row.paneLabel) { // 传入自定义tab title
                for (let i = 0; i < defaultVal.length; i++) {
                    let item = defaultVal[i]
                    if (row?.filterPane?.(item)) continue
                    editableTabs.list.push({
                        title: item[row.paneLabel as string],
                        name: String(i)
                    })
                }
                editableTabsValue.value = '0'
                return
            }
            if (defaultVal.length === 0 || (defaultVal.length === 1 && !defaultVal[0].rule)) {
                let data = init()
                if (defaultVal.length === 1) {
                    defaultValue.fields.shift()
                }
                defaultValue.fields.push(data)
                addMap('set_1', data)
                editableTabs.list.push({
                    title: 'set_1',
                    name: '1'
                })
            } else if (defaultVal.length > 0) {
                for (let item of defaultVal) {
                    addMap(item.rule, item)
                    editableTabs.list.push({
                        title: item.rule,
                        name: item.rule.slice(4)
                    })
                    editableTabsValue.value = String(item.rule.slice(4)) // 最后一项
                }
            }
        }
        const ruleTojson = () => {
            const cyData = {}
            rules.value.forEach((item: ObjectInterface) => {
                let type = item.type
                if (type === 'infoSlot' || type === 'infoDropdown') return
                if (type === 'infoInput') {
                    if (item.button?.show) {
                        type = 'inputButton'
                    } else if (item.select?.show) {
                        type = 'inputSelect'
                    } else if (item.inputType === 'textarea') {
                        type = 'textarea'
                    }
                }
                cyData[item.model] = {
                    label: (typeof item.label === 'function' ? item.label() : item.label) || '',
                    value: '',
                    type: type
                }
                if (item.closable) {
                    cyData[item.model].advanced = item.collapse
                }
            })
            // eslint-disable-next-line no-console
            console.log(cyData)
        }
        setDefaultValue()
        // ruleTojson()
        return {
            dynamicMap,
            defaultValue,
            editableTabsValue,
            editableTabs,
            itemProp,
            rules,
            handleTabsEdit,
            getIndex,
            handleClick
        }
    }
})
</script>

<style lang="scss" scoped>
.add-form {
    width: 100%;
}
.el-form-item .el-form-item {
    margin-bottom: 18px;
}
</style>
