<template>
    <div class="h-full">
        <hc-page-split v-if="wbsTypeTabKey === 'tree'" ref="pageSplitRef">
            <template #left>
                <div class="left-box-container bg-white">
                    <div class="hc-project-box">
                        <div class="hc-project-icon-box">
                            <HcIcon name="stack" />
                        </div>
                        <div class="project-name-box ml-2">
                            <div class="project-alias">{{ projectInfo.projectName }}</div>
                        </div>
                    </div>
                    <div class="hc-tree-box hc-tree-box1">
                        <div class="hc-search-tree-val">
                            <el-input
                                v-model="searchTreeVal"
                                clearable
                                block
                                placeholder="请输入名称关键词检索"
                                @keyup="searchTreeKeyUp"
                            >
                                <template #suffix>
                                    <HcIcon
                                        name="search-2"
                                        ui="text-xl iscusor"
                                        @click="searchTreeClick"
                                    />
                                </template>
                            </el-input>
                        </div>
                        <div
                            v-if="isShowLeft"
                            id="hc-tree-scrollbar"
                            v-loading="treeLoading"
                            class="hc-tree-scrollbar"
                            element-loading-text="获取数据中..."
                        >
                            <el-scrollbar
                                v-show="isSearchTree"
                                class="scroll-bar-right-16"
                            >
                                <HcDataTree
                                 
                                    :is-show-eye="true"
                                    :datas="searchTreeData"
                                    :is-mark="TreeMark"
                                    :menus="ElTreeMenu"
                                   

                                    is-type
                                    :auto-expand-keys="TreeAutoExpandKeys"
                                    
                                    is-counts default-expand-all is-form-date 
                                    :is-show-sync="userInfo?.role_id?.split(',').includes('1123598816738675201')"
                                    @node-tap="wbsElTreeClick"
                                    @menu-tap="ElTreeMenuClick"
                                />
                            </el-scrollbar>
                            <el-scrollbar
                                v-show="!isSearchTree"
                                class="scroll-bar-right-16"
                            >
                                <HcLazyTree
                                    ref="wbstree"
                                 
                                    :is-show-eye="true"
                                    :is-show-sync="userInfo?.role_id?.split(',').includes('1123598816738675201')"
                                    is-form-date
                               
                                    :auto-expand-keys="TreeAutoExpandKeys"
                                    :is-mark="TreeMark"
                                    :menus="ElTreeMenu"
                                    is-counts
                                    is-type
                                    show-checkbox
                                    check-strictly
                                    @load="treeLoadNode"
                                    @menu-tap="ElTreeMenuClick"
                                    @node-loading="ElTreeNodeLoading"
                                    @node-tap="wbsElTreeClick"
                                />
                            </el-scrollbar>
                        </div>
                    </div>
                    <div class="hc-tree-foot-tip-box">
                        <div class="dot-view green">已审批</div>
                        <div class="dot-view black">未填报</div>
                        <div class="dot-view orange">已填报-待审批</div>
                        <div class="dot-view blue">已填报-未上报</div>
                    </div>
                </div>
            </template>
   
            <hc-tab-card
                :tabs="authBtnTabdata"
                :tab-key="authBtnTabKey"
                @change="authBtnTabClick"
            >
                <el-scrollbar
                    v-if="ListItemDatas.length > 0"
                    ref="ListItemScrollRef"
                >
                    <CollapseForm
                        ref="ListItemRef"
                        :contract-info="
                            contractInfo?.contractType === 2
                                ? nodeDataInfo?.contractIdRelation
                                : contractId
                        "
                        :tree-auto-expand-keys="TreeAutoExpandKeys"
                        :classify="authBtnTabKey"
                        :contract-id="contractId"
                        :datas="ListItemDatas"
                        :draw-type="!isDrawType"
                        :primary-key-id="primaryKeyId"
                        :status="NodeStatus"
                        :tenant-id="userInfo?.tenant_id"
                        :wbs-temp-id="
                            projectInfo?.referenceWbsTemplateIdTrial
                        "
                        :wbs-type="2"
                        :treenode-data-info="nodeDataInfo"
                        :newlistdata="newlistdata"
                        @offset-top="ListItemOffsetTop"
                        @renew="getTableDataAll"
                        @get-list="searchNodeAllTable1"
                    />
                </el-scrollbar>
                <hc-empty v-else title="暂无表单" />
            </hc-tab-card>
        </hc-page-split>
    </div>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '~src/store'

import CollapseForm from './collapse-form/index.vue'


import { getStoreValue, setStoreValue } from '~src/utils/storage'


import {
    arrToKey,
    deepClone,

    getArrValue,

    getObjValue,
    isNullES,

} from 'js-fast-way'
import {
 
    userConfigSave,
} from '~api/other'
import wbsApi from '~api/data-fill/wbs'
import queryApi from '~api/data-fill/query'
import nodeBaseApi from '~api/data-fill/nodebaseinfo'
import { useClick } from 'hc-vue3-ui'

import { HcDelMsg, NewDelMsg } from 'hc-vue3-ui'

import { toPdfPage } from '~uti/btn-auth'
import website from '~src/config'


//初始变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()

//全局变量
const projectId = ref(useAppState.projectId)
const contractId = ref(useAppState.contractId)
const projectInfo = ref(useAppState.projectInfo)
const contractInfo = ref(useAppState.contractInfo)
const isCollapse = ref(useAppState.getCollapse)
const userInfo = ref(useAppState.getUserInfo)
const isLayout = ref(useAppState.isLayout)
const leftWidth = ref(440)
const isTemplateType = ref(useAppState.contractInfo?.templateType === 2)
//路由参数
const routerQuery = useRoutes?.query
// const typeName = routerQuery?.type || 'map'
const typeName = routerQuery?.type || 'tree'
//是否是抽屉
const isDrawType = ref(true)
//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])

//树搜索
const isSearchTree = ref(false)
const searchTreeHeight = ref()
const getSearchTreeData = async (type) => {
    treeLoading.value = true
        let response
      
            response = await queryApi.getTreeNodeByQueryValueAndContractId({
                contractId: contractId.value,
                tableOwner: authBtnTabKey.value,
               queryValue: searchTreeVal.value,
            })
        

        const { error, code, data } = response
             if (!error && code === 200) {
                let treedata = getArrValue(data)
                searchTreeData.value = treedata
                treeLoading.value = false
            } else {
                treeLoading.value = false

                searchTreeData.value = []
            }
}

//监听
const searchTreeVal = ref('')
watch(
    () => [useAppState.getCollapse, searchTreeVal.value],
    ([Collapse, search]) => {
        isCollapse.value = Collapse
        if (search.length == 0) {
            isSearchTree.value = false
        }
    },
)

//加载树需要的classType
const classType = ref('')
watch(
    () => [classType.value, useAppState.isLayout],
    ([classify, isLay]) => {
        isLayout.value = isLay || ''
        if (classify) {
            //重新加载左边树
            isShowLeft.value = false
            setTimeout(() => {
                isShowLeft.value = true
            }, 500)
        }
    },
)
const pageSplitRef = ref(null)

watch(() => pageSplitRef.value?.leftPanelWidth, (newWidth) => {

    
    leftWidth.value = newWidth
    setUserConfig(newWidth)
   
})
//渲染完成
onMounted(() => {
    console.log(projectInfo.value)
    treeLoading.value = typeName === 'tree'
    const treeWidth = useAppState.getTreeWidth
  
    
    leftWidth.value = isNullES(treeWidth) || treeWidth <= 0 ? 440 : treeWidth
    setContractType(contractInfo.value?.contractType)
 




     
      nextTick(() => {
       pageSplitRef.value?.setLeftWidth(leftWidth.value)
    })
     
    
})

//身份按钮切换数据
const authBtnTabKey = ref('1')

//变量
const wbstree = ref(null)
const isShowLeft = ref(true)
const authBtnTabClick = (val) => {
      
    if (!primaryKeyId.value) {
        window?.$message?.warning('请先在左侧项目树选择一个节点')
    } else if (val['key'] !== authBtnTabKey.value) {
        authBtnTabKey.value = val['key']
    
        //重新加载左边树
        isShowLeft.value = false
        setTimeout(() => {
            isShowLeft.value = true
        }, 500)
        getTableDataAll()
    }
}
//contractType,  1施工，2监理
const setContractType = (contractType) => {
    if (contractType <= 0) {
        authBtnTabKey.value = '1'
        classType.value = '1'
    } else if (contractType === 3) {
        authBtnTabKey.value = '1'
        classType.value = '1'
    } else {
        authBtnTabKey.value = contractType + ''
        classType.value = contractType + ''
    }
  
}

const getTableDataAll = async (key) => {
    await searchNodeAllTable()
    await queryNodeStatus()
 
    //保存后自动展开到当前表单
    if (!isNullES(key)) {
        console.log(key)
        await nextTick(() => {
            ListItemRef.value?.setCollapseKey(key)
        })
    }
}

//结构类型tab数据和相关处理
const wbsTypeTabKey = ref(typeName)

const authBtnTabdata = ref([
    { key: '1', name: '施工质检' },
    { key: '2', name: '监理质检' },
])
const wbsTypeTabChange = (item) => {
    wbsTypeTabKey.value = item?.key
    ListItemDatas.value = []
    isDrawer.value = false
    treeLoading.value = typeName === 'tree'
    setStoreValue('classifyType', classType.value)
    setStoreValue('tableOwner', authBtnTabKey.value)
    //路由跳转
    router.push({
        path: useRoutes.path,
        query: {
            type: item?.key,
            classifyType: classType.value,
            tableOwner: authBtnTabKey.value,
        },
    })
    getSearchTreeData()
}
//切换导图结构
const wbsMapTypeTab = () => {
    wbsTypeTabChange({ key: 'map', name: '导图结构填报' })
}

//设置图纸数据
const setUploadDrawingsData = async (echoParams, link) => {
    const info = nodeDataInfo.value
    const { error, code, data } = await wbsApi.saveContractTreeDrawings(
        {
            fileUrl: link,
            id: echoParams['drawingsId'],
            primaryKeyId: echoParams['primaryKeyId'],
        },
        false,
    )
    //处理数据
    if (!error && code === 200) {
        if (info['primaryKeyId'] === echoParams['primaryKeyId']) {
            nodeDataInfo.value['drawingsId'] = data
            nodeDataInfo.value['fileUrl'] = link
            window?.$message?.success('图纸上传成功')
        } else {
            window?.$message?.success(
                '图纸上传成功，由于您切换了其他节点，需要手动刷新才能查看到图纸',
            )
        }
    } else {
        window?.$message?.error('图纸保存失败')
    }
}



//设置树菜单数据
const ElTreeMenu = ref([])
const TreeMark = ref(false)


//树相关变量
const primaryKeyId = ref('')
const nodeItemInfo = ref({})
const nodeDataInfo = ref({})

const searchTreeData = ref([])

//回车
const searchTreeKeyUp = (e) => {
    if (e.key === 'Enter') {
        searchTreeClick()
    }
}

const treeLoading = ref(true)

const searchTreeClick = async () => {
    if (searchTreeVal.value) {
        searchTreeHeight.value
            = document.getElementById('hc-tree-scrollbar').offsetHeight
        isSearchTree.value = true
        //treeLoading.value = true
        getSearchTreeData()
      
    } else {
        isSearchTree.value = false
    }
}

//懒加载的数据
const treeLoadNode = async ({ node, item, level }, resolve) => {
    let contractIdRelation = '',
        parentId = '',
        primaryKeyId = ''
    if (level !== 0) {
        const nodeData = getObjValue(item)
        contractIdRelation = nodeData?.contractIdRelation || ''
        parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
        primaryKeyId = nodeData?.id || ''
    }
    //获取数据
    const { data } = await queryApi.queryWbsTreeData({
        contractId: contractId.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId,
        // classifyType: authBtnTabKey.value,
        classifyType: classType.value,
        tableOwner: authBtnTabKey.value,
        dataTime:new Date(),
    })
    treeLoading.value = false

    resolve(getArrValue(data))
}

//树被点击
const wbsElTreeClick = ({ node, data, keys }) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    primaryKeyId.value = data?.primaryKeyId || ''
    const { notExsitChild } = data
    const { hasChildren } = data
    if (notExsitChild || !hasChildren) {
      
        getTableDataAll()
    } else {
     
        ListItemDatas.value = []
        NodeStatus.value = '1'
    }
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []

  
    // getTableDataAll()
}
//树加载完成
const ElTreeNodeLoading = () => {
    treeLoading.value = false
}


//树菜单被点击
const ElTreeMenuClick = async ({ key, node, data, keys }) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
    
}








//设置滚动条位置
const ListItemScrollRef = ref(null)
const ListItemOffsetTop = (offsetTop) => {
    if (offsetTop > 0) {
        setTimeout(() => {
            ListItemScrollRef.value?.setScrollTop(offsetTop)
        }, 350)
    } else {
        ListItemScrollRef.value?.setScrollTop(offsetTop)
    }
}

//获取数据列表
const ListItemDatas = ref([])
const ListItemLoading = ref(false)
const searchNodeAllTable = async () => {
    ListItemLoading.value = true
    ListItemDatas.value = []
    const info = nodeDataInfo.value
    const { data } = await wbsApi.searchNodeAllTable({
        projectId: projectId.value,
        contractId: contractId.value,
        primaryKeyId: info['primaryKeyId'],
        type: authBtnTabKey.value,
    })
    ListItemDatas.value = getArrValue(data)
 
    ListItemLoading.value = false
}
//获取文件题名


const newlistdata = ref([])
const searchNodeAllTable1 = async () => {
    console.log('重新获取表单列表')
    const info = nodeDataInfo.value
    const { data } = await wbsApi.searchNodeAllTable({
        projectId: projectId.value,
        contractId: contractId.value,
        primaryKeyId: info['primaryKeyId'],
        type: authBtnTabKey.value,
    })
    newlistdata.value = getArrValue(data)
}
//查询状态
const NodeStatus = ref('1')
const queryNodeStatus = async () => {
    const info = nodeDataInfo.value
    if (contractInfo.value?.contractType == 1) {
        const { error, code, data } = await wbsApi.queryNodeStatus({
            primaryKeyId: info['primaryKeyId'],
            //classify:1
            classify: authBtnTabKey.value,
        })
        //1 未填报，2待上报，3已上报
        if (!error && code === 200) {
            NodeStatus.value = data ?? '1'
        } else {
            NodeStatus.value = '1'
        }
    } else {
        const { error, code, data } = await wbsApi.queryNodeStatusJl({
            // primaryKeyId: info['contractIdRelation'] ? info['id'] : info['primaryKeyId'],
            primaryKeyId: info['primaryKeyId'],
            //classify: 1
            classify: authBtnTabKey.value,
        })
        //1 未填报，2待上报，3已上报
        if (!error && code === 200) {
            NodeStatus.value = data ?? '1'
        } else {
            NodeStatus.value = '1'
        }
    }
}


//表单变量
const ListItemRef = ref(null)
const ListItemsRef = ref(null)


















//更新配置
watch(
    () => leftWidth.value,
    (diffVal) => {
        setUserConfig(diffVal)
    },
)
const setUserConfig = async (data) => {

    if (data > 0) {
         await useClick()
        useAppState.setTreeWidth(data)
        await userConfigSave({ treeWidth: data })
    }
   

}
</script>

<style lang="scss" scoped>
@import "../../styles/data-fill/wbs.scss";

.back-button {
  /* 确保按钮有足够的空间来展示放大效果 */
  padding: 4px;
  /* 过渡效果：所有属性变化在300ms内完成，使用ease-out缓动函数 */
  transition: all 300ms ease-out;
  /* 防止放大时内容溢出 */
  overflow: hidden;
}

/* 缩放状态的样式 */
.back-button.scaling {
  /* 放大到1.2倍 */
  transform: scale(1.2);
}
.hc-project-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
    // font-size:20px;
 
}
.title-input{
    height: 30px;
    padding: 10px;
    border: 1px solid #dcdfe6;
    background-color: #dcdfe6;
    line-height: 13px;
    border-radius: 5px;
    font-weight: 500;
    margin-left: 4px;
    max-width: 300px;
    overflow-x: auto;
    overflow-y: hidden;

}
.hc-add-node-modal-foot-box {
    position: relative;
    display: flex;
    align-items: center;
    .left-box {
        position: relative;
        flex: 1;
        display: flex;
        align-items: center;
    }
    .right-box {
        position: relative;
    }
}
.hc-expansion-contraction-tree {
    position: absolute;
    left: -13px;
    top: 0;
    width: 10px;
    height: 100%;
    user-select: none;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #8c9099;
    font-size: 22px;
    border-radius: 5px;
    transition: background 0.2s;
    background: rgba(255, 255, 255, 0);
    &:hover {
        background: #f1f5f8;
        color: var(--el-color-primary);
    }
}
.hc-table-form-action-tip {
    position: absolute;
    bottom: 77px;
    width: 100%;
}
.data-fill-wbs-hide-btn {
    background: #fff;
    color: #ffffff;
}

html.dark .data-fill-wbs-hide-btn {
    background: #141414;
    color: #141414;
}

html.theme-dark {
    .bg-svg-xml {
        background-color: initial;
        background-image: initial;
    }
    .hc-layout-box
        .hc-layout-content-box
        .hc-card-max-h-box.node-tree
        .hc-tree-foot-tip-box {
        border-top: 1px solid #303030;
    }
}
</style>

<style lang="scss">
.hc-tree-box1 .el-tree-node {
    .el-checkbox {
        margin-right: 0;
        .el-checkbox__inner {
            display: none;
        }
    }
    .is-leaf + .el-checkbox {
        margin-right: 8px;
        .el-checkbox__inner {
            display: inline-block;
        }
    }
}

.data-fill-wbs-content {
    position: relative;
    height: 100%;
    .n-drawer-container {
        margin: -20px -24px;
    }
    .n-drawer.n-drawer--top-placement {
        height: auto !important;
        background-color: initial;
        pointer-events: none;
        bottom: 0;
    }
    .drawer-data-fill-content-box {
        position: relative;
        height: 100%;
        padding: 24px;
        .n-card {
            pointer-events: auto;
            height: 100%;
            overflow: auto;
        }
        .data-fill-content {
            position: relative;
            height: 100%;
            overflow-y: auto;
            scroll-behavior: smooth;
            .data-fill-list-box .data-fill-list-item-content {
                height: calc(100vh - 470px);
                .data-fill-table-form-box {
                    height: 100%;
                }
            }
        }
        .data-fill-foot {
            position: relative;
            text-align: center;
        }
    }
}
.n-card.hc-card-overflow-box .n-card__content {
    padding: 24px;
}
.n-card.hc-custom-card > .n-card-header {
    padding: 15px 24px;
}
.n-card.hc-custom-card.copy {
    width: 1200px;
    max-height: 90vh;
    overflow: auto;
    .n-card-header .n-card-header__close {
        display: none;
    }
    &.one {
        width: 600px;
    }
    &.many {
        width: 1200px;
    }
}
.img-preview-box {
    position: relative;
    height: 100%;
    width: 100%;
}
.hc-layout-content-box {
    position: relative;
}

.iscusor {
    cursor: pointer;
}
.hc-table-form-action-tip .hc-alert {
    background-color: #f1f5f8;
    display: inline;
    vertical-align: middle;
    box-shadow: -2px 0 10px 0 rgba(32, 37, 50, 0.03),
        0 10px 21px 20px rgba(32, 37, 50, 0.03);
}
.copy-node-form-box {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #efeff5;
}
.hc-position-input-icon {
    position: relative;
    margin-bottom: 0;
    .el-form-item__content {
        position: relative;
        .el-textarea .el-textarea__inner {
            padding-right: 30px;
        }
        .hc-icon-i {
            position: absolute;
            right: 10px;
            bottom: 0;
            font-size: 20px;
            cursor: pointer;
            color: #0081ff;
            opacity: 1;
            transition: opacity 0.2s;
            &:hover {
                opacity: 0.5;
            }
        }
    }
}
</style>

<style lang="scss" scoped>
.hc-tree-back-to{
    display: flex;
    justify-content: space-between;
}
/* 新增拖拽排序相关样式 */
.sortable-ghost {
  opacity: 0.5;
  background: #f5f5f5;
  justify-content: center;
}

.hc-attachment-item {
  transition: all 0.3s;
  cursor: move;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  
  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.hc-attachment-content {
  min-height: 20px;
}

/* 原有样式保持不变 */
.hc-attachment-card {
  margin-bottom: 16px;
  
  .hc-attachment-header {
    font-weight: bold;
    margin-bottom: 8px;
    padding-left: 8px;
    border-left: 3px solid #409eff;

  }
  
  .hc-attachment-file-name {
    display: flex;
    align-items: center;
    
    .name {
      margin-left: 8px;
    }
  }
  
  .hc-attachment-btn-box {
    display: flex;
  }
}
</style>

<style>
.custom-tooltip-pro {
  background-color: #7691E0 !important;
  color: white !important;
  border: none !important;
  max-width: 300px !important; /* 最大宽度 */
  padding: 10px !important;
   font-size: 14px;




}

.tooltip-content {
  width: 100%;
}

.new-folder {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  cursor: pointer;
}

.add-icon {
  font-size: 18px;
}

.add-input-container {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 5px;
  margin-bottom: 8px;
  background: white;
}

.folder-input {
  flex: 1;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 4px;
 
}

.input-buttons {
  display: flex;
  gap: 8px;
}

.confirm-icon {
  color: #4CAF50;
  font-size: 18px;
}

.cancel-icon {
  color: #f44336;
  font-size: 18px;
}

.folder-list-container {
  max-height: 200px; /* 最大高度 */
  overflow-y: auto; /* 超出滚动 */
  overflow-x: hidden;
}

.folder-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 5px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.folder-name {
  margin-right: 15px; /* 名称与删除图标间距 */
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-icon {
  font-size: 18px;
  flex-shrink: 0; /* 防止图标被压缩 */
}

/* 滚动条样式优化 */
.folder-list-container::-webkit-scrollbar {
  width: 6px;
}

.folder-list-container::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}
</style>
