package com.clx.performance.listener;

import cn.hutool.json.JSONUtil;
import com.clx.order.vo.pc.carrier.InvoicingCompanyVO;
import com.clx.performance.component.IdGenerateSnowFlake;
import com.clx.performance.component.ThirdComponent;
import com.clx.performance.config.SettlementConfig;
import com.clx.performance.constant.RabbitKeyConstants;
import com.clx.performance.dao.OrderChildSyncTransportInvoiceRecordDao;
import com.clx.performance.dao.OrderGoodsDao;
import com.clx.performance.dao.OwnerAccountDao;
import com.clx.performance.dao.OwnerRunningWaterRecordDao;
import com.clx.performance.dao.settle.SettlementDriverDetailDao;
import com.clx.performance.dao.settle.SettlementOwnerDetailDao;
import com.clx.performance.dto.OrderChildSyncDTO;
import com.clx.performance.dto.OwnerLoanMqDTO;
import com.clx.performance.enums.*;
import com.clx.performance.enums.settle.SettlementDriverEnum;
import com.clx.performance.enums.settle.SettlementOwnerDetailEnum;
import com.clx.performance.enums.settle.SettlementOwnerEnum;
import com.clx.performance.enums.settle.SettlementWayEnum;
import com.clx.performance.event.OwnerLoanEvent;
import com.clx.performance.extranal.order.InvoicingCompanyService;
import com.clx.performance.feign.TransportFeignService;
import com.clx.performance.model.*;
import com.clx.performance.model.settle.SettlementDriverDetail;
import com.clx.performance.model.settle.SettlementOwnerDetail;
import com.clx.performance.param.feign.transport.ThirdOrderChildBrokerParam;
import com.clx.performance.service.TransportSyncService;
import com.clx.performance.service.broker.OrderChildSyncBrokerService;
import com.clx.performance.service.settle.NetworkDriverRunningWaterRecordService;
import com.msl.common.dto.HttpDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

/**
 * 承运同步网络货运运单
 */
@Slf4j
@Component
@AllArgsConstructor
public class OrderChildSyncTransportListener {

    private final OrderGoodsDao orderGoodsDao;

    private final TransportSyncService transportSyncService;

    private final TransportFeignService transportFeignService;

    private final OwnerRunningWaterRecordDao ownerRunningWaterRecordDao;

    private final NetworkDriverRunningWaterRecordService networkDriverRunningWaterRecordService;

    private final OwnerAccountDao ownerAccountDao;

    private final IdGenerateSnowFlake idGenerateSnowFlake;

    private final SettlementOwnerDetailDao settlementOwnerDetailDao;

    private final SettlementDriverDetailDao settlementDriverDetailDao;

    private final OrderChildSyncTransportInvoiceRecordDao orderChildSyncTransportInvoiceRecordDao;

    private final ApplicationEventPublisher applicationEventPublisher;
    private final InvoicingCompanyService invoicingCompanyService;
    private final SettlementConfig settlementConfig;
    private final OrderChildSyncBrokerService orderChildSyncBrokerService;

    /**
     * 承运同步网络货运运单
     */
    @RabbitListener(queues = RabbitKeyConstants.ORDER_CHILD_SYNC_TRANSPORT_QUEUE)
    public void onMessage(String message) {
        OrderChild orderChild = JSONUtil.toBean(message, OrderChild.class);
        //是否通过风控,调用网络货运
        try {
            transportOrderChildProcess(orderChild);
        } catch (Exception e) {
            log.info("当前OrderChildSyncTransportListener监听同步网络货运失败,运单号{}, 错误信息{}", orderChild.getChildNo(), ExceptionUtils.getStackTrace(e));

            OrderChildSyncTransportInvoiceRecord entity = new OrderChildSyncTransportInvoiceRecord();
            entity.setChildNo(orderChild.getChildNo());
            entity.setType(TransportSyncTypeEnum.Type.EXCEPTION.getCode());
            entity.setRemark(e.getMessage());
            orderChildSyncTransportInvoiceRecordDao.saveEntity(entity);
        }
    }

    public void transportOrderChildProcess(OrderChild orderChild) {
//        Integer invoiceType = SettlementOwnerEnum.InvoiceType.ORDINARY.getCode();

        OrderGoods orderGoods = orderGoodsDao.getByOrderGoodsNo(orderChild.getOrderGoodsNo()).get();

        SettlementOwnerDetail settlementOwnerDetail = settlementOwnerDetailDao.getByChildNo(orderChild.getChildNo()).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);
        SettlementDriverDetail settlementDriverDetail = settlementDriverDetailDao.getByChildNo(orderChild.getChildNo()).orElseThrow(PerformanceResultEnum.DATA_NOT_FIND);
        settlementOwnerDetail.setInvoiceFreight(invoiceFreightCalc(orderChild.getSettlementWay(), orderGoods.getInvoiceServiceFeeRate(), settlementOwnerDetail));

//        // 同步网络货运
//        ThirdOrderChildBrokerParam param = transportSyncService.generateOrderChildSync(orderChild, orderGoods, settlementOwnerDetail, settlementDriverDetail);
//        HttpDTO httpDTOResult = transportFeignService.orderChildSync(param);
//        String decrypt = ThirdComponent.decrypt(httpDTOResult.getData());
//        OrderChildSyncDTO bean = JSONUtil.toBean(decrypt, OrderChildSyncDTO.class);
//        extracted(orderChild, bean, JSONUtil.parse(bean).toString(), settlementOwnerDetail, invoiceType, settlementDriverDetail);

        // 同步broker
        orderChildSyncBrokerService.orderChildSync(orderChild, orderGoods, settlementOwnerDetail, settlementDriverDetail);

//        extracted(orderChild, bean, JSONUtil.parse(bean).toString(), settlementOwnerDetail, invoiceType, settlementDriverDetail);
    }

    public void extracted(OrderChild orderChild, OrderChildSyncDTO bean, String remark,
                           SettlementOwnerDetail settlementOwnerDetail,
                           Integer invoiceType, SettlementDriverDetail settlementDriverDetail) {
        OrderGoods orderGoods = orderGoodsDao.getByOrderGoodsNo(orderChild.getOrderGoodsNo()).get();

        if (null != bean  && bean.getCode() == 0) {
            log.info("当前OrderChildSyncTransportListener监听同步网络货运成功,运单号为{}", orderChild.getChildNo());
            if (null != bean.getData() && bean.getData().getStatus() == 1) {
                //通过风控
                List<OwnerRunningWaterRecord> runningWaterRecordList = ownerRunningWaterRecordDao.getOwnerRunningWaterRecord(orderChild.getOrderNo());
                BigDecimal frozen = runningWaterRecordList.stream().filter(item -> {
                    return item.getRunningWaterType().equals(OwnerAccountEnum.RunningWaterStatus.FROZEN.getCode())
                            && item.getAccountType().equals(OwnerAccountEnum.AccountTypeStatus.PREPAID_FREIGHT_ACCOUNT.getCode())
                            ;
                }).map(OwnerRunningWaterRecord::getAlterationBalance).reduce(BigDecimal.ZERO, BigDecimal::add);

                BigDecimal takeOut = runningWaterRecordList.stream().filter(item -> {
                    return item.getRunningWaterType().equals(OwnerAccountEnum.RunningWaterStatus.TAKE_OUT.getCode())
                            && item.getAccountType().equals(OwnerAccountEnum.AccountTypeStatus.PREPAID_FREIGHT_ACCOUNT.getCode())
                            ;
                }).map(OwnerRunningWaterRecord::getAlterationBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
                //设置预付运费金额
                BigDecimal ans = getPrepayFreightPay(orderChild.getSettlementWay(), settlementOwnerDetail, frozen);
                BigDecimal subtract = frozen.subtract(takeOut);
                log.info("冻结预付运费:{}, 扣除的流水总和：{}", frozen, takeOut);
                invoiceType = SettlementOwnerEnum.InvoiceType.ONLINE.getCode();
                settlementDriverDetail.setPrepayFreight(ans);
                //冻结的预付运费为0 或者 此刻预付运费也可能为0，那么就不用生成扣除相关流水逻辑
                if (subtract.compareTo(BigDecimal.ZERO) <= 0 || ans.compareTo(BigDecimal.ZERO) == 0) {
                    settlementOwnerDetail.setPrepayFreight(BigDecimal.ZERO);
                    settlementDriverDetail.setPrepayFreightFlag(SettlementDriverEnum.PrepayFreightFlag.NO_PAY.getCode());

                } else {
                    if (subtract.subtract(ans).compareTo(BigDecimal.ZERO) >= 0) {
                        //账户扣钱并生成扣除流水
                        generateTakeOutRunningWatter(orderChild, ans, settlementOwnerDetail, settlementDriverDetail);
                        try {
                            //网络货运钱包账户
                            networkDriverRunningWaterRecordService.generateNetworkDriverRunningWaterRecord(
                                    settlementDriverDetail,
                                    NetworkDriverAccountEnum.RunningWaterStatus.SETTLEMENT.getCode()
                            );
                            //生成提现记录
                            networkDriverRunningWaterRecordService.generateNetworkCaseOutRecord(settlementDriverDetail);
                        } catch (Exception e) {
                            log.info("运单同步网络货运生成司机运单结算流水失败：{}", e.getMessage());
                        }

                    } else {
                        settlementOwnerDetail.setPrepayFreight(BigDecimal.ZERO);
                        settlementDriverDetail.setPrepayFreightFlag(SettlementDriverEnum.PrepayFreightFlag.NO_PAY.getCode());
                    }
                }
            }
            else {
                settlementDriverDetail.setPrepayFreightFlag(SettlementDriverEnum.PrepayFreightFlag.NO_PAY.getCode());
                settlementOwnerDetail.setPrepayFreight(BigDecimal.ZERO);
                settlementOwnerDetail.setFinalPaymentStatus(SettlementOwnerDetailEnum.FinalPaymentStatus.NO.getCode());
            }
        }
        else {
            log.info("当前OrderChildSyncTransportListener监听同步网络货运失败,变为普通单,运单号{}, 错误信息{}", orderChild.getChildNo(), remark);
            settlementDriverDetail.setPrepayFreightFlag(SettlementDriverEnum.PrepayFreightFlag.NO_PAY.getCode());
            settlementOwnerDetail.setPrepayFreight(BigDecimal.ZERO);
            settlementOwnerDetail.setFinalPaymentStatus(SettlementOwnerDetailEnum.FinalPaymentStatus.NO.getCode());
        }

        // 结算金额
        settlementOwnerDetail.setSettlementFreight(settlementFreightCalc(orderChild.getSettlementWay(), settlementOwnerDetail));

        if (SettlementOwnerEnum.InvoiceType.ORDINARY.getCode().equals(invoiceType)) {
            if (settlementOwnerDetail.getSettlementFreight().compareTo(BigDecimal.ZERO) == 0) {
                settlementOwnerDetail.setFinalPaymentStatus(SettlementOwnerDetailEnum.FinalPaymentStatus.NO_REQUIRE.getCode());
            }
            // 如果开票标识为“普通单”时，开票费率从开票公司“五寨华祥”中获取
            settlementOwnerDetail.setInvoiceServiceFeeRate(BigDecimal.ZERO);

            InvoicingCompanyVO invoiceCompany = invoicingCompanyService.getInvoicingCompanyByGroupCode(
                    settlementConfig.getOrdinaryInvoiceCompanyGroupCode());
            //设置开票公司信息
            settlementOwnerDetail.setInvoicingCompanyId(invoiceCompany.getId());
            settlementOwnerDetail.setInvoicingCompanyShorterName(invoiceCompany.getCompanyShorterName());
            settlementOwnerDetail.setInvoicingCompanyGroupCode(invoiceCompany.getCompanyGroupCode());

            settlementDriverDetail.setInvoicingCompanyId(invoiceCompany.getId());
            settlementDriverDetail.setInvoicingCompanyShorterName(invoiceCompany.getCompanyShorterName());
            settlementDriverDetail.setInvoicingCompanyGroupCode(invoiceCompany.getCompanyGroupCode());
        } else {
            if (settlementDriverDetail.getSettlementFreight().compareTo(BigDecimal.ZERO) == 0) {
                settlementOwnerDetail.setFinalPaymentStatus(SettlementOwnerDetailEnum.FinalPaymentStatus.NO_REQUIRE.getCode());
            }
            // 如果开票标识为“网运单”时，开票费率取货单单所记录的开票费率
            settlementOwnerDetail.setInvoiceServiceFeeRate(
                    orderGoods.getInvoiceServiceFeeRate()==null? BigDecimal.ZERO : orderGoods.getInvoiceServiceFeeRate());
        }
        settlementOwnerDetail.setInvoiceType(invoiceType);
        settlementDriverDetail.setInvoiceType(invoiceType);

        // 开票服务费
        settlementOwnerDetail.setInvoiceServiceFee(invoiceServiceFeeCalc(orderChild.getSettlementWay(), settlementOwnerDetail));
        // 开票金额
        settlementOwnerDetail.setInvoiceFreight(invoiceFreightCalc(orderChild.getSettlementWay(),
                orderGoods.getInvoiceServiceFeeRate(), settlementOwnerDetail));

        //货主借款事件处理
        OwnerLoanMqDTO dto = new OwnerLoanMqDTO();
        dto.setSettlementOwnerDetail(settlementOwnerDetail);
        dto.setSettlementDriverDetail(settlementDriverDetail);
        dto.setOrderChild(orderChild);
        applicationEventPublisher.publishEvent(new OwnerLoanEvent(this, dto));

    }

    private void generateTakeOutRunningWatter(OrderChild orderChild, BigDecimal ans, SettlementOwnerDetail settlementOwnerDetail, SettlementDriverDetail settlementDriverDetail) {
        OwnerAccount account = null;
        while (true) {
            account = ownerAccountDao.getAccountByOwnerUserNoAndAccountType(orderChild.getOwnerUserNo(),
                    OwnerAccountEnum.AccountTypeStatus.PREPAID_FREIGHT_ACCOUNT.getCode());
            OwnerAccount update = new OwnerAccount();
            update.setId(account.getId());
            update.setAccountBalance(ans);
            update.setModifiedTime(account.getModifiedTime());
            update.setFrozenBalance(ans);
            Integer i = ownerAccountDao.updateOwnerAccountForConfirm(update);
            if (null != i && i > 0) {
                break;
            }
        }
        account = ownerAccountDao.getAccountByOwnerUserNoAndAccountType(orderChild.getOwnerUserNo(),
                OwnerAccountEnum.AccountTypeStatus.PREPAID_FREIGHT_ACCOUNT.getCode());

        settlementOwnerDetail.setPrepayFreight(ans);
        settlementDriverDetail.setPrepayFreightFlag(SettlementDriverEnum.PrepayFreightFlag.PAYED.getCode());
        settlementOwnerDetail.setFinalPaymentStatus(SettlementOwnerDetailEnum.FinalPaymentStatus.NO_REQUIRE.getCode());


        OwnerRunningWaterRecord runningWaterRecord = new OwnerRunningWaterRecord();
        runningWaterRecord.setOwnerUserName(orderChild.getOwnerName());
        runningWaterRecord.setMobile(orderChild.getDriverMobile());
        runningWaterRecord.setCreateBy("系统");
        runningWaterRecord.setOrderNo(orderChild.getOrderNo());
        runningWaterRecord.setOrderChildId(orderChild.getId());
        runningWaterRecord.setOrderChildNo(orderChild.getChildNo());
        runningWaterRecord.setRelationId(null);
        runningWaterRecord.setAlterationBalance(ans);
        runningWaterRecord.setFrozenBalance(account.getFrozenBalance());
        runningWaterRecord.setUsableBalance(account.getUsableBalance());
        runningWaterRecord.setTakeOutBalance(ans);
        runningWaterRecord.setAccountBalance(account.getAccountBalance());
        runningWaterRecord.setOwnerUserNo(account.getOwnerUserNo());

        runningWaterRecord.setAccountType(OwnerAccountEnum.AccountTypeStatus.PREPAID_FREIGHT_ACCOUNT.getCode());
        runningWaterRecord.setRunningWaterType(OwnerAccountEnum.RunningWaterStatus.TAKE_OUT.getCode());
        runningWaterRecord.setRunningWaterNo(idGenerateSnowFlake.nextId(IdTypeEnum.Type.TAKE_OUT.getCode()));
        ownerRunningWaterRecordDao.saveEntity(runningWaterRecord);
    }

    private BigDecimal getPrepayFreightPay(Integer settlementWay, SettlementOwnerDetail settlementOwnerDetail, BigDecimal accountFrozenFreight) {
        //订单结算方式为“装车净重”时
        if (Objects.equals(settlementWay, SettlementWayEnum.WayType.LOAD.getCode())) {
            BigDecimal subtract = settlementOwnerDetail.getFreight().subtract(settlementOwnerDetail.getLossFreight());
            if (accountFrozenFreight.compareTo(subtract) >= 0) {
                return subtract;
            } else {
                return BigDecimal.ZERO;
            }
        } else {
            if (accountFrozenFreight.compareTo(settlementOwnerDetail.getFreight()) >= 0) {
                return settlementOwnerDetail.getFreight();
            } else {
                return BigDecimal.ZERO;
            }
        }
    }



    /**
     * 开票金额
     */
    private BigDecimal invoiceFreightCalc(Integer settlementWay, BigDecimal invoiceServiceFeeRate, SettlementOwnerDetail settlementOwnerDetail) {
        if (Objects.equals(settlementWay, SettlementWayEnum.WayType.LOAD.getCode())) { //订单结算方式为“装车净重”时，开票金额=实际净重*平台运费报价-货损金额。
            return settlementOwnerDetail.getWeight().multiply(settlementOwnerDetail.getFreightPrice())
                    .subtract(settlementOwnerDetail.getLossFreight());
        }
        else if (Objects.equals(settlementWay, SettlementWayEnum.WayType.UNLOAD_LOSS.getCode())) {
            if (invoiceServiceFeeRate!=null){
                //结算方式为“卸车净重（减货损）”，平台运费报价为“未税”时，开票金额=平台运费单价*实际净重-货损单价*货损吨数+开票服务费。
                return settlementOwnerDetail.getWeight().multiply(settlementOwnerDetail.getFreightPrice())
                        .subtract(settlementOwnerDetail.getLossPrice())
                        .add(settlementOwnerDetail.getInvoiceServiceFee());
            }
            else{
                //结算方式为“卸车净重（减货损）”，平台运费报价为“含税”时   开票金额=平台运费单价*实际净重-货损单价*货损吨数
                return settlementOwnerDetail.getWeight().multiply(settlementOwnerDetail.getFreightPrice())
                        .subtract(settlementOwnerDetail.getLossFreight());
            }
        }
        else { //订单结算方式为“卸车净重”时，开票金额=实际净重*平台运费报价。
            return settlementOwnerDetail.getWeight().multiply(settlementOwnerDetail.getFreightPrice());
        }
    }
    /**
     * 开票服务费金额
     */
    private BigDecimal invoiceServiceFeeCalc(Integer settlementWay, SettlementOwnerDetail settlementOwnerDetail) {
        return settlementOwnerDetail.getFreight().subtract(settlementOwnerDetail.getLossFreight())
                .divide(BigDecimal.ONE.subtract(settlementOwnerDetail.getInvoiceServiceFeeRate()), 0, RoundingMode.HALF_UP)
                .multiply(settlementOwnerDetail.getInvoiceServiceFeeRate()).setScale(0, RoundingMode.HALF_UP);
    }

    private BigDecimal settlementFreightCalc(Integer settlementWay, SettlementOwnerDetail settlementOwnerDetail) {
        if (Objects.equals(settlementWay, SettlementWayEnum.WayType.LOAD.getCode())) { //订单结算方式为“装车净重”时，结算金额=实际净重*平台运费报价-预付运费-货损金额。
            return settlementOwnerDetail.getWeight().multiply(settlementOwnerDetail.getFreightPrice())
                    .subtract(settlementOwnerDetail.getPrepayFreight()).subtract(settlementOwnerDetail.getLossFreight());
        }
        else if (Objects.equals(settlementWay, SettlementWayEnum.WayType.UNLOAD_LOSS.getCode())) {
            //结算方式为“卸车净重（减货损）“，结算金额=开票金额-预付运费金额-借款抵扣金额。
            return settlementOwnerDetail.getInvoiceFreight()
                    .subtract(settlementOwnerDetail.getPrepayFreight())
                    .subtract(settlementOwnerDetail.getLoanFreight());

        }else { //订单结算方式为“卸车净重”时，结算金额=实际净重*平台运费报价-预付运费
            return settlementOwnerDetail.getWeight().multiply(settlementOwnerDetail.getFreightPrice()).subtract(settlementOwnerDetail.getPrepayFreight());
        }
    }

}
