import { queryDeliveryRelation } from "@/services/go/delivery";
import { QueryDeliveryRelationRsp } from '@/services/go/delivery/interface';
import { ref, watchEffect } from "vue";

// 所有交割关系
const allDeliveryRelation = ref<QueryDeliveryRelationRsp[]>([])
export function handleDeliveryRelation() {
    function hasDR() {
        return allDeliveryRelation.value.length !== 0
    }
    /**
     * 查询交割商品关系
     */
    function queryDR() {
        queryDeliveryRelation({}).then(res => {
            allDeliveryRelation.value = res
        })
    }
    /**
     * 更新交割商品
     */
    function updateDeliveryRelation() {
        queryDR()
    }
    if (!hasDR()) {
        queryDR()
    }
    /**
     * 通过goodsid 查找对应的交割商品
     * @param goodsid
     * @returns
     */
    function getItemDeliveryRelationByGoodsId(goodsid: number) {
        const result = ref<QueryDeliveryRelationRsp>()
        const fn = () => allDeliveryRelation.value.find(e => e.goodsid === goodsid)
        const stop = watchEffect(() => {
            result.value = fn()
        })
        if (hasDR()) {
            stop()
        }
        return result
        // return allDeliveryRelation.value.find(e => e.goodsid === goodsid)
    }
    return { allDeliveryRelation, updateDeliveryRelation, getItemDeliveryRelationByGoodsId }
}