<template>
    <div class="h-full">
        <div v-if="wbsTypeTabKey === 'tree'" class="hc-layout-box" element-loading-text="批量保存数据中...">
            <div
                id="wbs-left-tree" :class="[isWbsTreeShow ? 'show' : '', isMouseTree ? 'on-transition' : '']"
                :style="`width:${isWbsTreeShow ? leftWidth : 0}px; ${isWbsTreeShow ? '' : 'display: none'}`"
                class="hc-layout-left-box 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">
                    <div class="hc-tree-back-to">
                        <HcTooltip keys="hide-data-show">
                            <el-button type="primary" hc-btn keys="hide-data-show" :loading="showTreeNodeLoad" @click="showTreeNode">显示</el-button>
                        </HcTooltip>
                    </div>
                    <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

                                :datas="searchTreeData"
                                :is-mark="TreeMark"

                                is-counts
                                is-type
                                :auto-expand-keys="TreeAutoExpandKeys"
                                default-expand-all
                                @node-tap="wbsElTreeClick"
                            >
                                <template #default="{ node, data, level }">
                                    <div class="data-custom-tree-node">
                                        <!-- 树组件，节点名称 -->
                                        <div :class="node.level === 1 ? 'level-name' : ''" class="label">
                                            <span v-if="(data.type > 0 && data.majorDataType > 0) || (data.type > 0 && data.majorDataType <= 0)" class="hc-tree-node-type">
                                                {{ getTreeNodeType(data.type, data.majorDataType) }}
                                            </span>

                                            <span :class="data.isBussShow === '2' ? 'text-red' : ''">
                                                {{ node.label }}
                                            </span>
                                        </div>
                                        <!-- 树组件，统计数量 -->
                                        <div class="submit-counts text-blue">【{{ data.submitCounts ?? 0 }}】</div>


                                        <!-- 树组件，操作菜单 END -->
                                    </div>
                                </template>
                            </HcDataTree>
                        </el-scrollbar>
                        <el-scrollbar v-show="!isSearchTree" class="scroll-bar-right-16">
                            <HcLazyTree
                                ref="wbstree"
                                :auto-expand-keys="TreeAutoExpandKeys"
                                :is-mark="TreeMark"
                                is-counts
                                is-type
                                show-checkbox
                                check-strictly
                                @load="treeLoadNode"

                                @node-loading="ElTreeNodeLoading"
                                @node-tap="wbsElTreeClick"
                                @check="ElTreeNodeCheck"
                            >
                                <template #default="{ node, data, level }">
                                    <div class="data-custom-tree-node">
                                        <!-- 树组件，节点名称 -->
                                        <div :class="node.level === 1 ? 'level-name' : ''" class="label">
                                            <span v-if="(data.type > 0 && data.majorDataType > 0) || (data.type > 0 && data.majorDataType <= 0)" class="hc-tree-node-type">
                                                {{ getTreeNodeType(data.type, data.majorDataType) }}
                                            </span>

                                            <span :class="data.isBussShow === '2' ? 'text-red' : ''">
                                                {{ node.label }}
                                            </span>
                                        </div>
                                        <!-- 树组件，统计数量 -->
                                        <div class="submit-counts text-blue">【{{ data.submitCounts ?? 0 }}】</div>


                                        <!-- 树组件，操作菜单 END -->
                                    </div>
                                </template>
                            </HcLazyTree>
                        </el-scrollbar>
                    </div>
                </div>
                <div class="hc-tree-foot-tip-box">
                    <div class="dot-view red">已隐藏</div>
                    <div class="dot-view black">未隐藏</div>
                </div>
                <!-- 左右拖动 -->
                <div class="horizontal-drag-line" @mousedown="onmousedown" />
            </div>
            <div id="wbs-content-box" v-loading="ListItemLoading" class="hc-layout-content-box">
                <!---展开收缩树 -->
                <div class="hc-expansion-contraction-tree" @click="setWbsTreeShow">
                    <HcIcon v-show="isWbsTreeShow" name="arrow-left-s" />
                    <HcIcon v-show="!isWbsTreeShow" name="arrow-right-s" />
                </div>
                <hc-tab-card :tabs="authBtnTabdata" :tab-key="authBtnTabKey" @change="authBtnTabClick">
                    <el-scrollbar v-if="ListItemDatas.length > 0" ref="ListItemScrollRef">
                        <CollapseForm
                            ref="ListItemRef"
                            :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>
            </div>
        </div>
    </div>
</template>

<script setup>
import { nextTick, onActivated, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '~src/store'
import { HcIsButton } from '~src/plugins/IsButtons'
import CollapseForm from './collapse-form/index.vue'
import NodeTree from './components/nodeTree/index.vue'

import { getTreeNodeType } from 'hc-vue3-ui'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import {
    arrToKey,
    getArrValue,
    getObjValue,
    isNullES,
} from 'js-fast-way'
import { getDictionary } from '~api/other'
import wbsApi from '~api/data-fill/wbs'
import queryApi from '~api/data-fill/query'




//初始变量
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 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 () => {
    treeLoading.value = true
    const { error, code, data } = await queryApi.getTreeNodeByQueryValueAndContractId({
        contractId: contractId.value,
        queryValue: searchTreeVal.value,
        tableOwner:authBtnTabKey.value,
        description: 1,
    })
    //判断状态
    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,
], ([classify]) => {
 if (classify) {
      //重新加载左边树
      isShowLeft.value = false
        setTimeout(()=>{
            isShowLeft.value = true
        }, 500)
 }

})
//渲染完成
onMounted(() => {
    console.log(projectInfo.value)
    treeLoading.value = typeName === 'tree'
    setContractType(contractInfo.value?.contractType)
    getDictionaryApi()
})
onActivated(()=>{
    //重新加载左边树
    isShowLeft.value = false
        setTimeout(()=>{
            isShowLeft.value = true
        }, 500)
})
//身份按钮切换数据
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()
//     wbstree.value.resetNode().then((res)=>{
//         if(res){
//             searchNodeAllTable()
//             queryNodeStatus()
//         }
//  })
    //保存后自动展开到当前表单
    if (!isNullES(key)) {
        console.log(key)
        await nextTick(() => {
            ListItemRef.value?.setCollapseKey(key)
        })
    }
}

//结构类型tab数据和相关处理
const wbsTypeTabKey = ref(typeName)
const wbsTypeTab = ref([
    { key: 'map', name: '导图结构填报' },
    { key: 'tree', name: '树形结构填报' },
])
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 NodeTreeAccordion = ref(true)

//设置树菜单数据

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,
        description: 1,
    })
    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 NodeTreeRef = ref(null)

//鼠标左键单击事件
const NodeTreeClick = ({ keys }) => {
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
}

//双击事件
const isDrawer = ref(false)
const NodeTreeDblClick = ({ node, data }) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    primaryKeyId.value = data?.primaryKeyId || ''
    isDrawer.value = true
    getTableDataAll()
}
const drawerClose = () => {
    isDrawer.value = false
    ListItemDatas.value = []
}









//获取节点类型
const nodeTypeData = ref([])
const getDictionaryApi = async () => {
    const { data } = await getDictionary({
        code: 'wbs_node_type',
    })
    //处理数据
    let newArr = []
    const newData = getArrValue(data)
    for (let i = 0; i < newData.length; i++) {
        newArr.push({
            label: newData[i]['dictValue'],
            value: Number(newData[i]['dictKey']),
        })
    }
    nodeTypeData.value = newArr
}


































//设置滚动条位置
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)
















//划分变更
const divisionClick = () => {
    router.push({
        path: '/data-fill/division',
    })
}

//树展开和收起
const isWbsTreeShow = ref(true)
const setWbsTreeShow = () => {
    isWbsTreeShow.value = !isWbsTreeShow.value
}



//左右拖动，改变树形结构宽度
const leftWidth = ref(382)
const isMouseTree = ref(false)
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    isMouseTree.value = true
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum
        if (diffVal >= 310 && diffVal <= 900) {
            leftWidth.value = diffVal
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
        isMouseTree.value = false
    }
}






//树节点被选中
const treeSelectNode = ref([])

const treeSelectdata = ref([])
const ElTreeNodeCheck = (_, { checkedKeys, checkedNodes }) => {
    console.log(checkedNodes, 'checkedNodes')
    treeSelectNode.value = getArrValue(checkedKeys)
    treeSelectdata.value = getArrValue(checkedNodes)
}
const showTreeNodeLoad = ref(false)
const showTreeNode = async ()=>{
    const keys = arrToKey(treeSelectdata.value, 'pKeyId', ',')
    if (keys.length <= 0) {
        window?.$message?.warning('请先在左侧项目树选择节点')
        return
    }
    //发起请求
    showTreeNodeLoad.value = true
    const { error, code, msg } = await wbsApi.updateNodeStates({
        ids: keys,
        status:1,

    }, false)
    showTreeNodeLoad.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg || '操作成功')
         //重新加载左边树
            isShowLeft.value = false
            setTimeout(()=>{
                isShowLeft.value = true
            }, 500)

    } else {
        window?.$message?.error(msg)
    }
}
</script>

<style lang="scss" scoped>
@import "../../styles/data-fill/wbs.scss";
.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%;
}
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-box .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: .5;
            }
        }
    }
}
</style>
