package com.clx.performance.job.settlement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clx.performance.dao.OrderChildDao;
import com.clx.performance.dao.OrderChildSyncTransportInvoiceRecordDao;
import com.clx.performance.dao.settle.*;
import com.clx.performance.model.OrderChild;
import com.clx.performance.model.settle.*;
import com.clx.performance.service.broker.OrderChildBrokerMqService;
import com.clx.performance.service.settle.SettlementMqService;
import com.msl.common.job.JobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor

public class SettlementJob {

    // 默认30天
    private static final Integer EFFECT_TIME = 30;
    private final OrderChildSyncTransportInvoiceRecordDao orderChildSyncTransportInvoiceRecordDao;

    private final SettlementMqService settlementMqService;
    private final SettlementOwnerDetailDao settlementOwnerDetailDao;
    private final SettlementDriverDetailDao settlementDriverDetailDao;
    private final SettlementDriverDao settlementDriverDao;
    private final SettlementOwnerDao settlementOwnerDao;
    private final OrderChildSyncTransportRecordDao orderChildSyncTransportRecordDao;
    private final OrderChildBrokerMqService orderChildBrokerMqService;
    private final OrderChildDao orderChildDao;

    /**
     * 同步无车承运运单开票类型
     */
    @XxlJob("settlementInvoiceTypeSync")
    public void settlementInvoiceTypeSync() {
        // 首次
        List<SettlementOwnerDetail> recordList = settlementOwnerDetailDao
                .listInvoiceTypeSync();

        log.info("待同步无车承运运单状态，size:{}", recordList.size());
        if (recordList.isEmpty()) {return;}

        for (SettlementOwnerDetail item : recordList) {

            settlementMqService.invoiceTypeSync(item.getChildNo());
        }
    }

    /**
     * 司机确认收货同步
     */
    @XxlJob("settlementDriverConfirmSync")
    public void settlementDriverConfirmSync() {
        List<SettlementDriver> recordList = settlementDriverDao
                .listDriverConfirmSync();
        log.info("待司机确认收货同步，size:{}", recordList.size());
        if (recordList.isEmpty()) {return;}

        List<OrderChild> childList = orderChildDao.findListByChildNoList(
                recordList.stream().map(SettlementDriver::getChildNo).collect(Collectors.toList()));
        childList = childList.stream().filter(item -> item.getConfirmTime() != null).collect(Collectors.toList());
        log.info("待司机确认收货同步，size:{}", childList.size());

        for (OrderChild item : childList) {

            settlementMqService.settlementDriverConfirm(item.getChildNo());
        }
    }

    /**
     * 同步无车承运运单支付受理
     */
    @XxlJob("settlementDriverPayAcceptSync")
    public void settlementDriverPayAcceptSync() {

        List<SettlementDriverDetail> recordList = settlementDriverDetailDao
                .listDriverPayAcceptSync();

        log.info("待同步无车承运运单支付受理，size:{}", recordList.size());
        if (recordList.isEmpty()) {return;}

        for (SettlementDriverDetail item : recordList) {

            settlementMqService.driverPayAcceptSync(item.getChildNo());
        }
    }

    /**
     * 同步无车承运运单开票状态
     */
    @XxlJob("settlementInvoiceStatusSync")
    public void settlementInvoiceStatusSync() {
        try {
            List<SettlementOwnerDetail> list = settlementOwnerDetailDao.listInvoiceStatusSync();
            log.info("待同步无车承运运单开票状态, size:{}", list.size());
            if (list.isEmpty()) {return;}

            for (SettlementOwnerDetail item : list) {
                settlementMqService.invoiceStatusSync(item.getChildNo());
            }
        } catch (Exception e) {
            log.warn("同步无车承运运单开票状态失败，异常原因:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("同步无车承运运单开票状态失败，异常原因=====================", e);
        }
    }

    /**
     * 同步无车承运运单支付状态
     */
    @XxlJob("settlementPayStatusSync")
    public void settlementPayStatusSync() {
        try {
            List<OrderChildSyncTransportRecord> list = orderChildSyncTransportRecordDao.selectListForJob();

            log.info("待同步无车承运运单支付状态, size:{}", list.size());
            if (list.isEmpty()) {return;}

            for (OrderChildSyncTransportRecord item : list) {

                settlementMqService.payStatusSync(item.getChildNo());
            }
        } catch (Exception e) {
            log.warn("同步无车承运运单支付状态失败，异常原因:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("同步无车承运运单支付状态失败，异常原因=====================", e);
        }
    }

    /**
     * 结算单平台自动确认更新
     */
    @XxlJob("settlementPlatformAutoConfirmUpdate")
    public void settlementPlatformAutoConfirmUpdate() {
        try {
            Integer effectTime= null;

            String jobParam= XxlJobHelper.getJobParam();
            log.info("结算单平台自动确认更新, param:{}", jobParam);
            if (StringUtils.isNotBlank(jobParam)) {
                JSONObject jsonObject = JSON.parseObject(jobParam);
                effectTime = jsonObject.getInteger("effectTime");
            }
            if (effectTime == null) {
                effectTime = EFFECT_TIME;
            }

            LocalDateTime time = LocalDateTime.now().minusDays(effectTime);
            List<SettlementOwner> list = settlementOwnerDao.listPlatformToBeConfirmed(time);

            log.info("结算单平台自动确认更新, size:{}", list.size());
            if (list.isEmpty()) {return;}

            for (SettlementOwner item : list) {

                settlementMqService.settlementPlatformAutoConfirmUpdate(item.getSettlementNo());
            }
        } catch (Exception e) {
            log.warn("结算单平台自动确认更新失败，msg:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("结算单平台自动确认更新失败", e);
        }
    }


    /**
     * 网络货运运单更新(测试)
     */
    @XxlJob("settlementBrokerOrderChildUpdateTest")
    public void settlementBrokerOrderChildUpdateTest() {
        try {
            List<String> childNoList=null;

            String jobParam= XxlJobHelper.getJobParam();
            log.info("网络货运运单更新, param:{}", jobParam);
            if (StringUtils.isNotBlank(jobParam)) {
                childNoList = JSON.parseArray(jobParam, String.class);
            }
            if (childNoList == null || childNoList.isEmpty()) {
                return;
            }

            for (String childNo : childNoList) {

                // 发送mq (运单更新)
                orderChildBrokerMqService.orderChildUpdate(childNo);
            }
        } catch (Exception e) {
            log.warn("网络货运运单更新失败，msg:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("网络货运运单更新失败", e);
        }
    }

    /**
     * 网络货运运单同步(测试)
     */
    @XxlJob("settlementBrokerOrderChildSyncTest")
    public void settlementBrokerOrderChildSyncTest() {
        try {
            List<String> childNoList=null;

            String jobParam= XxlJobHelper.getJobParam();
            log.info("网络货运运单同步, param:{}", jobParam);
            if (StringUtils.isNotBlank(jobParam)) {
                childNoList = JSON.parseArray(jobParam, String.class);
            }
            if (childNoList == null || childNoList.isEmpty()) {
                return;
            }

            for (String childNo : childNoList) {

                // 发送mq (运单同步)
                orderChildBrokerMqService.orderChildSync(childNo);
            }
        } catch (Exception e) {
            log.warn("网络货运运单同步失败，msg:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("网络货运运单同步失败", e);
        }
    }

    /**
     * 网络货运运单支付同步(测试)
     */
    @XxlJob("settlementDriverPayTest")
    public void settlementDriverPayTest() {
        try {
            List<String> childNoList=null;

            String jobParam= XxlJobHelper.getJobParam();
            log.info("网络货运运单支付同步, param:{}", jobParam);
            if (StringUtils.isNotBlank(jobParam)) {
                childNoList = JSON.parseArray(jobParam, String.class);
            }
            if (childNoList == null || childNoList.isEmpty()) {
                return;
            }

            for (String childNo : childNoList) {

                // 发送mq (运单司机支付)
                orderChildBrokerMqService.orderChildDriverPay(childNo);
            }
        } catch (Exception e) {
            log.warn("网络货运运单支付同步 失败，msg:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("网络货运运单支付同步 失败", e);
        }
    }

}
