<template>
    <div class="data-fill-list-box">
        <el-collapse v-model="ActiveKey" accordion @change="CollapseChange">
            <el-collapse-item v-for="(item, index) in listDatas" :id="`item-${index}-${item?.pkeyId}`" :key="item?.pkeyId" :disabled="item.isBussShow === 2" :name="`item-${index}-${item?.pkeyId}`">
                <template #title>
                    <div class="hc-collapse-item-header">
                        <div class="real-fill-rate">
                            <div class="tag" :class="item.realFillRate >= 80 ? 'yes' : ''">已填{{ item.realFillRate ?? 0 }}%</div>
                            <HcTooltip v-if="isStatus !== 3" keys="wbs_preview_table">
                                <el-link v-if="item.isBussShow === 2 || item.isTabPdf === 1 || item.pdfUrl === '' || item.pdfUrl === null" type="primary" disabled>本 表 预 览</el-link>
                                <el-link v-else type="primary" :disabled="tableFormPreviewLoading" @click.stop="previewClick(item)">本 表 预 览</el-link>
                            </HcTooltip>
                        </div>
                        <div class="text-lg truncate item-title">{{ item.nodeName }}</div>
                    </div>
                </template>
                <div :style="`height: calc(100vh - ${draw_type ? '555px' : '222px'});`" class="data-fill-list-item-content">
                    <div v-if="item?.isWindow" class="data-fill-table-form-box is-window">
                        <div class="hc-window-tip">
                            <div class="table-form-no">
                                <img :src="NoDataSvg" alt="">
                                <div class="desc">当前表单处于窗口模式，关闭相关窗口后恢复</div>
                            </div>
                        </div>
                    </div>
                    <div v-else class="data-fill-table-form-box">
                        <TableFormItem
                            v-if="item.isTableRender"
                            :ref="(el) => setItemRefs(el, item)"
                            :classify="classifys"
                            :datas="changeFormDatas(item?.pkeyId, 'collapse')"
                            :kid="item?.pkeyId"
                            :node-name="item.nodeName"
                            :pid="`table-form-${item?.pkeyId}`"
                            :tid="treeId"
                            @excel-body-tap="excelTableFormClick($event)"
                            @render="tableFormRender($event, item, index)"
                            @right-tap="tableFormRightTap($event, index)"
                        />
                        <el-tooltip :content="item.isWindow ? '关闭窗口并恢复' : '当前表单窗口化'" :hide-after="0" placement="top">
                            <div class="form-window-icon" @click.stop="windowClick(item, index)">
                                <template v-if="item.isWindow">
                                    <HcIcon name="fullscreen-exit" />
                                </template>
                                <template v-else>
                                    <HcIcon name="fullscreen" />
                                </template>
                            </div>
                        </el-tooltip>
                    </div>
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>
    <!-- 查看表单 -->
    <template v-for="(item, index) in DragModalTableForm" :key="index">
        <HcDragModal
            :close-icon-arr="closeIconArr" :eid="item.pkeyId" :height="DragModalHeight" :is-show="item.isShow"
            :loading="item.loading" :loading-text="item.loadingText" :title="item.title" is-sort-top
            @close="TableFormClose(item, index)" @close-icon-tap="closeIconTap($event, item, index)"
        >
            <HcDragNode :more-menu="dragNodeMoreMenu" @menu-tap="dragNodeMoreMenuTap($event, item)">
                <TableFormItem
                    :ref="(el) => setItemRefs(el, item)"
                    :classify="item.classify"
                    :datas="changeFormDatas(item?.pkeyId, 'window')"
                    :height="item.height"
                    :kid="item.pkeyId"
                    :node-name="item.title"
                    :pid="`table-form-${item?.pkeyId}`"
                    :scroll="false"
                    :tid="item.treeId"
                    :width="item.width"
                    @excel-body-tap="excelTableFormClick($event)"
                    @render="tableFormRender($event, item.item, item.index)"
                    @right-tap="tableFormRightTap($event, item.index)"
                />
            </HcDragNode>
        </HcDragModal>
    </template>
</template>

<script setup>
import { nextTick, onActivated, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue'
import { getStoreValue } from '~src/utils/storage'
import HTableForm from '~src/plugins/HTableForm'
import { useAppStore } from '~src/store'
import wbsApi from '~api/data-fill/wbs'

import TableFormItem from './table-form-item.vue'





import NoDataSvg from '~src/assets/view/no-data.svg'

import {
    arrIndex, deepClone,
    downloadBlob, getArrValue, getObjVal, getObjValue, isNullES, setPosRange,
} from 'js-fast-way'

import { toPdfPage } from '~uti/btn-auth'
//参数
const props = defineProps({
    datas: {
        type: Array,
        default: () => ([]),
    },
    classify: {
        type: [String, Number],
        default: '',
    },
    status: {
        type: [String, Number],
        default: '',
    },
    primaryKeyId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    drawType: {
        type: Boolean,
        default: false,
    },
    wbsTempId: {
        type: [String, Number],
        default: '',
    },
    tenantId: {
        type: [String, Number],
        default: '',
    },
    wbsType: {
        type: [String, Number],
        default: '',
    },
    treeAutoExpandKeys: {
        type: [Array],
        default: () => ([]),
    },
    treenodeDataInfo: {
        type: [Object],
        default: () => ({}),
    },
    newlistdata:{
        type: [Array],
        default: () => ([]),
    },

})

//事件
const emit = defineEmits(['renew', 'offsetTop', 'getList'])

//初始变量
const useAppState = useAppStore()

//全局变量
const projectId = ref(useAppState.projectId)
const contract_id = ref(props.contractId)
const treeId = ref(props.primaryKeyId)
const classifys = ref(props.classify)
const wbsTemp_id = ref(props.wbsTempId)
const tenant_id = ref(props.tenantId)
const wbs_type = ref(props.wbsType)
const isStatus = ref(parseInt(props.status))
const listDatas = ref([])
const draw_type = ref(props.drawType)
const tree_AutoExpandKeys = ref(props.treeAutoExpandKeys)
const treenodeDataInfo = ref(props.treenodeDataInfo)
const newlistdata = ref(props.newlistdata)


//表单变量
const formDataList = ref([])
const formKeyIds = ref('')
const formparentId = ref('')

//处理ref
const itemRefs = ref([])
const setItemRefs = (el, { pkeyId }) => {
    if (el) {
        let index = arrIndex(itemRefs.value, 'pkeyId', pkeyId)
        if (index !== -1) {
            itemRefs.value[index].ref = el
        } else {
            itemRefs.value.push({
                pkeyId: pkeyId,
                ref: el,
            })
        }
    }
}

//处理表单的ref
const setSpliceItemRefs = async ({ pkeyId }) => {
    const refs = itemRefs.value
    let index = arrIndex(refs, 'pkeyId', pkeyId)
    if (index !== -1) {
        refs.splice(index, 1)
        itemRefs.value = refs
    }
}

const closeIconArr = [
    { key: 'reduction', icon: 'picture-in-picture-2', name: '还原到面板内，并自动展开面板' },
]

//组件参数变量
const apis = ref({
    dataInfo: wbsApi.getBussDataInfo,
    bussCols: wbsApi.getHtmlBussCols,
    excelHtml: wbsApi.getExcelHtml,
})

//深度监听数据
watch(() => [
    props.datas,
], ([datas]) => {
    setFormDataNum(datas)
}, { deep: true })

//监听变量值
watch(() => [
    useAppState.projectId,
    props.contractId,
    props.wbsTempId,
    props.tenantId,
    props.wbsType,
    props.status,
    props.classify,
    props.primaryKeyId,
    props.newlistdata,
    props.treenodeDataInfo,
], ([pid, cid, temp_id, tid, type, status, class_id, tree_id, Newlistdata, TreenodeDataInfo]) => {
    projectId.value = pid
    contract_id.value = cid
    wbsTemp_id.value = temp_id
    tenant_id.value = tid
    wbs_type.value = type
    isStatus.value = parseInt(status)
    classifys.value = class_id
    treeId.value = tree_id
    newlistdata.value = Newlistdata
    treenodeDataInfo.value = TreenodeDataInfo
})

//渲染完成
onMounted(() => {
    setFormDataNum(props.datas)
    // setTableFormMenu(useAppState.projectInfo)
    const { offsetHeight } = document.body
    DragModalHeight.value = offsetHeight - 200
    setMountOnEventKey()
})

//处理变动的数据
const changeFormData = ref({
    window: [],
    collapse: [],
})
const changeFormDatas = (pkeyId, type) => {
    const changeData = changeFormData.value[type]
    const index = arrIndex(changeData, 'pkeyId', pkeyId)
    if (index !== -1) {
        return changeData[index]
    } else {
        return {}
    }
}

//设置变动的数据
const setChangeFormDatas = async (pkeyId, type) => {
    const refs = await getFormRef(pkeyId)
    const formData = refs?.getFormData()
    const changeData = changeFormData.value[type]
    const index = arrIndex(changeData, 'pkeyId', pkeyId)
    if (index !== -1) {
        changeData[index] = formData
    } else {
        changeData.push(formData)
    }
    changeFormData.value[type] = changeData
}

//展开事件
const ActiveKey = ref('')
const CollapseChange = (name) => {
    ActiveKey.value = name
    let index = getCollapseItemIndex(name)
    if (index > -1) {
        getOffsetTop(name)
        const item = listDatas.value[index]
        formKeyIds.value = setToString(item.pkeyId)
        formparentId.value = setToString(item.parentId)
        nextTick(() => {
            if (!item.isTableRender) {
                item.isTableRender = true
            }
        })
    } else {
        getOffsetTop()
        formKeyIds.value = ''
        formparentId.value = ''
    }
}

const setCollapseKey = (key) => {
    CollapseChange(key)
}

//初始设置
const setFormDataNum = (datas) => {
    itemRefs.value = []
    ActiveKey.value = ''
    let newArr = []
    for (let i = 0; i < datas.length; i++) {
        newArr.push({ isCollapseLoad: false })
    }
    formDataList.value = newArr
    listDatas.value = deepClone(datas)
}

//渲染完成
const tableFormRender = (form, item, index) => {
    formDataList.value[index] = form
    formDataList.value[index].isCollapseLoad = form.isRenderForm
    item.isTableForm = form.isRenderForm
}


//菜单数据
const contextMenuRef = ref(null)

const tableFormItemNode = ref({}) //临时信息



//鼠标右键事件
const tableFormRightTap = ({ event, KeyName, startPos, endPos, pkeyId }, index) => {
    //存储临时信息
    tableFormItemNode.value = { KeyName, index, startPos, endPos, pkeyId }
    contextMenuRef.value?.showMenu(event, false) //展开菜单
}

//插入设计值
const designModal = ref(false)

const formDesignModel = ref()

//初始设计值/频率表单
const setInitDesignForm = () => {
    formDesignModel.value = {
        type: 1, design: '', size: '',
        dev: '', key: '', capacity: '',
        pass: '', pkId: '', direction:1,
    }
}























//窗口化
const DragModalTableForm = ref([])
const DragModalHeight = ref(600)
const windowClick = async (item, indexs) => {
    const list = deepClone(DragModalTableForm.value)
    let index = arrIndex(list, 'pkeyId', item.pkeyId)
    if (!item.isWindow) {
        const formSize = getTableFormSize(item?.pkeyId)
        const newTableForm = {
            ...setInitDragModalTableForm(item, indexs),
            ...formSize,
        }
        await setChangeFormDatas(item?.pkeyId, 'window')
        item.isWindow = true
        //处理表单的ref
        await setSpliceItemRefs(item)
        //弹窗表单的排序
        if (index === -1) {
            list.push(newTableForm)
        } else if (index !== list.length - 1) {
            //检查是否在最上层，不在则置顶，可以解决多次点击时，频繁更改全局状态的问题
            list.splice(index, 1)
            list.push(newTableForm)
        }
        DragModalTableForm.value = list
        ActiveKey.value = ''
    } else {
        await setChangeFormDatas(item?.pkeyId, 'collapse')
        //处理表单的ref
        await setSpliceItemRefs(item)
        if (index !== -1) {
            list.splice(index, 1)
            DragModalTableForm.value = list
        }
        item.isWindow = false
    }
}

//初始拖动表单的内容
const setInitDragModalTableForm = (item, index) => {
    return {
        projectId: projectId.value,
        contractId: contract_id.value,
        wbsTempId: wbsTemp_id.value,
        tenantId: tenant_id.value,
        wbsType: wbs_type.value,
        classify: classifys.value,
        treeId: treeId.value,
        pkeyId: item.pkeyId,
        height: '100%',
        width: '100%',
        title: item.nodeName,
        isShow: true,
        index: index,
        item: item,
    }
}

//关闭窗口
const TableFormClose = async ({ pkeyId, index }, indexs) => {
    const list = deepClone(DragModalTableForm.value)
    //取表单的数据
    await setChangeFormDatas(pkeyId, 'collapse')
    //关闭窗口
    list.splice(indexs, 1)
    DragModalTableForm.value = list
    listDatas.value[index].isWindow = false
}

const dragNodeMoreMenu = [
    { key: 'save', icon: 'save-2', name: '保存' },
    { key: 'preview', icon: 'eye', name: '预览' },
]

//还原窗口
const closeIconTap = async (event, item, indexs) => {
    const { index, pkeyId } = item
    let KeyId = `item-${index}-${pkeyId}`
    await TableFormClose(item, indexs)
    ActiveKey.value = KeyId
}

//菜单被点击
const dragNodeMoreMenuTap = ({ key }, items) => {
    const { item } = items
    if (key === 'save') {
        if (item?.isTableForm) {
            tableFormSaveClick(item, items)
        } else {
            window.$message.warning('此表单暂无数据和文件')
        }
    } else if (key === 'preview') {
        if (item['isBussShow'] === 2 || item['isTabPdf'] === 1 || item['pdfUrl'] === '' || item['pdfUrl'] === null) {
            window.$message.warning('此表单暂无可预览文件')
        } else {
            previewClick(item, items)
        }
    }
}


//跨节点复制弹窗
// const copyClick =  (items) => {
//     showcopyModal.value=true
//     copyItems.value=items

// }



//获取表单列表
const getNewList = ()=>{
    emit('getList')
   setTimeout(() => {
    let newObj = newlistdata.value
    let oldObj = listDatas.value
    const addedObject = newObj.find(obj => !oldObj.some(oldObj => oldObj.pkeyId === obj.pkeyId))
    let index = arrIndex(listDatas.value, 'id', addedObject.id) // 1
    listDatas.value.splice(index + 1, 0, addedObject)
   }, 1000)
}


//预览本表
const tableFormPreviewLoading = ref(false)
const previewClick = async (item, dragItem = null) => {
    tableFormPreviewLoading.value = true
    await getBussPdfInfo(item, dragItem)
    tableFormPreviewLoading.value = false
}









//预览PDF
const getBussPdfInfo = async ({ pkeyId }, dragItem = null, showTip = true) => {
    setDragModalLoading(dragItem, '获取pdf中...', true)
    const { error, code, data } = await wbsApi.getBussPdfInfo({
        pkeyId: pkeyId,
    }, false)
    setDragModalLoading(dragItem)
    if (!error && code === 200) {
        if (data) {
            toPdfPage(data)
            //window.open(data, '_blank')
        } else if (showTip) {
            window?.$message?.warning('PDF错误')
        }
    } else {
        if (showTip) {
            window?.$message?.warning(data.msg || '获取PDF失败')
        }
    }
}


//通知数据更新
const renewData = () => {
    emit('renew', ActiveKey.value)
    ActiveKey.value = ''
}

//设置表单的加载状态
const setDragModalLoading = (dragItem, text = '保存中...', show = false) => {
    if (dragItem && show) {
        dragItem.loading = true
        dragItem.loadingText = text
    }
    if (dragItem && !show) {
        dragItem.loading = false
    }
}

//获取表单的ref
const getFormRef = async (pkeyId) => {
    const itemRef = getArrValue(itemRefs.value)
    if (itemRef.length <= 0) return ''
    const index = arrIndex(itemRef, 'pkeyId', pkeyId)
    if (index === -1) return ''
    const obj = getObjValue(itemRef[index])
    return obj?.ref
}

//删除打开的窗口
const delWindowRefs = (pkeyId) => {
    //判断是否存在窗口，如果存在，就删除窗口
    const list = DragModalTableForm.value
    const index = arrIndex(list, 'pkeyId', pkeyId)
    if (index !== -1) {
        list.splice(index, 1)
        DragModalTableForm.value = list
    }
}

//计算展开高度和滚动位置
const getOffsetTop = (key = '') => {
    if (key) {
        const dom = document.getElementById(key)
        if (!draw_type.value) {
            if (dom?.offsetTop >= 583 && key) {
                emit('offsetTop', dom?.offsetTop - 583)
            } else {
                emit('offsetTop', dom?.offsetTop)
            }
        } else {
            if (dom.offsetTop >= 424 && key) {
                emit('offsetTop', dom?.offsetTop - 424)
            } else {
                emit('offsetTop', dom?.offsetTop)
            }
        }
    } else {
        emit('offsetTop', 0)
    }
    ActiveKey.value = key
}

//获取折叠面板的索引
const getCollapseItemIndex = (name) => {
    const keys = name.split('-')
    if (keys.length > 0) {
        return keys[1]
    } else {
        return -1
    }
}

//获取表单的大小
const getTableFormSize = (pkeyId) => {
    let formId = `table-form-${pkeyId}`
    try {
        const { clientWidth, clientHeight } = document.getElementById(formId).children[0]
        return {
            width: (clientWidth + 40) + 'px',
            height: (clientHeight + 80) + 'px',
        }
    } catch {
        return {
            width: '100%',
            height: '100%',
        }
    }
}

//转字符串
const setToString = (val) => {
    return val ? val + '' : ''
}

//表单被点击
const presentId = ref('')
const excelTableFormClick = (key) => {
    presentId.value = key
}

//缓存被激活时
onActivated(() => {
    setMountOnEventKey()
})

//缓存时被移除
onDeactivated(() => {
    HTableForm.unmountEventKey()
})

//页面被卸载
onUnmounted(() => {
    HTableForm.unmountEventKey()
})

const setMountOnEventKey = () => {
    HTableForm.setOnEventKey({
        //按下ctrl键 或 control 键
        onCtrlDown: async () => {
            //window.$HcLog('全局按键', '按下ctrl键 或 control 键')
            const refs = await setOnFuncFormRef()
            refs?.setIsCtrlKey(true)
        },
        //按下复制快捷键
        onCtrlDownC: async (event) => {
            //window.$HcLog('全局按键', '按下复制快捷键')
            const refs = await setOnFuncFormRef()
            refs?.setCopyKeyList(event)
        },
        //按下粘贴快捷键
        onCtrlDownV: async (event) => {
            //window.$HcLog('全局按键', '按下粘贴快捷键')
            const refs = await setOnFuncFormRef()
            await refs?.setPasteKeyList(event)
        },
        //放开ctrl键 或 control 键
        onCtrlUp: async () => {
            //window.$HcLog('全局按键', '放开ctrl键 或 control 键')
            const refs = await setOnFuncFormRef()
            refs?.setIsCtrlKey(false)
        },
    })
}

//获取表单的ref
const setOnFuncFormRef = async () => {
    const pkeyId = presentId.value
    if (!isNullES(pkeyId)) {
        return await getFormRef(pkeyId)
    } else {
        return
    }
}


//获取已渲染的表单
const getFilterFormData = async () => {
    const formArr = formDataList.value
    return formArr.filter((item) => {
        return (item.pkeyId ?? '') !== '' && item.isCollapseLoad
    })
}

//获取表单数据
const getFormData = async () => {
    const formArr = await getFilterFormData()
    //获取表单数据
    let newArr = []
    for (let i = 0; i < formArr.length; i++) {
        const pkeyId = formArr[i].pkeyId
        const refs = await getFormRef(pkeyId)
        const form = refs?.getFormData()
        newArr.push({ ...form })
    }
    console.log('表单数据', newArr)
    return newArr
}

//获取表单效验数据
const getFormRegExpJson = async () => {
    const formArr = await getFilterFormData()
    const list = listDatas.value
    //获取表单数据
    let formRegExpJson = {}
    for (let i = 0; i < formArr.length; i++) {
        const pkeyId = formArr[i].pkeyId
        const refs = await getFormRef(pkeyId)
        const regExp = refs?.getRegExpJson()
        const nodeName = refs?.getNodeName()
        if (getObjVal(regExp)) {
            const index = arrIndex(list, 'pkeyId', pkeyId)
            formRegExpJson[pkeyId] = {
                ...regExp,
                itemId: `item-${index}-${pkeyId}`,
                nodeName: nodeName,
            }
        }
    }
    return formRegExpJson
}

//获取当前展开项
const getActiveKey = () => {
    return ActiveKey.value
}

//设置当前展开项
const setActiveKey = (key) => {
    return ActiveKey.value = key
}



// 暴露出去
defineExpose({
    getFormData,
    getFormRegExpJson,
    getActiveKey,
    setActiveKey,
    setCollapseKey,
})
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>

<style lang="scss">
@import "./style.scss";
</style>
