package com.clx.performance.service.impl.breakcontract;

import com.clx.performance.dao.breakcontract.BreakContractSettlementDriverDao;
import com.clx.performance.enums.BreakContractSettlementDriverEnum;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.model.breakcontract.BreakContractSettlementDriver;
import com.clx.performance.service.breakcontract.BreakContractJobHandlerService;
import com.clx.performance.service.payment.PayService;
import com.msl.common.exception.ServiceSystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Slf4j
@Service
public class BreakContractJobHandlerServiceImpl implements BreakContractJobHandlerService {

    @Autowired
    private BreakContractSettlementDriverDao breakContractSettlementDriverDao;

    @Autowired
    private PayService payService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void pay(Integer settlementId){

        BreakContractSettlementDriver breakContractSettlementDriver = breakContractSettlementDriverDao.getEntityByKey(settlementId).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);

        if (Objects.equals(breakContractSettlementDriver.getSettleStatus(), BreakContractSettlementDriverEnum.SettleStatus.YES)){
            return;
        }

        try {
            pay(breakContractSettlementDriver);
        }catch (ServiceSystemException e){
            breakContractSettlementDriver.setPayRemark(e.getMessage());
            breakContractSettlementDriverDao.updatePayFail(breakContractSettlementDriver);
        }

    }

    /**
     * 支付
     */
    private void pay(BreakContractSettlementDriver settlement){

        // 车主
        if (Objects.equals(settlement.getBreakContractPartyType(), BreakContractSettlementDriverEnum.BreakContractPartyType.DRIVER.getCode())){

            payService.driverPay(settlement.getSettlementNo(), settlement.getTruckOwnUserNo(), settlement.getFigure().intValue());
        }
        // 平台
        else if (Objects.equals(settlement.getBreakContractPartyType(), BreakContractSettlementDriverEnum.BreakContractPartyType.PLATFORM.getCode())) {
            payService.payDriver(settlement.getSettlementNo(), settlement.getTruckOwnUserNo(), settlement.getFigure().intValue());

        }
    }

}
