<template>
    <hc-sys class="hc-ledger-table-form" navBarUi="white">
        <template #navBar>
            <hc-nav-back-bar title="关联工序">
                <text @click="finishClick">确定</text>
            </hc-nav-back-bar>
        </template>
        <uni-section title="关联工序列表" type="line" class="mt-1px">
            <uni-list>
                <uni-list-item :title="item.path" v-for="(item, index) in linkIds" >
                    <template v-slot:footer>
                        <view>
                            <uni-tag :inverted="true" @click="clearItem(index)" text="删除" type="error" />
                        </view>
                    </template>
                </uni-list-item>
            </uni-list>
        </uni-section>

        <!--底部操作栏-->
        <HcTabbarBlock :height="85"/>
        <hc-tabbars>
            <button class="check-btn" type="primary" @click="addLinks">新增关联工序</button>
        </hc-tabbars>

        <!-- 普通弹窗 -->
        <hc-popup ref="popupRef" @confirm="popupConfirm">
            <hc-tree ref="hcTreeRef" check strictly :checkKey="treeCheckKey" @load="getLazyLoad"/>
        </hc-popup>
    </hc-sys>
</template>

<script setup>
import {ref, onMounted, nextTick, getCurrentInstance} from "vue";
import {onLoad, onShow, onUnload} from '@dcloudio/uni-app'
import {getArrValue, getObjValue} from "js-fast-way";
import wbsApi from '~api/data-fill/wbs';
import mainApi from '~api/ledger/index';
import {useAppStore} from "@/store";

const store = useAppStore()
const instance = getCurrentInstance().proxy

//初始变量
const contractInfo = ref(store.contractInfo);
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);
const itemFormId = ref('');

//页面传参数据
let eventChannel = null;
const getEventChannel = async () => {
    await nextTick();
    eventChannel = instance.getOpenerEventChannel();
}

onLoad((option) => {
    itemFormId.value = option?.id ?? ''
    getEventChannel()
    querySelectProcessList()
})

//已关联的工序
const linkIds = ref([])
const treeCheckKey = ref([])

//查询已关联的工序
const querySelectProcessList = async () => {
    if (itemFormId.value) {
        const { data } = await mainApi.queryCurrentLogSelectProcessList({
            contractId: contractId.value ?? '',
            businessId: itemFormId.value,
        })
        linkIds.value = getArrValue(data)
    } else {
        linkIds.value = []
    }
}

//删除当前的节点
const clearItem = (index) => {
    linkIds.value.splice(index, 1)
}

//新增关联工序
const popupRef = ref(null)
const addLinks = () => {
    let ids = linkIds.value, tree_check_key = []
    for (let i = 0; i < ids.length; i++) {
        const {primaryKeyId} = ids[i]
        tree_check_key.push(primaryKeyId ? primaryKeyId + '' : '')
    }
    treeCheckKey.value = tree_check_key
    popupRef.value?.open()
}

//获取树形数据
const hcTreeRef = ref(null)
const getLazyLoad = async (node, resolve) => {
    const { contractType } = contractInfo.value
    const { id, primaryKeyId, contractIdRelation } = getObjValue(node.data)
    const { data } = await wbsApi.queryWbsTreeData({
        contractId: contractId.value || '',
        contractIdRelation: contractIdRelation ?? '',
        primaryKeyId: id ?? '',
        parentId: node.level <= 0 ? '' : contractIdRelation ? primaryKeyId : id,
        classifyType: node.level <= 0 ? '' : contractType ?? '',
        tableOwner: contractType ?? ''
    })
    resolve(getArrValue(data))
}

//确认选择
const popupConfirm = async () => {
    const linkTabIds = []
    const { nodes } = await hcTreeRef.value?.getCheckKeys()
    for (let i = 0; i < nodes.length; i++) {
        let pathArr = [], item = nodes[i]
        if (item.level > 1) {
            getPathName(item, pathArr)
            linkTabIds.push({
                path: pathArr.join('/'),
                primaryKeyId: item.key,
            })
        }
    }
    linkIds.value = linkTabIds
    popupRef.value?.close()
}

//获取节点的路径名字
const getPathName = (node, pathArr) => {
    if (node.level > 1) {
        pathArr.unshift(node.label.replace(/(^\s*)|(\s*$)/g, '')) //去掉头尾空格
        getPathName(node.parentNodes, pathArr)
    }
}

//确认关联工序
const finishClick = () => {
    eventChannel.emit('finish', linkIds.value);
    uni.navigateBack()
}
</script>

<style lang="scss" scoped>
page {
    height: 100%;
    background: #FAFBFE;
}
</style>

<style lang="scss">

</style>
