<template>
    <hc-new-dialog v-model="isShow" is-table widths="95%" :title="title" :loading="addNodeLoading" @save="modalSave" @close="closeAddModal">
        <div class="relative h-full flex">
            <div :id="`hc_tree_card_${uuid}`">
                <hc-new-card scrollbar>
                    <template #header>
                        <div class="text-sm text-orange">↓ 选择部位【点击新增】</div>
                    </template>
                    <div v-if="title === '合同计量单元新增'" class="tree-list">
                        <div v-for="(item, index) in treeDataList" :key="index" class="item" @click="treeListClick(item)">
                            <HcIcon name="box-3" fill />
                            <span class="ml-1">{{ item.nodeName }}</span>
                        </div>
                    </div>
                    <div v-else>
                        <HcDataTree
                            ref="leftTree"
                            tree-key="id"
                            show-checkbox
                            :datas="leftTreeData"
                            :h-props="lefttreeProps"
                            :default-expand-all="defaultExpandAll"
                            :check-strictly="checkStrictly"
                            :default-checked-keys="defaultCheckedKeys"
                            @node-tap="nodeElTreeClick"
                            @check="treeNodeCheck"
                        />
                    </div>
                </hc-new-card>
            </div>
            <div :id="`hc_table_card_${uuid}`" class="flex-1">
                <hc-new-card scrollbar title="合同计量单元">
                    <hc-table :is-index="false" :column="tableColumn" :datas="tableData" is-new :index-style="{ width: 60 }">
                        <template #nodeName="{ row }">
                            <hc-table-input v-model="row.nodeName" />
                        </template>
                        <template #startStake="{ row }">
                            <hc-table-input v-model="row.startStake" />
                        </template>
                        <template #endStake="{ row }">
                            <hc-table-input v-model="row.endStake" />
                        </template>
                        <template #contractPicture="{ row }">
                            <hc-table-input v-model="row.contractPicture" />
                        </template>
                        <template #isAddChildNode="{ row, index }">
                            <el-radio-group v-model="row.isAddChildNode" @change="changeIsAdd($event, row, index)">
                                <el-radio :value="1">是</el-radio>
                                <el-radio :value="0" class="ml-2">否</el-radio>
                            </el-radio-group>
                        </template>
                        <template #action="{ index }">
                            <el-link type="danger" @click="delRowClick(index)">删除</el-link>
                        </template>
                    </hc-table>
                </hc-new-card>
            </div>
        </div>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { arrToId, arrUnion, getArrValue, getRandom } from 'js-fast-way'
import unitApi from '~api/project/debit/contract/unit.js'
import { useAppStore } from '~src/store'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
    menuType:{
        type: [String, Number],
        default: '',
    },
    templateId:{
        type: [String, Number],
        default: '',
    },
    title:{
        type: [String],
         default: '合同计量单元新增',
    },
    parentData:{
        type:Object,
        default: () => ({}),

    },
    isTable: {
        type: Boolean,
        default: false,
    },
})
//事件
const emit = defineEmits(['finish', 'close'])
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')
const menuType = ref(props.menuType)
const ids = ref(props.ids)
const templateId = ref(props.templateId)
const title = ref(props.title)
const parentData = ref(props.parentData)
const isTable = ref(props.isTable)
const uuid = getRandom(4)

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})
const getTreeDataList = async ()=>{
    const { error, code, data } = await unitApi.getLeftList({
      id:ids.value,
    })

    if (!error && code === 200) {
        treeDataList.value = getArrValue(data)
    } else {
        treeDataList.value = []
    }
}

//表格数据
const tableColumn = ref([
    { key: 'nodeName', name: '名称' },
    { key: 'startStake', name: '开始桩号' },
    { key: 'endStake', name: '结束桩号' },
    { key: 'contractPicture', name: '合同图号' },
    { key: 'isAddChildNode', name: '是否划分子节点', width: 120, align: 'center' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
])
const leftTreeData = ref([])
const treeLoading = ref(false)
const getLeftTreeData = async (id) => {
    treeLoading.value = true
    const { error, code, data } = await unitApi.getCurrentNodeTree({
        id,
       contractId:contractId.value,

    })
    treeLoading.value = false
    if (!error && code === 200) {
        leftTreeData.value = getArrValue(data)

    } else {
        leftTreeData.value = []

    }
}
//监听
watch(() => [
    props.ids,
    props.menuType,
    props.templateId,
    props.title,
    props.parentData,
    props.isTable,
], ([Ids, Type, Tem, til, parent, tab]) => {
    ids.value = Ids
    menuType.value = Type
    templateId.value = Tem
    title.value = til
    parentData.value = parent
    isTable.value = tab
    if (title.value === '合同计量单元复制') {
            tableColumn.value = [
            { key: 'nodeName', name: '名称' },
            { key: 'startStake', name: '开始桩号' },
            { key: 'endStake', name: '结束桩号' },
            { key: 'contractPicture', name: '合同图号' },
            { key: 'isAddChildNode', name: '是否划分子节点', width: 120, align: 'center' },
            ]
    } else {
        tableColumn.value = [
            { key: 'nodeName', name: '名称' },
            { key: 'startStake', name: '开始桩号' },
            { key: 'endStake', name: '结束桩号' },
            { key: 'contractPicture', name: '合同图号' },
            { key: 'isAddChildNode', name: '是否划分子节点', width: 120, align: 'center' },
            { key: 'action', name: '操作', width: 80, align: 'center' },
        ]
    }
    getTreeDataList()
    if (isShow.value) {
        getLeftTreeData(ids.value)
        checkStrictly.value = false
    }

}, { immediate: true })

//监听
watch(isShow, (val) => {
    if (val) {
        setSplitRef()
        checkStrictly.value = false



    }
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    nextTick(() => {
        window.$split(['#hc_tree_card_' + uuid, '#hc_table_card_' + uuid], {
            sizes: [20, 80],
            snapOffset: 0,
            minSize: [50, 500],
        })
    })
}

const treeDataList = ref([])
const treeListClick = (item) => {
    tableData.value.push({
        nodeName: item.nodeName,
        startStake: '',
        endStake: '',
        contractPicture: '',
        isAddChildNode: 1,
        leftNodeId:item.id,
    })
}

const tableData = ref([])

//删除
const delRowClick = (index) => {
    tableData.value.splice(index, 1)
}
const addNodeLoading = ref(false)
const modalSave = async () => {
    if (tableData.value.length === 0) {
        window.$message.warning('请选择部位点击新增')
        return
    }
    if (title.value === '合同计量单元新增') {

        const { error, code, msg } = await unitApi.addNode({
            contractId:contractId.value,
            projectId:projectId.value,
            contractNodeId:ids.value,
            requestType:menuType.value === 'add' ? 1 : 2, //请求类型 1=节点新增 2=增补单元新增
            templateId: templateId.value,
            dataList:tableData.value,

        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)
            tableData.value = []

        } else {
             window.$message.error(msg)
         }
        emit('finish')
    } else {
        console.log(tableData.value, 'tableData.value')
        const { error, code, msg } = await unitApi.copyNode({
            contractId:contractId.value,
            id:ids.value,
            vo2s:tableData.value,
        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)
            tableData.value = []

        } else {
             window.$message.error(msg)
         }
        emit('finish')
    }
}
const closeAddModal = ()=>{
    tableData.value = []
}

const lefttreeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'notExsitChild',
}
const nodeElTreeClick = (data)=>{

}
// 递归函数来获取节点的所有父级对象
const getAllParents = (tree, targetId, parents = [])=> {
  for (const node of tree) {
    if (node.id === targetId) {
      return parents
    }
    if (node.children && node.children.length > 0) {
      const parentCopy = [...parents]
      parentCopy.push(node)
      const result = getAllParents(node.children, targetId, parentCopy)
      if (result) {
        return result
      }
    }
  }
  return null
}
const treeNodeCheck = (checkdata, { checkedNodes, halfCheckedNodes }) => {
   let allArr = arrUnion(halfCheckedNodes, checkedNodes)
    tableData.value = []
    allArr.forEach((item)=>{
        tableData.value.push(
            { nodeName: item.nodeName,
            startStake: '',
            endStake: '',
            contractPicture: '',
            isAddChildNode: item.isAddChildNode,
            id:item.id,
            parentId:item.parentId,
            isParent:item?.children ? true : false,
           },
        )
    })

    if (checkedNodes.length > 0 ) {
        let alarr = tableData.value
             // 使用reduce方法进行去重
            const uniqueArray = alarr.reduce((acc, current) => {
            // 检查当前对象的某个字段是否已存在于累积数组中
            const x = acc.find(item => item.id === current.id)

            // 如果不存在，则将其添加到累积数组中
            if (!x) {
                return acc.concat([current])
            } else {
                return acc
            }
            }, [])

            tableData.value = uniqueArray


    }

}
const checkStrictly = ref(false)
const defaultCheckedKeys = ref([])
const defaultExpandAll = ref(true)

const changeIsAdd = (val, row, index)=>{
        const { isParent } = row
        if (isParent && val === 0) {
            let rowTreeData = leftTree.value.treeRef.getNode(row.id)
            let delKeys = arrToId(rowTreeData.data.children).split(',')
            nextTick(()=>{
                delKeys.forEach((ele)=>{

                    leftTree.value.treeRef.setChecked(ele, false, true)
                    leftTree.value.treeRef.setChecked(row.id, true, false)
                    let checkKeys = leftTree.value.treeRef.getCheckedKeys()
                    let arr = []
                    tableData.value.forEach((ele)=>{
                        checkKeys.forEach((ele1)=>{
                            if (ele.id === ele1) {
                                arr.push(ele)
                            }
                        })
                    })
                    tableData.value = arr

                })
                const isIdExist = tableData.value.some(obj => obj.id === parentData.value.id)
                if (!isIdExist) {
                    tableData.value.unshift(
                            { nodeName: parentData.value.nodeName,
                            startStake: '',
                            endStake: '',
                            contractPicture: '',
                            isAddChildNode:1,
                            id:parentData.value.id,
                            parentId:parentData.value.parentId,
                            isParent:true,
                            },
                 )
                }

            })
        } else if (isParent && val === 1) {
            checkStrictly.value = false
            let rowTreeData = leftTree.value.treeRef.getNode(row.id)
            let delKeys = arrToId(rowTreeData.data?.children).split(',') || []
            let checkNodes = []
            nextTick(()=>{
                delKeys.forEach((ele)=>{
                    leftTree.value.treeRef.setChecked(ele, true, true)
                    checkNodes = leftTree.value.treeRef.getCheckedNodes()
                })
                const filteredArray1 = checkNodes.filter(obj1 => !tableData.value.some(obj2 => obj1.id === obj2.id))

                filteredArray1.forEach((ele)=>{
                    tableData.value.push(
                        { nodeName: ele.nodeName,
                        startStake: '',
                        endStake: '',
                        contractPicture: '',
                        isAddChildNode:1,
                        id:ele.id,
                        parentId:ele.parentId,
                        isParent:ele?.children ? true : false,
                        },
                    )
                })
            })
        }
}
const leftTree = ref(null)
</script>

<style lang="scss" scoped>
.tree-list {
    position: relative;
    .item {
        position: relative;
        height: 24px;
        display: flex;
        align-items: center;
        white-space: nowrap;
        cursor: pointer;
        transition: color .2s;
        &:hover {
            color: var(--el-color-primary);
        }
    }
}
</style>
