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

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import landApi from '~api/agree/land.js'
import { deepClone, getArrValue, getObjVal, isString } from 'js-fast-way'

//初始
const props = defineProps({
    areaId: { // 树节点
        type: [String, Number],
        default: '',
    },
    kid: { // pkeyId
        type: [String, Number],
        default: '',
    },
    classify: { // 类型1新增，2是编辑
        type: [String, Number],
        default: '',
    },
    scroll: {
        type: Boolean,
        default: true,
    },
    height: {
        type: String,
        default: '100%',
    },
    width: {
        type: String,
        default: 'auto',
    },
    datas: {
        type: Object,
        default: () => ({}),
    },
   
    pid: { // 折叠ID
        type: String,
        default: '',
    },
 
    tableId:{
        type: [String, Number],
        default: '', //表单initTableId
    },
    agreementId:{
        type: [String, Number],
        default: '', //协议ID
    },

   
})

//事件
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 areaId = ref(props.areaId)
const agreementId = ref(props.agreementId)
const classify = ref(props.classify)
const loading = ref(false)
const changeData = ref(props.datas)


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

const tableFormRef = ref(null)

const tableId = ref(props.tableId)

//监听
watch(() => [
    useAppState.getProjectId,
    useAppState.getContractId,
    props.areaId,
    props.kid,
    props.classify,
    props.nodeName,
    props.height,
    props.width,
    props.pid,

    props.tableId,
    props.agreementId,
], (
    [project_id, contract_id, area_id, key_id, cid, height, width, pid, , table_id, aeement_id],
) => {
    projectId.value = project_id
    contractId.value = contract_id
    areaId.value = area_id
    keyId.value = key_id ? key_id + '' : ''
    classify.value = cid
  
    heights.value = height
    widths.value = width
    activeKey.value = pid

    tableId.value = table_id
    agreementId.value = aeement_id
})

//深度监听变动的对象数据
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,
    
        agreementId: agreementId.value, //	协议的id,新增协议为null
        areaId:areaId.value, //当前树节点id
        projectId: projectId.value,
        tableId:tableId.value, //表单的tableId
        isRenderForm: false,
        linkId: keyId.value,
    
    }
}

//获取已填写的数据
const tableFormInfo = ref({})
const getTableFormInfo = async (pkeyId) => {
    if (pkeyId) {
        const { error, code, data } = await landApi.getBussInfo({
            id: pkeyId,
        }, 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 landApi.getBussCols({
            id: 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 landApi.getExcelHtml({
            id: 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 }
}

const getFormData = () => {
    return tableFormInfo.value
    //return tableFormRef.value?.getFormData()
}

const setFormData = (data) => {
    setFormChangeData(data)
    tableFormRef.value?.setFormData(tableFormInfo.value)
}

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

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



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

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

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

// 暴露出去
defineExpose({
    getFormData,
    setFormData,
    getRegExpJson,
    isFormRegExp,

    setIsCtrlKey,
    setCopyKeyList,
    setPasteKeyList,
})
</script>
