import { api_costFeeSetProductIdList, api_customerFeeGroupList } from '@/api/lading/lading';
import { CustomerFeeProductObject } from '@/api/receivable/receivableModel';
import { deal_FeeDateVersionList } from '@/utils/dealData';
import { isArrayLength } from '@/utils/is';
import { resCodeSuccess } from '@/utils/useReturnData';
import { reactive, computed, unref, Ref } from 'vue';

type CustomerFeeList = {
    parentId: string;
    customerFeeProductIdDtoList: CustomerFeeProductObject[]
}
type DateVersionType = "receivable" | "payable"
/**
 * 查找处理对应的费用日期版本
 * @param customerFeeList 
 * @param ClosingCostFeeRef 
 * @returns 
 */
function useFeeDateVersionList(dateVersionList: Ref<CustomerFeeList[]>, dataType: DateVersionType) {
    // 基础数据
    const stateFeeDateVersion = reactive<{ customerFeeList: Recordable[] }>({
        customerFeeList: []
    })
    const getCustomerFeeList = computed(() => {
        return stateFeeDateVersion.customerFeeList
    })

    // 初始化单个费用版本数据
    const initDateVersion = async (feeSetParentId) => {
        if (!feeSetParentId) return
        switch (dataType) {
            case "receivable":
                const receivableRes = await api_customerFeeGroupList({ parentIdList: [feeSetParentId] })
                if (resCodeSuccess(receivableRes)) {
                    const dataResult = receivableRes.data
                    if (isArrayLength(dataResult)) stateFeeDateVersion.customerFeeList = deal_FeeDateVersionList(dataResult[0]['customerFeeProductIdDtoList'])
                }
                break;
            case "payable":
                const payableRes = await api_costFeeSetProductIdList({ parentIdList: [feeSetParentId] })
                if (resCodeSuccess(payableRes)) {
                    const dataResult = payableRes.data
                    if (isArrayLength(dataResult)) stateFeeDateVersion.customerFeeList = deal_FeeDateVersionList(dataResult[0]['costFeeSetProductIdDtoList'])
                }
                break;
        }
    }
    // 成本的稳定费用的日期版本 =》 从模版获取为空
    const initSelect = (row) => {
        const data = unref(dateVersionList).find(item => item.parentId === row.feeSetParentId)
        if (data) {
            const field = dataType === 'receivable' ? 'customerFeeProductIdDtoList' : 'costFeeSetProductIdDtoList'
            stateFeeDateVersion.customerFeeList = deal_FeeDateVersionList(data[field])
            return false
        }
        const feeFindData = stateFeeDateVersion.customerFeeList.find(item => item.parentId === row.feeSetParentId)
        if (!feeFindData) initDateVersion(row.feeSetParentId)
    }
    // 点击当前行表格事件
    const feeCellClick = (scope) => {//val: boolean, { row }
        const isEditByRow = scope.$grid.isEditByRow(scope.row)
        if (!isEditByRow) initSelect(scope.row)
    }

    return {
        feeCellClick,
        getCustomerFeeList,
    }
}

export { useFeeDateVersionList, CustomerFeeList }