<template>
    <div :id="`table-form-item-${uuid}`" :class="!isTableForm ? 'no-scroll-bar' : ''" class="hc-table-form-data-item h-full w-full">
        <el-scrollbar class="table-form-item-scrollbar">
            <div :id="`table-form-${uuid}`" class="hc-excel-table-form" />
        </el-scrollbar>
        <hc-empty v-if="!isTableForm" :src="notableform" title="暂无表单数据" />
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import HTableForm from '~src/plugins/HTableForm'
import notableform from '~src/assets/view/notableform.svg'
import { getRandom, isNullES, isString } from 'js-fast-way'

//初始
const props = defineProps({
    html: String,
    form: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['tap', 'render'])

const uuid = getRandom(8)

//表单数据
const excelHtml = ref(props.html)
const excelForm = ref(props.form)

//样式
const tableFormApp = ref(null)
const tableFormVM = ref(null)
const isTableForm = ref(false)

//渲染完成
onMounted(() => {
    getExcelHtml()
})

//html变动
watch(() => props.html, (html) => {
    excelHtml.value = html
    setExcelHtml()
}, { deep: true })

//深度监听变动的对象数据
watch(() => props.form, (val) => {
    excelForm.value = val
    setFormData(val)
}, { deep: true })

const setExcelHtml = () => {
    //先卸载
    if (tableFormApp.value) {
        tableFormApp.value?.unmount()
        tableFormApp.value = null
        nextTick(() => {
            getExcelHtml()
        })
    } else {
        getExcelHtml()
    }
}

//获取模板标签数据
const getExcelHtml = () => {
    const temp = isString(excelHtml.value) ? excelHtml.value : ''
    if (isNullES(temp)) {
        isTableForm.value = false
        excelForm.value.isRenderForm = false
        emit('render', excelForm.value)
        return
    }
    //渲染表单
    isTableForm.value = true
    const { app, vm } = HTableForm.createForm({
        template: temp,
        tableForm: excelForm.value,
        appId: `#table-form-${uuid}`,
        onFormDataChange: (form) => {
            excelForm.value = form
        },
        /*onRight: () => {
            console.log('onRight')
        },
        onBlur: () => {
            console.log('onBlur')
        },
        onLeftClick: () => {
            console.log('onLeftClick')
        },*/
    })
    tableFormApp.value = app
    tableFormVM.value = vm
    excelForm.value.isRenderForm = true
    emit('render', excelForm.value)
    initEmits()
}

//获取表单数据
const getFormData = () => {
    return excelForm.value
}

//设置表单数据
const setFormData = (data) => {
    excelForm.value = data
    tableFormVM.value?.setFormData(excelForm.value)
}

//卸载渲染
const unmountHtml = () => {
    if (tableFormApp.value) {
        tableFormApp.value?.unmount()
    }
}

//获取所有组件
const getAllComponents = async () => {
    try {
        return document.getElementById(`table-form-${uuid}`).querySelectorAll('.hc-table-form-components-box')
    } catch (error) {
        return []
    }
}

//注册事件
const initEmits = async () => {
    const boxs = await getAllComponents()
    for (let i = 0; i < boxs.length; i++) {
        boxs[i].addEventListener('click', async (e) => {
            await tableFormComponentsClick(e)
        })
    }
}

//被点击
const tableFormComponentsClick = async (e) => {
    const boxs = await getAllComponents()
    for (let i = 0; i < boxs.length; i++) {
        boxs[i].classList.remove('cur')
    }
    e.target.classList.add('cur')
    emit('tap', e)
}

//清空全部选择
const clearClick = async () => {
    const boxs = await getAllComponents()
    for (let i = 0; i < boxs.length; i++) {
        boxs[i].classList.remove('cur')
    }
}

//设置选中
const setSelect = async (arr) => {
    await clearClick()
    if (arr.length <= 0) return
    const boxs = await getAllComponents()
    for (let i = 0; i < boxs.length; i++) {
        const index = boxs[i].getAttribute('data-index')
        if (arr.indexOf(index) > -1) {
            boxs[i].classList.add('cur')
        }
    }
}

// 暴露出去
defineExpose({
    getFormData,
    setFormData,
    setExcelHtml,
    unmountHtml,
    clearClick,
    setSelect,
})
</script>

<style lang="scss">
//插入特殊字符弹窗的输入框
.hc-table-form-data-item .hc-excel-table-form td,
.hc-table-form-data-item .hc-excel-table-form td .hc-table-form-components-box {
    font-family: "hc-eudc", hc-sans, 宋体, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" !important;
}

.hc-table-form-data-item {
    position: relative;
    padding: 12px;
    background-color: white;
    border: 1px solid #101010;
    border-radius: 4px;
    overflow: hidden;
    .el-scrollbar .el-scrollbar__bar.is-vertical {
        right: -10px;
    }
    &.no-scroll-bar .el-scrollbar {
        display: none;
    }
    .hc-excel-table-form {
        position: relative;
        padding: 10px;
        display: flex;
        justify-content: center;
        td {
            position: relative;
            padding: 6px;
            background-clip: padding-box;
            //公式
            &[gscolor] .hc-table-form-components-box {
                background-color: #dcdcdc !important;
            }
        }
        //列合并的单元格
        td[rowspan] {
            height: initial;
        }
        //非输入框颜色
        td:not([titlexx]), td[titlexx*=''],
        td:not([title]), td[title*=''] {
            background-color: white !important;
            user-select: none;
        }
    }
}
</style>
