package com.sckw.report.service;

import com.sckw.report.api.model.ViewUrl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.model.dto.req.ContractAuditPara;
import com.sckw.contract.api.model.dto.res.ContractDetailRespVo;
import com.sckw.contract.api.model.dto.res.LogisticDetailRespVo;
import com.sckw.contract.api.model.vo.ContractCountVo;
import com.sckw.contract.api.model.vo.ContractVo;
import com.sckw.core.utils.BeanUtils;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.*;
import com.sckw.report.service.vo.OperationCountVo;
import com.sckw.report.api.model.TodoCountVo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.transport.api.dubbo.TransportRemoteService;
import com.sckw.transport.api.feign.TransportApi;
import com.sckw.transport.api.model.vo.LogisticsDto;
import com.sckw.transport.api.model.param.LogisticsOrderAuditPara;
import com.sckw.transport.api.model.param.TimePara;
import com.sckw.transport.api.model.vo.CountPara2;
import com.sckw.transport.api.model.vo.LogisticsVo;
import com.sckw.transport.api.model.vo.TransportTopStatisticsVo;
import com.sckw.transport.api.model.vo.WaybillOrderDetailVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zk
 * @desc 订单服务
 * @date 2023/7/10 0010
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class KwHomeService {

    private final TransportApi transportApi;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 80000)
    private RemoteContractService remoteContractService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 80000)
    private TradeOrderInfoService tradeOrderInfoService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 80000)
    private TransportRemoteService transportRemoteService;

    /**
     * 运营统计
     *
     * @return
     */
    public OperationCountVo operationCount() {
        ContractCountVo contractCountVo = remoteContractService.contractCount();
        Long aLong = tradeOrderInfoService.orderCount();
        Long aLong1 = transportRemoteService.queryCount();
        return new OperationCountVo(contractCountVo.getTradeContractCount(), contractCountVo.getLogisticsContractCount(), aLong, aLong1, 0L);
    }


    public List<ContractVo> operationTradeContract() {
        return remoteContractService.tradeList();
    }

    public List<ContractVo> operationLogisticsContract() {
        return remoteContractService.logisticsList();
    }

    public List<TradeVo> operationTradeOrder() {
        return tradeOrderInfoService.tradeList();
    }

    public List<LogisticsVo> operationLogisticsOrder() {
        return transportRemoteService.logisticsList();
    }

    public SaleDto countSale(CountPara countPara) {
        return tradeOrderInfoService.countSale(countPara);
    }

    public BuyDto countBuy(CountPara countPara) {
        return tradeOrderInfoService.countBuy(countPara);
    }

    public Object countLogistics(CountPara countPara) {
        return transportRemoteService.countLogistics(BeanUtils.toBean(countPara, CountPara2.class));
    }

    public GoodsDto countGoods(CountPara countPara) {
        return tradeOrderInfoService.countGoods(countPara);
    }

    public TimeSaleDto timeSale() {
        CountPara countPara = new CountPara();
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        countPara.setStartTime(LocalDateTimeUtil.formatNormal(localDateTime));
        countPara.setEndTime(LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
        return tradeOrderInfoService.timeSale(countPara);
    }

    public RankDto buyRank() {
        CountPara countPara = new CountPara();
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        countPara.setStartTime(LocalDateTimeUtil.formatNormal(localDateTime));
        countPara.setEndTime(LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
        return tradeOrderInfoService.buyRank(countPara);
    }

    public LogisticsDto logisticsRank() {
        TimePara timePara = new TimePara();
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        timePara.setStartTime(LocalDateTimeUtil.formatNormal(localDateTime));
        timePara.setEndTime(LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
        return transportRemoteService.logisticsRank(timePara);
    }

    public ContractDetailRespVo auditTradeContract(ContractAuditPara contractAuditPara) {
        return remoteContractService.auditTradeContract(contractAuditPara);
    }

    public ContractDetailRespVo signTradeContract(ContractAuditPara contractAuditPara) {
        return remoteContractService.signTradeContract(contractAuditPara);
    }

    public LogisticDetailRespVo signLogisticsContract(ContractAuditPara contractAuditPara) {
        return remoteContractService.signLogisticsContract(contractAuditPara);
    }

    public OrderDetailRes auditTradeOrder(TradeOrderAuditPara para) {
        return tradeOrderInfoService.auditTradeOrder(para);
    }

    public WaybillOrderDetailVo auditLogisticsTask(LogisticsOrderAuditPara para) {
        return transportRemoteService.auditLogisticsTask(para);
    }

    /**
     * 查询首页顶部运输统计数据。
     * <p>
     * 现有 Dubbo 接口只能提供部分数量统计，无法同时满足：
     * 累计运量、累计车次、今日车次、今日运量四个口径，
     * 因此这里通过 Feign 复用运输服务新增的聚合接口，避免在报表模块重复拼装业务逻辑。
     * </p>
     *
     * @return 顶部四项统计指标
     */
    public TransportTopStatisticsVo transportTopStatistics() {
        log.info("开始调用运输服务查询顶部运输统计数据");
        try {
            TransportTopStatisticsVo statisticsVo = transportApi.topStatistics();
            if (statisticsVo == null) {
                log.warn("运输服务返回顶部运输统计数据为空，使用默认零值返回");
                return buildDefaultTransportTopStatistics();
            }
            log.info("顶部运输统计数据查询完成，result={}", statisticsVo);
            return statisticsVo;
        } catch (Exception e) {
            // 顶部卡片属于展示型接口，远程服务异常时降级为零值，避免页面整体不可用。
            log.error("调用运输服务查询顶部运输统计数据失败，使用默认零值降级返回", e);
            return buildDefaultTransportTopStatistics();
        }
    }

    private TransportTopStatisticsVo buildDefaultTransportTopStatistics() {
        return TransportTopStatisticsVo.builder()
                .totalTransportAmount(BigDecimal.ZERO)
                .totalTripCount(0L)
                .todayTripCount(0L)
                .todayTransportAmount(BigDecimal.ZERO)
                .build();
    }

    public TodoCountVo todoCount() {
        ContractCountVo contractCountVo = remoteContractService.contractCount();
        Long aLong = tradeOrderInfoService.orderCount();
        Long aLong1 = transportRemoteService.queryCount();
        TodoCountVo todoCountVo = new TodoCountVo();
        todoCountVo.setTradeContractCount(new ViewUrl(contractCountVo.getTradeContractCount(), "/#/contractManagement/tradeContract/list"));
        todoCountVo.setLogisticsContractCount(new ViewUrl(contractCountVo.getLogisticsContractCount(), "/#/contractManagement/logisticsContract/list"));
        todoCountVo.setTradeOrderCount(new ViewUrl(aLong, "/#/orderManagement/tradeOrder/list"));
        todoCountVo.setLogisticsOrderCount(new ViewUrl(aLong1, "/#/operatManagement/logisticsWaybill/list"));
        return todoCountVo;
    }
}
