<template>
    <HcTableForm
        ref="tableFormRef"
        :cols="colsKeys"
        :form="tableFormInfo"
        :height="heights"
        :html="excelHtml"
        :loading="loading"
        :pid="activeKey"
        :pkey="keyId"
        :scroll="scroll"
        :width="widths"
        @excel-body-tap="excelTableFormClick"
        @render="tableFormRender"
        @right-tap="tableFormRightTap"
    />
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import wbsApi from '~api/data-fill/wbs'
import { deepClone, getArrValue, getObjVal, isString } from 'js-fast-way'

//初始
const props = defineProps({
    tid: { // 树节点
        type: [String, Number],
        default: '',
    },
    kid: { // pkeyId
        type: [String, Number],
        default: '',
    },
    classify: { // 类型
        type: [String, Number],
        default: '',
    },
    scroll: {
        type: Boolean,
        default: true,
    },
    height: {
        type: String,
        default: '100%',
    },
    width: {
        type: String,
        default: 'auto',
    },
    datas: {
        type: Object,
        default: () => ({}),
    },
    nodeName: { // 表单名称
        type: String,
        default: '',
    },
    pid: { // 折叠ID
        type: String,
        default: '',
    },
})

//事件
const emit = defineEmits(['rightTap', 'render', 'excelBodyTap'])
//初始变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const keyId = ref(props.kid ? props.kid + '' : '')
const treeId = ref(props.tid)
const classify = ref(props.classify)
const loading = ref(false)
const changeData = ref(props.datas)
const nodeNames = ref(props.nodeName)

const heights = ref(props.height)
const widths = ref(props.width)
const activeKey = ref(props.pid)

const tableFormRef = ref(null)

//监听
watch(() => [
    useAppState.getProjectId,
    useAppState.getContractId,
    props.tid,
    props.kid,
    props.classify,
    props.nodeName,
    props.height,
    props.width,
    props.pid,
], ([project_id, contract_id, tree_id, key_id, cid, nodeName, height, width, pid]) => {
    projectId.value = project_id
    contractId.value = contract_id
    treeId.value = tree_id
    keyId.value = key_id ? key_id + '' : ''
    classify.value = cid
    nodeNames.value = nodeName
    heights.value = height
    widths.value = width
    activeKey.value = pid
})

//深度监听变动的对象数据
watch(() => [
    props.datas,
], ([data]) => {
    changeData.value = data
    setFormChangeData(data)
}, { deep: true })


//渲染完成
onMounted(async () => {
    loading.value = true
    //获取已填写的数据
    await getTableFormInfo(keyId.value)
    //按键key列表
    await getHtmlBussColsApi(keyId.value)
    //渲染表单
    await getExcelHtml(keyId.value)
    loading.value = false
})

//表单被点击
const excelTableFormClick = (item) => {
    emit('excelBodyTap', item)
}

//获取表单初始数据
const getFormDataInit = () => {
    return {
        projectId: projectId.value,
        contractId: contractId.value,
        classify: classify.value,
        pkeyId: keyId.value,
        nodeId: treeId.value,
        isRenderForm: false,
    }
}

//获取已填写的数据
const tableFormInfo = ref({})
const getTableFormInfo = async (pkeyId) => {
    if (pkeyId) {
        const { error, code, data } = await wbsApi.getBussDataInfo({
            pkeyId: pkeyId,
            nodeId:treeId.value,
        }, false)
        const resData = getObjVal(data)
        if (!error && code === 200 && resData) {
            tableFormInfo.value = {
                ...resData,
                ...getFormDataInit(),
                ...changeData.value,
            }
        } else {
            tableFormInfo.value = {
                ...getFormDataInit(),
                ...changeData.value,
            }
        }
    } else {
        tableFormInfo.value = {}
        window?.$message?.warning('pkeyId为空')
    }
}

//获取按键切换输入框的key列表
const colsKeys = ref([])
const getHtmlBussColsApi = async (pkeyId) => {
    if (pkeyId) {
        const { error, code, data } = await wbsApi.getHtmlBussCols({
            pkeyId: pkeyId,
        }, false)
        if (!error && code === 200) {
            let keys = getArrValue(data)
            for (let i = 0; i < keys.length; i++) {
                if (keys[i].length <= 0) {
                    keys.splice(i, 1)
                }
            }
            colsKeys.value = keys
        } else {
            colsKeys.value = []
        }
    } else {
        colsKeys.value = []
    }
}

//获取模板标签数据
const excelHtml = ref('')
const getExcelHtml = async (pkeyId) => {
    if (pkeyId) {
        const { error, code, data } = await wbsApi.getExcelHtml({
            pkeyId: pkeyId,
        }, false)
        const resData = isString(data) ? data || '' : ''
        if (!error && code === 200 && resData) {
            excelHtml.value = resData
        } else {
            excelHtml.value = ''
            tableFormInfo.value.isRenderForm = false
            window?.$message?.warning('暂无表单')
        }
    } else {
        excelHtml.value = ''
        tableFormInfo.value.isRenderForm = false
        window?.$message?.warning('pkeyId为空')
    }
}

//渲染完成
const tableFormRender = (form) => {
    tableFormInfo.value = form
    emit('render', form)
}

//右键点击
const tableFormRightTap = (item) => {
    emit('rightTap', item)
}

//设置数据
const setFormChangeData = (data) => {
    const form = deepClone(tableFormInfo.value)
    tableFormInfo.value = { ...form, ...data }
    //console.log('设置数据', {...form, ...data})
}

const getFormData = () => {
    return tableFormInfo.value
    //return tableFormRef.value?.getFormData()
}
const getCols = ()=>{
    return colsKeys.value
}
const setFormData = (data) => {
    setFormChangeData(data)
    tableFormRef.value?.setFormData(tableFormInfo.value)
}

const getRegExpJson = () => {
    return tableFormRef.value?.getRegExpJson()
}

const isFormRegExp = async () => {
    return await tableFormRef.value?.isFormRegExp()
}

//获取表单名称
const getNodeName = () => {
    return nodeNames.value
}

//按下ctrl键
const setIsCtrlKey = (data) => {
    tableFormRef.value?.setIsCtrlKey(data)
}

//按下复制快捷键
const setCopyKeyList = (event) => {
    tableFormRef.value?.setCopyKeyList(event)
}

//按下粘贴快捷键
const setPasteKeyList = async (event) => {
    await tableFormRef.value?.setPasteKeyList(event)
}
const getCetCopyKeyList = async (event)=>{
   let res = await tableFormRef.value?.getCetCopyKeyList(event)
   return res


}
const clearCheckKeyList = ()=>{
    tableFormRef.value?.clearCheckKeyList()



}
// 暴露出去
defineExpose({
    getFormData,
    setFormData,
    getRegExpJson,
    isFormRegExp,
    getNodeName,
    setIsCtrlKey,
    setCopyKeyList,
    setPasteKeyList,
    getExcelHtml,
    getTableFormInfo,
    getHtmlBussColsApi,
    getCols,
    getCetCopyKeyList,
    clearCheckKeyList,
})
</script>
