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


import com.clx.order.enums.QuotationEnum;
import com.clx.performance.dao.OrderChildDao;
import com.clx.performance.dao.OrderGoodsDao;
import com.clx.performance.dao.settle.*;
import com.clx.performance.dto.PayStatusNotifyDTO;
import com.clx.performance.enums.NetworkDriverAccountEnum;
import com.clx.performance.enums.OrderChildEnum;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.enums.settle.SettlementDriverEnum;
import com.clx.performance.enums.settle.SettlementOwnerDetailEnum;
import com.clx.performance.enums.settle.SettlementWayEnum;
import com.clx.performance.model.OrderChild;
import com.clx.performance.model.OrderGoods;
import com.clx.performance.model.settle.OrderChildSyncTransportRecord;
import com.clx.performance.model.settle.SettlementDriver;
import com.clx.performance.model.settle.SettlementDriverDetail;
import com.clx.performance.model.settle.SettlementOwnerDetail;
import com.clx.performance.param.pc.payment.PayPlatformFeeParam;
import com.clx.performance.service.PaymentService;
import com.clx.performance.service.settle.*;
import com.clx.performance.struct.settle.SettlementDriverDetailStruct;
import com.msl.common.result.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author kavin
 * Date 2023-12-08
 * Time 11:42
 */
@Service
@Slf4j
@AllArgsConstructor
public class OrderChildSyncTransportRecordServiceImpl implements OrderChildSyncTransportRecordService {

    private final OrderChildSyncTransportRecordDao orderChildSyncTransportRecordDao;

    private final SettlementDriverDetailStruct struct;

    private final NetworkCaseOutRecordDao networkCaseOutRecordDao;

    private final NetworkDriverRunningWaterRecordService networkDriverRunningWaterRecordService;

    private final SettlementDriverDetailService settlementDriverDetailService;

    private final OrderChildDao orderChildDao;

    private final  PaymentService paymentService;

    private final OrderGoodsDao orderGoodsDao;

    private final SettlementOwnerDetailDao settlementOwnerDetailDao;
    private final SettlementDriverDao settlementDriverDao;

    private final SettlementPostService settlementPostService;

    @Override
    public void addOrderChildSyncTransportRecord(SettlementDriverDetail detail) {
        OrderChildSyncTransportRecord record = struct.convertRecord(detail);
        record.setId(null);
        //0：未同步
        record.setStatus(0);
        orderChildSyncTransportRecordDao.saveEntity(record);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(PayStatusNotifyDTO payStatusNotifyDTO) {
        String childNo = payStatusNotifyDTO.getChildNo();
        //支付平台服务费
        OrderChild orderChild = orderChildDao.getByChildNo(childNo).orElseThrow(PerformanceResultEnum.ORDER_CHILD_NO_FOUND);
        OrderGoods orderGoods = orderGoodsDao.getByOrderGoodsNo(orderChild.getOrderGoodsNo()).orElseThrow(PerformanceResultEnum.ORDER_CHILD_NO_FOUND);
        SettlementOwnerDetail settlementOwnerDetail = settlementOwnerDetailDao
                .getByChildNo(orderChild.getChildNo()).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);

        SettlementDriver settlementDriver = settlementDriverDao
                .findByChildNo(settlementOwnerDetail.getChildNo()).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);
        settlementDriver.setStatus(SettlementDriverEnum.Status.SETTLED.getCode());
        settlementDriverDao.updatePayStatus(settlementDriver);

        settlementOwnerDetail.setPayStatus(SettlementOwnerDetailEnum.PayStatus.YES.getCode());
        settlementOwnerDetailDao.updatePayStatus(settlementOwnerDetail);

        orderChildSyncTransportRecordDao.updateStatus(childNo);

        networkCaseOutRecordDao.updateStatus(payStatusNotifyDTO.getChildNo(),
                NetworkDriverAccountEnum.CaseOutRecordStatus.PAYED.getCode(),
                NetworkDriverAccountEnum.CaseOutRecordStatus.PAYED.getMsg()
        );

        SettlementDriverDetail driverDetail = settlementDriverDetailService.selectOneByChildNo(childNo);

        orderChild.setStatus(OrderChildEnum.Status.COMPLETE.getCode());
        orderChild.setSettleTime(LocalDateTime.now());
        orderChild.setFinishTime(orderChild.getSettleTime());
        orderChildDao.updateSettlement(orderChild);

        if (Objects.equals(orderGoods.getPlatformFreightQuotationTaxType(),
                QuotationEnum.PlatformFreightQuotationTaxType.NO.getCode())
                && Objects.equals(orderGoods.getSettlementWay(), SettlementWayEnum.WayType.UNLOAD_LOSS.getCode())) {
            // 未税，卸车减货损
            networkDriverRunningWaterRecordService.generateCaseOutSuccessRunningWaterRecord1(driverDetail);
        }
        else {
            networkDriverRunningWaterRecordService.generateCaseOutSuccessRunningWaterRecord(driverDetail);
        }


        try{
            //支付平台服务费
            if (Objects.nonNull(orderChild.getPlatformServiceFee()) &&
                    !Objects.equals(orderChild.getPlatformServiceFee().intValue(), 0)) {
                PayPlatformFeeParam payPlatformFeeParam = PayPlatformFeeParam.builder()
                        .figure(orderChild.getPlatformServiceFee().intValue())
                        .tradeNo(childNo)
                        .build();
                Result result = paymentService.paymentCompletePlatformFee(payPlatformFeeParam);
                log.info("运单完成 第三方回调 {}  ,{} " ,childNo,result);
            }
        }catch (Exception e){
            log.error("支付平台服务费异常 {}",e);
        }

        settlementPostService.updateDriverPaySuccess(orderChild.getChildNo());
    }
}
