package cn.superdesk.uniorder.openapi.service.qchjc.accounting;

import cn.superdesk.uniorder.common.enums.invoice.customer.InvoiceApplyCustomerBackAccountStatusEnum;
import cn.superdesk.uniorder.common.exception.OpenApiException;
import cn.superdesk.uniorder.dubbo.facade.thirdpart.qchjc.accounting.DubboQchjcCustomerStatementService;
import cn.superdesk.uniorder.openapi.api._thirdpart.qchjc._dto.accounting.QchjcCustomerStatementDto;
import cn.superdesk.uniorder.openapi.api._thirdpart.qchjc._dto.accounting.QchjcCustomerStatementStatusDto;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author xc
 * @description 采购单位对账单
 * @date 2022/3/31 11:02
 */
@Slf4j
@Service
public class CustomerStatementService {

    @Reference(version = "1.0.0", timeout = 300000, retries = -1)
    private DubboQchjcCustomerStatementService dubboQchjcCustomerStatementService;

    /**
     * 采购单位对账单接收
     *
     * @param dto
     */
    public void receive(QchjcCustomerStatementDto dto) {
        //保存到中间表-待入库状态
        try {
            dubboQchjcCustomerStatementService.receive(JSON.toJSONString(dto));
        } catch (UndeclaredThrowableException e) {
            Throwable cause = e.getUndeclaredThrowable().getCause();
            if (cause instanceof OpenApiException) {
                throw (OpenApiException) cause;
            } else {
                throw e;
            }
        }
    }

    /**
     * 采购单位对账单状态同步 集采 -> 结算中心
     *
     * @param dto
     */
    public void syncStatus(QchjcCustomerStatementStatusDto dto) {
        try {
            verifyParam(dto);
            dubboQchjcCustomerStatementService.syncStatus(JSON.toJSONString(dto));
        } catch (UndeclaredThrowableException e) {
            Throwable cause = e.getUndeclaredThrowable().getCause();
            if (cause instanceof OpenApiException) {
                throw (OpenApiException) cause;
            } else {
                throw e;
            }
        }
    }

    private void verifyParam(QchjcCustomerStatementStatusDto dto) {
        Integer backAccountModeRecord = dto.getBackAccountModeRecord();
        Integer backAccountStatus     = dto.getBackAccountStatus();
        if (!InvoiceApplyCustomerBackAccountStatusEnum.未回款.getKey().equals(backAccountStatus)
                && !InvoiceApplyCustomerBackAccountStatusEnum.已回款.getKey().equals(backAccountStatus)) {
            throw new OpenApiException(500, "回款状态值错误");
        }
        if (0 != backAccountModeRecord && 10 != backAccountModeRecord && 11 != backAccountModeRecord) {
            throw new OpenApiException(500, "回款登记方式值错误");
        }
    }


}
