<!-- 关联资料 -->
<template>
    <hc-new-dialog v-model="linkModal" is-table title="关联资料" widths="1200px" @close="closeModal">
        <span class="text-orange font-400">温馨提示：允许单对多、多对单、多对多的关联关系。关联后可在对应节点清单列表下查看“关联并继续”可继续进行关联。</span>
        <div class="title-box">
            <div class="title-box-left">合同计量单元部位</div>
            <div class="title-box-right">WBS树</div>
        </div>
        <div class="link-data-box">
            <div class="link-data-left">
                <div class="relative h-full flex">
                    <div v-loading="treeLoading" class="hc_tree_card_border relative w-full">
                        <hc-body scrollbar padding="0px">
                            <HcDataTree 
                                ref="leftTree"
                                tree-key="id" 
                                show-checkbox 
                                :datas="leftTreeData" 
                                :h-props="lefttreeProps" 
                                :default-checked-keys="defaultCheckedKeys" 
                                :auto-expand-keys="autoExpandKeys"
                                @node-tap="nodeElTreeClick"
                                @check="treeNodeCheck"
                            />
                        </hc-body>
                    </div>
                </div>
            </div>
            <div class="link-data-icon">
                <HcIcon type="primary" name="links" style="font-size: 22px;" />
            </div>
            <div class="link-data-right">
                <div class="relative h-full flex">
                    <div v-loading="treeLoading" class="hc_tree_card_border relative w-full">
                        <hc-body scrollbar padding="0px">
                            <HcDataTree 
                                ref="rightTree"
                                tree-key="pkeyId" 
                                show-checkbox :datas="rightTreeData" 
                                :h-props="treeProps" 
                                :default-checked-keys="rightKeys" 
                                @node-tap="nodeElTreeClickRight" 
                                @check="treeNodeCheckRight" 
                            />
                        </hc-body>
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button hc-btn style="border: 1px solid var(--el-button-border-color);" @click="closeModal">
                    <HcIcon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button hc-btn type="primary" :loading="sureLoading" @click="sureClick(1)">
                    <HcIcon name="check" />
                    <span>关联并退出</span>
                </el-button>
                <el-button hc-btn type="primary" :loading="sureLoading" @click="sureClick(2)">
                    <HcIcon name="check" />
                    <span>关联并继续</span>
                </el-button>
            </div>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue, getObjValue } from 'js-fast-way'
import { useAppStore } from '~src/store'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import unitApi from '~api/project/debit/contract/unit'
import { linkEmits } from 'element-plus'
const props = defineProps({
    linkModal: {
        type: Boolean,
        default: false,
    },
    isCheckId:{
        type: Number,
        default: 1,
    },
    checkIds:{
        type: [Number, String],
        default: '',
    },
    rightTreeCheck:{
        type: Array,
        default: () => ([]),
    },
  
})
//事件
const emit = defineEmits(['close', 'save'])
const useAppState = useAppStore()
const contractId = ref(useAppState.getContractId)
const projectId = ref(useAppState.getProjectId)
const isCheckId = ref(props.isCheckId)
const checkIds = ref(props.checkIds)
const rightTreeCheck = ref(props.rightTreeCheck)

const linkModal = defineModel('modelValue', {
    default: false,
})
const closeModal = ()=>{
    linkModal.value = false
    emit('close')
}
//获取两棵树的数据
const treeLoading = ref(false)
const leftTreeData = ref([])
const rightTreeData = ref([])
const getTwotreeData = async () => {
    treeLoading.value = true
    const { error, code, data } = await unitApi.getMeterTreeAndWbsTree({
        projectId:projectId.value,
       contractId:contractId.value,
  
    })
    treeLoading.value = false
    if (!error && code === 200) {
        leftTreeData.value = getArrValue(data['meterTree'])
        rightTreeData.value = getArrValue(data['wbsTree'])
        if (isCheckId.value === 2) {
            nextTick(()=>{
                addDisabledFlag(leftTreeData.value)
            })
        }
    
            
    } else {
        leftTreeData.value = []
        rightTreeData.value = []
    }
}

const addDisabledFlag = (data) =>{
  data.forEach(node => {
    // 给当前节点添加 disabled 属性
    node.disabled = true

    // 如果当前节点有子节点，则递归调用 addDisabledFlag 函数
    if (node.children && node.children.length > 0) {
      addDisabledFlag(node.children)
    }
  })
}
//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
}
const lefttreeProps = {
    label: 'nodeName',
    children: 'children',
    disabled: 'disabled',
}
const defaultCheckedKeys = ref([])
const rightKeys = ref([])
 const autoExpandKeys = ref([])
 const meterIds = ref('')
const wbsIds = ref('')
const rightTree = ref(null)
const leftTree = ref(null)
//监听
watch(() => [
props.linkModal,
props.isCheckId,
props.checkIds,
props.rightTreeCheck,
], ([link, check, ids, right]) => {
    linkModal.value = link
    isCheckId.value = check
    checkIds.value = ids
    rightTreeCheck.value = right
    if (link) {
        getTwotreeData()
    }
   
  

    if (check === 2) {
        const keys = getStoreValue('wbsTreeExpandKeys')
        autoExpandKeys.value = keys
        defaultCheckedKeys.value = [ids]
        wbsIds.value = right.join(',')
        meterIds.value = ids
        rightKeys.value = right
     
    } else {
        autoExpandKeys.value = []
        defaultCheckedKeys.value = []
        rightKeys.value = []
        wbsIds.value = ''
        meterIds.value = ''
    }
}, { immediate: true })


const sureLoading = ref(false)
const sureClick = async (type)=>{

    if (!meterIds.value || !wbsIds.value) {
        window.$message.warning('请先选择需要关联的节点')
        return
    }
    sureLoading.value = true
    const { error, code, data, msg } = await unitApi.LinkMeterTreeAndWbsTree({
        projectId:projectId.value,
       contractId:contractId.value,
       meterIds:meterIds.value,
       wbsIds:wbsIds.value,
  
    })
    sureLoading.value = false
    if (!error && code === 200) {
     window.$message.success(msg)
   if (type === 1) {
    linkModal.value = false
    emit('save')
   } else {
    if (isCheckId.value === 1) {
        nextTick(()=>{
            autoExpandKeys.value = []
            defaultCheckedKeys.value = []
            rightKeys.value = []
            wbsIds.value = ''
            meterIds.value = ''
            leftTree.value.treeRef.setCheckedKeys([])
            rightTree.value.treeRef.setCheckedKeys([])
            })
    }
   }
    
    } else {
        window.$message.error(msg)
    }
}


const nodeElTreeClick = ()=>{
    
}

const treeNodeCheck = (_, { checkedNodes }) => {
    console.log(checkedNodes, 'checkedNodes')
    let arr = []
    checkedNodes.forEach(ele => {
        if (!ele.hasChild) {
            arr.push(ele.id)
        }
    })
  
    meterIds.value = arr.join(',')
}
const nodeElTreeClickRight = ()=>{
    
}
const treeNodeCheckRight = (_, { checkedNodes }) => {
    let arr = []
    checkedNodes.forEach(ele => {
        if (!ele.hasChild) {
            arr.push(ele.pkeyId)
        }
    })
  
    wbsIds.value = arr.join(',')
}
</script>

<style lang='scss' scoped>
.title-box{
    position: relative;
    display: flex;

    // padding: 40px;
    font-weight: 400;
    font-size: 18px;
    width: 100%;
    margin-bottom: 10px;
    margin-top: 10px;
 
    .title-box-left{
       width: 50%;
       text-align: center;
    }
    .title-box-right{
       width: 50%;
       text-align: center;
    }
}
.link-data-box{
    position: relative;
    display: flex;
    height: calc(100% - 45px);
    align-items: center;
    // border: 1px solid rgb(187, 187, 187);
    padding: 0px 40px 40px 40px;
    .link-data-left{
        width: 50%;
        position: relative;
        height: 100%;
        background: #ffffff;
        border: 1px solid #273044;
    }
    .link-data-icon{
        display: inline-block;
        vertical-align: middle;
        padding: 0 16px;
    }
    .link-data-right{
        width: 50%;
        position: relative;
        height: 100%;
        background: #ffffff;
        border: 1px solid #273044;
    }
}
</style>