package com.ghy.quartz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.enums.OrderStatus;
import com.ghy.common.enums.WxMsgEnum;
import com.ghy.common.utils.WechatMsgUtils;
import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.goods.domain.DeptGoodsCategory;
import com.ghy.goods.domain.Goods;
import com.ghy.goods.domain.GoodsStandard;
import com.ghy.goods.service.DeptGoodsCategoryService;
import com.ghy.goods.service.GoodsService;
import com.ghy.goods.service.GoodsStandardService;
import com.ghy.order.domain.*;
import com.ghy.order.service.*;
import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.domain.OrderTimeoutRecord;
import com.ghy.payment.mapper.OrderFineRecordMapper;
import com.ghy.payment.service.FinancialChangeRecordService;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.quartz.pojo.OrderListRequest;
import com.ghy.quartz.pojo.OrderListResponse;
import com.ghy.quartz.pojo.OrderStandard;
import com.ghy.quartz.service.OrderService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.domain.SysDeptConfig;
import com.ghy.system.service.ISysAreaService;
import com.ghy.system.service.ISysDeptConfigService;
import com.ghy.system.service.IWxMsgService;

import com.ghy.worker.domain.Worker;
import com.ghy.worker.domain.WorkerCertification;
import com.ghy.worker.service.IWorkerCertificationService;
import com.ghy.worker.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    private static final Integer ZERO = 0;
    private static final Integer ONE = 1;
    private static final Integer TWO = 2;
   @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;
    /**
     * 需要超时扣款的订单状态
     *
     * @see OrderStatus
     */
    @Value("${order.timeout.status:-4,-3,-2,-1,0,2,1,3}")
    private List<Integer> timeoutOrderStatus;
    private static final List<Integer> orderMasterTimeoutStatus = Arrays.asList(0, 1);

    @Resource
    private ThreadPoolTaskExecutor executor;
    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderFineRecordMapper orderFineRecordMapper;
    @Resource
    private FinancialDetailService financialDetailService;
    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private ISysDeptConfigService sysDeptConfigService;
    @Resource
    private IAfterServiceRecordService afterServiceRecordService;
    @Resource
    private IWxMsgService wxMsgService;
    @Resource
    private WorkerService workerService;
    @Autowired
    private CustomerAddressService customerAddressService;
    @Autowired
    private IOrderCallRecordService orderCallRecordService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private CustomerAddressService addressService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private FinancialChangeRecordService financialChangeRecordService;
    @Resource
    private IWorkerCertificationService workerCertificationService;

    @Override
    public void overTimeOrder(String orderStatus) {
        LocalTime nowT = LocalTime.now();
        //待上门订单通知
        List<OrderDetail> orders = orderDetailService.selectByStatus(timeoutOrderStatus);
        log.info("扫描到{}条未完成的子订单", orders.size());
        for (OrderDetail order : orders) {
            try {
                checkTimeoutDoor(order);
            } catch (Exception e) {
                log.error("子单超时定时任务执行:单号:{},错误原因:{}", order.getCode(), e.getMessage());
                e.printStackTrace();
            }
        }
        // 晚上19点后 - 早上8点前不需要执行定时器
        if (nowT.getHour() < 8 || nowT.getHour() >=20) {
            return;
        }
        List<Integer> list = new ArrayList<>();
        list.add(OrderStatus.FINISH_CHECK.code());
        OrderMaster orderMasterFinishCheck = new OrderMaster();
        orderMasterFinishCheck.setOrderStatus(OrderStatus.FINISH_CHECK.code());
        orderMasterFinishCheck.setWithdrawn(1);
        List<OrderMaster> orderMasterFinish = orderMasterService.selectOrderMasterList(orderMasterFinishCheck);
        for (OrderMaster orderMaster : orderMasterFinish) {
            log.info("满足完成条件的主订单{}", orderMaster);
            List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(orderMaster.getId());
            boolean allDrawCashStatusIs2 = orderDetailList != null
                    && orderDetailList.stream()
                    .allMatch(detail -> detail.getDrawCashStatus() == 2);
            if (allDrawCashStatusIs2) {
                orderMaster.setWithdrawn(2);
                orderMaster.setOrderStatus(OrderStatus.FINISH.code());
                orderMasterService.updateOrderMaster(orderMaster);
            }
        }


        // 查询待接单状态的主单
        List<OrderMaster> orderMasters = orderMasterService.selectByStatus(orderMasterTimeoutStatus);
        log.info("扫描到{}条未完成的主订单", orderMasters.size());
        for (OrderMaster orderMaster : orderMasters) {
            try {
                checkTimeout(orderMaster);
            } catch (Exception e) {
                log.error("主单超时定时任务执行:单号:{},错误原因:{}", orderMaster.getCode(), e.getMessage());
                e.printStackTrace();
            }

        }

        // 查询符合超时的子单
        for (OrderDetail order : orders) {
            try {
                checkTimeout(order);
            } catch (Exception e) {
                log.error("子单超时定时任务执行:单号:{},错误原因:{}", order.getCode(), e.getMessage());
                e.printStackTrace();
            }
        }
    }

    //    @Transactional(rollbackFor = Exception.class)
    public void checkTimeout(OrderMaster order) {
       // log.info("主单超时开始:单号:{}, 内容:{}", order.getCode(), order);
        Date now = new Date();
        // 待接单状态的超时逻辑
        if (ZERO.equals(order.getOrderStatus())) {
            log.info("单号:{},状态:{},创建时间:{},更新时间:{}是否超时：{}", order.getCode(), order.getOrderStatus(), order.getCreateTime(), order.getUpdateTime(),order.getTimeout());
            Date createTime = order.getCreateTime();
            Date overTime30min = getOverTime(createTime, 30 * 60 * 1000);
            Date overTime1h = getOverTime(createTime, 30 * 60 * 1000);
            Integer timenumber=45*60*1000;
            if (order.getOrderType()==1) {
                timenumber=8*60*60*1000;
            }else{
                Goods goods=goodsService.selectById(order.getGoodsId());
                 if (goods.getStoreService()!=null) {
                     timenumber=8*60*60*1000;
                }
            }


            boolean flag;
            if (order.getUpdateTime() != null) {
                flag = getOverTime(order.getUpdateTime(), timenumber).before(now);
            } else {
                flag = getOverTime(createTime, timenumber).before(now);
                log.info("判断时间:{},当前时间:{},结果:{}", getOverTime(createTime, timenumber), now, flag);
            }
            // 是否已经超时
            boolean timeout = ONE.equals(order.getTimeout());
            log.info("是否超时:{}超时时间为{}", timeout,overTime30min);
            if (!timeout) {
                if (overTime30min.before(now)) {
                    // 30min未接单为超时
                    log.info("主订单[{}]超时30分钟", order.getId());
                    orderMasterService.updateTimeout(order.getId(), 1);
                    timeout = true;
                    // 通知一次超时
                    // 通知师傅新订单
                    try {
                        // 推送公众号通知数据。
                        // 消息组装。
                        Map<String, Object> paramsNew = new HashMap<>();
                        // 订单编号
                        paramsNew.put("thing9", "您帐号有1条新订单超时未接");
                        // 名称
                        paramsNew.put("thing10", "请进入【我的订单--新订单】操作处理");
                        CustomerAddress address = customerAddressService.selectByCustomerAddressId(order.getAddressId());
                        paramsNew.put("thing2", address.getName());
                        // 预约时间
                        paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                        // 查师傅信息
                        Worker worker = workerService.selectById(order.getWorkerId());
                        WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
            if (flag && order.getWorkerId() != null) {
                log.info("主订单[{}]超时60分钟", order.getId());
                // 已超时 45min后取消超时状态 清空workerId
                orderMasterService.updateTimeout(order.getId(), 0);
                if (order.getGoodsOrderMasterId()==null) {
                    orderMasterService.removeWorker(order.getId());
                }
//                orderMasterService.up;
                // 移除 updateCreateTime 调用：创建时间不应该被修改，它代表订单最初创建的时间
            }
            return;
        }

        // 未派单状态的超时逻辑
        if (ONE.equals(order.getOrderStatus())) {
            log.info("单号:{},状态:{},创建时间:{},更新时间:{}", order.getCode(), order.getOrderStatus(), order.getCreateTime(), order.getUpdateTime());
            Date updateTime = order.getUpdateTime();
            Date overTime30min = getOverTime(updateTime, 30 * 60 * 1000);
            Date overTime4h = getOverTime(updateTime, 4 * 60 * 60 * 1000);
            Date overTime6h = getOverTime(updateTime, 6 * 60 * 60 * 1000);
            // 是否已经超时
            boolean timeout = ONE.equals(order.getTimeout());
            Integer fineTimes = order.getTimeoutFineTimes();
            if (!timeout) {
                log.info("主订单是否未约未排[{}]派单工id{}", order.getIsCall(), order.getWorkerId());
                if (overTime30min.before(now)) {
                    // 30min未接单为超时
                    log.info("主订单[{}]超时30分钟未排的参数{}", order.getId(), order.getHasDispatchedAll());
                    orderMasterService.updateTimeout(order.getId(), 1);
                    timeout = true;
                    //主单超时未约未排
                    if (order.getIsCall().equals("01") && order.getHasDispatchedAll().equals(0)) {
                        log.info("主订单未约[{}]", order.getIsCall());
                        try {
                            // 推送公众号通知数据。
                            // 消息组装。
                            Map<String, Object> paramsNew = new HashMap<>();
                            // 订单编号
                            paramsNew.put("thing9", "您有1条订单，超时未联系客户");
                            // 名称
                            paramsNew.put("thing10", "进入【我的订单--未约未排】操作处理");
                            CustomerAddress address = customerAddressService.selectByCustomerAddressId(order.getAddressId());
                            paramsNew.put("thing2", address.getName());
                            // 预约时间
                            paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                            // 查师傅信息
                            Worker worker = workerService.selectById(order.getWorkerId());
                            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    //主订单未排
                    else if (order.getHasDispatchedAll().equals(0)) {
                        log.info("主订单未排[{}]", order.getIsCall());
                        try {
                            // 推送公众号通知数据。
                            // 消息组装。
                            Map<String, Object> paramsNew = new HashMap<>();
                            // 订单编号
                            paramsNew.put("thing9", "您有1条订单联系客户后，未排时间");
                            // 名称
                            paramsNew.put("thing10", "进入【我的订单--未约未排--预约时间】");
                            CustomerAddress address = customerAddressService.selectByCustomerAddressId(order.getAddressId());
                            paramsNew.put("thing2", address.getName());
                            // 预约时间
                            paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                            // 查师傅信息
                            Worker worker = workerService.selectById(order.getWorkerId());
                            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }

            if (false) {
                if (overTime4h.before(now) && ZERO.equals(fineTimes)) {
                    log.info("主订单[{}]超时4小时", order.getId());
                    orderMasterService.updateTimeout(order.getId(), 1, 1);
                    // insert 罚金记录
                    OrderTimeoutRecord record = new OrderTimeoutRecord(order.getId(), order.getWorkerId(), order.getDeptId(), order.getOrderStatus());
                    record.setPayMoney(getFineMoney(order));
                    record.setFineStatus(0);
                    orderFineRecordMapper.insert(record);
                    fineTimes = ONE;
                }

                if (overTime6h.before(now) && ONE.equals(fineTimes)) {
                    log.info("主订单[{}]超时6小时", order.getId());
                    orderMasterService.updateTimeout(order.getId(), 1, 2);
                    // insert 罚金记录
                    OrderTimeoutRecord record = new OrderTimeoutRecord(order.getId(), order.getWorkerId(), order.getDeptId(), order.getOrderStatus());
                    record.setPayMoney(getFineMoney(order));
                    record.setFineStatus(0);
                    orderFineRecordMapper.insert(record);
                }
            }
        }
    }

    public boolean isInTimeRange(LocalTime now, int hour, int minute) {
        LocalTime end = LocalTime.of(hour, minute, 59);   // 17:30:59
        if (minute == 0) {
            minute = 60;
            hour = hour - 1;
        }
        LocalTime start = LocalTime.of(hour, minute - 1, 59); // 17:29:59
        return !now.isBefore(start) && !now.isAfter(end);
    }

    /**
     * 判断是否超时
     *
     * @param order 订单信息
     */
//    @Transactional(rollbackFor = Exception.class)
    public void checkTimeout(OrderDetail order) {
       // log.info("子单超时开始:单号:{}, 内容:{}", order.getCode(), order);
        Date now = new Date();
        // 是否超时
        boolean timeout = ONE.equals(order.getTimeout());
        // 超时扣款次数
        Integer times = order.getTimeoutFineTimes();
        // 判断是否是售后订单
        AfterServiceRecord afterParam = new AfterServiceRecord();
        afterParam.setOrderDetailId(order.getId());
        boolean afterTimeout = ONE.equals(order.getAfterTimeout());
        List<AfterServiceRecord> afterServiceRecord = afterServiceRecordService.selectAfterServiceRecordList(afterParam);
        if (CollectionUtil.isNotEmpty(afterServiceRecord) && (afterServiceRecord.get(0).getCustomerFinalCheck() == null || afterServiceRecord.get(0).getCustomerFinalCheck() != 1L)) {
            log.info("售后订单更新时间{},售后订单是否超时{}", afterServiceRecord.get(0).getUpdateTime(), afterTimeout);
            // 查询一下售后单时间
            Date afterTime = getOverTime(afterServiceRecord.get(0).getUpdateTime(), 30 * 60 * 1000);
            //师傅没有操作 则正常进行售后超时计算
            boolean WorkerFeedback = afterServiceRecord.get(0).getWorkerFeedbackResult() == null;
           // log.info("师傅操作{},所有记录{},师傅是否进行操作{}", afterServiceRecord.get(0).getWorkerFeedbackResult(), afterServiceRecord, WorkerFeedback);
            if (afterTime.before(now) && !afterTimeout && WorkerFeedback) {
                log.info("售后订单[{}]超时30分钟", order.getId());
                orderDetailService.updateAfterTimeout(order.getId(), 1, 0);
                // 售后超时通知
                OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.get(0).getOrderDetailId());
                // 通知师傅新订单
                try {
                    Worker worker = workerService.selectById(orderDetail.getWorkerId());
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    // 推送公众号通知数据。
                    // 消息组装。
                    Map<String, Object> paramsNew = new HashMap<>();
                    // 订单编号
                    paramsNew.put("thing9", "您有1条售后/投诉单，超时未处理");
                    // 名称
                    paramsNew.put("thing11", "进入【我的订单--售后中】操作处理");
                    CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                    paramsNew.put("thing10", address.getName());
                    // 预约时间
                    paramsNew.put("time12", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                    WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.AFTER_SALES_TIMEOUT_ORDER, paramsNew);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        if (!timeout) {
            log.info("单号:{},状态:{},创建时间:{},更新时间:{}", order.getCode(), order.getOrderStatus(), order.getCreateTime(), order.getUpdateTime());
            if (order.getOrderStatus().equals(OrderStatus.SERVER.code())) {
                // 服务中状态要按预计上门时间计算4h超时
                // Date overTime = DateUtils.addMilliseconds(order.getUpdateTime(), 4 * 60 * 60 * 1000);
                Date overTime = calculateOverTime(order.getUpdateTime());
                log.info("订单[{}]服务中状态超时4小时 4小时后的时间", overTime);
                if (overTime.before(now)) {
                    log.info("订单[{}]服务中状态超时4小时 扣款", order.getId());
                    OrderTimeoutRecord record = new OrderTimeoutRecord(order.getId(), order.getWorkerId(), order.getDeptId(), order.getOrderStatus());
                    record.setPayMoney(getFineMoney(order));
                    record.setFineStatus(0);
//                    orderFineRecordMapper.insert(record);
                    orderDetailService.updateTimeout(order.getId(), 1, 1);
                    // 超时未上门通知
                    // 通知师傅新订单
                    try {
                        // 推送公众号通知数据。
                        Worker worker = workerService.selectById(order.getWorkerId());
                        // 消息组装。
                        Map<String, Object> paramsNew = new HashMap<>();
                        // 订单编号
                        paramsNew.put("thing9", "您有1条订单，超时未完单");
                        // 名称
                        paramsNew.put("thing10", "进入【我的订单--服务中--打卡及完单】");
                        OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
                        CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                        paramsNew.put("thing2", address.getName());
                        // 预约时间
                        paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                        WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);

                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } else if (timeoutOrderStatus.contains(order.getOrderStatus())) {
                // 其它状态用update_time判断30min超时
                Date overTime = getOverTime(order.getUpdateTime(), 30 * 60 * 1000);
                if (overTime.before(now) && order.getOrderStatus() != OrderStatus.GOING.code()) {
                    log.info("订单[{}]超时30分钟", order.getId());
                    orderDetailService.updateTimeout(order.getId(), 1, 0);
                    // 判断是否约单
                    OrderCallRecord param = new OrderCallRecord();
                    param.setOrderId(order.getId());
                    List<OrderCallRecord> list = orderCallRecordService.selectOrderCallRecordList(param);
                    if (order.getOrderStatus() == OrderStatus.RECEIVE.code()) {
                        try {
                            // 推送公众号通知数据。
                            // 消息组装。
                            Map<String, Object> paramsNew = new HashMap<>();
                            // 订单编号
                            paramsNew.put("thing9", "您帐号有1条新订单超时未接");
                            // 名称
                            paramsNew.put("thing10", "请进入【我的订单--新订单】操作处理");
                            OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
                            CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                            paramsNew.put("thing2", address.getName());
                            // 预约时间
                            paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                            // 查师傅信息
                            Worker worker = workerService.selectById(order.getWorkerId());
                            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 超时预约通知
                    else if (CollectionUtil.isEmpty(list)) {
                        // 通知师傅新订单
                        try {
                            // 推送公众号通知数据。
                            Worker worker = workerService.selectById(order.getWorkerId());
                            // 消息组装。
                            Map<String, Object> paramsNew = new HashMap<>();
                            // 订单编号
                            paramsNew.put("thing9", "您有1条订单，超时未联系客户");
                            // 名称
                            paramsNew.put("thing10", "进入【我的订单--未约未排】操作处理");
                            OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
                            CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                            paramsNew.put("thing2", address.getName());
                            // 预约时间
                            paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);

                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 超时未排单
                    if (CollectionUtil.isNotEmpty(list)) {
                        // 通知师傅新订单
                        try {
                            // 推送公众号通知数据。
                            // 推送公众号通知数据。
                            Worker worker = workerService.selectById(order.getWorkerId());
                            // 消息组装。
                            Map<String, Object> paramsNew = new HashMap<>();
                            // 订单编号
                            paramsNew.put("thing9", "您有1条订单联系客户后，未排时间");
                            // 名称
                            paramsNew.put("thing10", "进入【我的订单--未约未排--预约时间】");
                            OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
                            CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                            paramsNew.put("thing2", address.getName());
                            // 预约时间
                            paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                            // 非自己承接的订单需要通知
                            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);

                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
            return;
        }

        if (times > 1) {
            // 已经扣过2次款了 不再扣款
            log.info("订单[{}]已经扣过2次超时款 不再扣款", order.getId());
        } else if (times == 0) {
            // 没扣过款的
            if (order.getOrderStatus().equals(OrderStatus.SERVER.code())) {
                // 服务中的订单第一次扣款在上面已经扣过了
                return;
            }
            Date overTime = getOverTime(order.getUpdateTime(), 4 * 60 * 60 * 1000);
            if (overTime.before(now)) {
                log.info("订单[{}]超时4h 扣款", order.getId());
                OrderTimeoutRecord record = new OrderTimeoutRecord(order.getId(), order.getWorkerId(), order.getDeptId(), order.getOrderStatus());
                record.setPayMoney(getFineMoney(order));
                record.setFineStatus(0);
//                orderFineRecordMapper.insert(record);
                orderDetailService.updateTimeout(order.getId(), 1, 1);
            }
        } else if (times == 1) {
            // 扣过一次款的
            // 服务中状态取预计上门时间 其它状态取update_time
            Date orderTime = order.getOrderStatus().equals(OrderStatus.SERVER.code()) ? order.getExpectTimeStart() : order.getUpdateTime();
            Date overTime = getOverTime(orderTime, 6 * 60 * 60 * 1000);
            if (overTime.before(now)) {
                log.info("订单[{}]超时6h 再次扣款", order.getId());
                OrderTimeoutRecord record = new OrderTimeoutRecord(order.getId(), order.getWorkerId(), order.getDeptId(), order.getOrderStatus());
                record.setPayMoney(getFineMoney(order));
                record.setFineStatus(0);
//                orderFineRecordMapper.insert(record);
                orderDetailService.updateTimeout(order.getId(), 1, 2);
            }
        }
    }

    /**
     * 计算订单罚金(固定罚金+比例罚金)
     */
    private BigDecimal getFineMoney(OrderDetail order) {
        OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
        FinancialDetail orderFinancial = financialDetailService.selectByOrderDetailId(order.getId());
        SysDeptConfig deptConfig = sysDeptConfigService.selectByDeptId(orderMaster.getDeptId());
        BigDecimal fineMoney = deptConfig.getGoingOutTime();
        // 如果扣款额为null或<0
        if (fineMoney == null || BigDecimal.ZERO.compareTo(fineMoney) > -1) {
            fineMoney = BigDecimal.ZERO;
        }
        BigDecimal timeoutRate = deptConfig.getGoingOutTimeRate();
        // 如果扣款比例 为null 或 <0 或 >1.00
        if (timeoutRate == null || BigDecimal.ZERO.compareTo(timeoutRate) > 0 || BigDecimal.ONE.compareTo(timeoutRate) < 0) {
            return fineMoney;
        }
        BigDecimal rateMoney = orderFinancial.getPayMoney().multiply(timeoutRate);
        return fineMoney.add(rateMoney);
    }

    /**
     * 计算订单罚金(固定罚金+比例罚金)
     */
    private BigDecimal getFineMoney(OrderMaster orderMaster) {
        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMaster.getId());
        SysDeptConfig deptConfig = sysDeptConfigService.selectByDeptId(orderMaster.getDeptId());
        BigDecimal fineMoney = deptConfig.getGoingOutTime();
        // 如果扣款额为null或<0
        if (fineMoney == null || BigDecimal.ZERO.compareTo(fineMoney) > -1) {
            fineMoney = BigDecimal.ZERO;
        }
        BigDecimal timeoutRate = deptConfig.getGoingOutTimeRate();
        // 如果扣款比例 为null 或 <0 或 >1.00
        if (timeoutRate == null || BigDecimal.ZERO.compareTo(timeoutRate) > 0 || BigDecimal.ONE.compareTo(timeoutRate) < 0) {
            return fineMoney;
        }
        BigDecimal rateMoney = financialMaster.getPayMoney().multiply(timeoutRate);
        return fineMoney.add(rateMoney);
    }

    /**
     * 计算超时时间
     *
     * @param orderTime 开始时间
     * @param time      超时时间
     * @return 超时时间
     */
    private Date getOverTime(Date orderTime, int time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(orderTime);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //只在8-20点生效
        if (hour < 8 || hour > 20) {
            // 设置时间为今天的 8 点
            Calendar newCalendar = Calendar.getInstance();
            newCalendar.set(Calendar.HOUR_OF_DAY, 8);
            newCalendar.set(Calendar.MINUTE, 0);
            newCalendar.set(Calendar.SECOND, 0);
            newCalendar.set(Calendar.MILLISECOND, 0);

            // 获取早上 8 点的 Date 对象
            orderTime = newCalendar.getTime();
        }
        return DateUtils.addMilliseconds(orderTime, time);
    }

    /**
     * @param orderTime 单据时间/可能为上门开始时间
     * @param time      超时时间，0.5h/4h/8h等
     * @return 最低限制时间
     * @throws Exception
     */
    private long getOverTimeSec(Date orderTime, long time) throws Exception {
        long overTime = orderTime.getTime();
        // 隔夜需要加上13个小时
        long isNight = 13 * 60 * 60 * 1000;
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Date nowTime = df.parse(df.format(new Date()));
        // 早上8点-晚上19点
        Date amBeginTime = df.parse("08:00");
        Date pmEndTime = df.parse("19:00");
        //设置当前时间
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        //设置开始时间
        Calendar beginTime = Calendar.getInstance();
        beginTime.setTime(amBeginTime);
        //设置结束时间
        Calendar endTime = Calendar.getInstance();
        endTime.setTime(pmEndTime);
        // 符合时间区间
        if (date.after(beginTime) && date.before(endTime)) {
            // 当日单
            if (checkIsTodayOrder(orderTime)) {
                overTime = overTime + time;
            } else {
                overTime = overTime + isNight + time;
            }
        }
        return overTime;
    }

    private Boolean checkIsTodayOrder(Date orderTime) throws Exception {
        // 订单日期
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate = df.parse(df.format(orderTime));
        // 当前日期
        Date now = df.parse(df.format(new Date()));
        if (orderDate.before(now)) {
            return false;
        } else {
            return true;
        }
    }


    @Override
    public void autoFinishOrder() {
        // 子订单自动完单
        // 查询出"待确认"状态的子订单
        List<OrderDetail> orderDetails = orderDetailService.selectByStatus(Collections.singletonList(OrderStatus.FINISH_CHECK.code()));
        long now = System.currentTimeMillis();

//        long day14ago = now - 10000L;
        for (OrderDetail orderDetail : orderDetails) {
            // 获取倒计时时长，如果为null则使用默认值336小时（14天）
            Integer countdownDuration = orderDetail.getShareAccountCountdownDuration();
            int hours = countdownDuration != null ? countdownDuration : 1;
            // 超时时间
            //TODO:修改为后台类目配置时间 

            long day14ago = now - (hours*60 * 60 * 1000L);

            // 筛选符合自动确认的订单
            if (day14ago > orderDetail.getWorkFinishTime().getTime()) {
                log.info("子订单自动完成[id={}, code={}]", orderDetail.getId(), orderDetail.getCode());
                try {
                    // 子订单完单流程(分账与提现)
                    orderDetailService.finish(orderDetail.getId());
                } catch (Exception e) {
                    log.error("子订单自动完成[id={}, code={}]出错", orderDetail.getId(), orderDetail.getCode(), e);
                }
            }
        }

        // 主订单自动完单
        List<OrderMaster> orderMasters = orderMasterService.selectUnfinished();
        for (OrderMaster om : orderMasters) {
            try {
                boolean allAssign = orderMasterService.isAllAssign(om.getId());
                // 如果存在未派单的子订单 就不刷新主单状态
                if (!allAssign) {
                    continue;
                }
                List<OrderDetail> ods = orderDetailService.selectByOrderMasterId(om.getId());
                Set<Integer> statusSet = ods.stream().map(OrderDetail::getOrderStatus).collect(Collectors.toSet());
                // 没有子单,未派单的情况不刷新主单状态
                if (CollectionUtils.isEmpty(statusSet)) {
                    continue;
                }
                boolean allFinish = true;
                for (Integer integer : statusSet) {
                    if (integer < 5) {
                        allFinish = false;
                        break;
                    }
                }
                // 如果已经不存在"已完成"和"已取消"以外的子订单 就把主订单也改为完成
                if (allFinish && om.getWithdrawn() == null) {
                    log.info("主订单自动完成[id={} code={}]", om.getId(), om.getCode());
                    orderMasterService.finish(om.getId());
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public void autoChangeDrawCashStatus() {
    }

    @Override
    public void timeOutOrder() {
        List<Worker> workList = workerService.getWorkList(null);
        for (Worker worker : workList) {
            OrderListRequest orderListRequest = new OrderListRequest();

            orderListRequest.setDeptId(worker.getDeptId());
            orderListRequest.setTimeout(1);
            orderListRequest.setWorkerId(worker.getWorkerId());
            orderListRequest.setIsMonitoredOrder(true);
            orderListRequest.setNeedImgs(false);
            long num = this.appMixOrderCount(orderListRequest);
            log.info("超时巡查超时数量{},超时师傅名称{}", num, worker.getName());
            if (num > 0) {
                try {
                    // 推送公众号通知数据。
                    // 消息组装。
                    Map<String, Object> paramsNew = new HashMap<>();
                    // 订单编号
                    paramsNew.put("thing13", "超时巡查，您或您下级订单超时中");
                    // 名称
                    paramsNew.put("thing7", "请进入【我的订单--超时单】迅速处理");

                    paramsNew.put("character_string23", num);
                    // 预约时间
                    paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));

                    WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.DEFAULT_HANDLE_ORDER, paramsNew);

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }


    }

    @Override
    public void AfterSalesAndShelveOrder() {
        List<Worker> workList = workerService.getWorkList(null);
        for (Worker worker : workList) {
            OrderListRequest orderListRequest = new OrderListRequest();
            OrderDetail orderDetail1 = new OrderDetail();
            orderDetail1.setDeptId(worker.getDeptId());
            orderDetail1.setWorkerId(worker.getWorkerId());
            orderDetail1.setShelveStatus(1);
            long num = orderDetailService.countOrderDetailList(orderDetail1);
            log.info("搁置单巡查超时数量{},超时师傅名称{}", num, worker.getName());
            if (num > 0) {
                try {
                    // 推送公众号通知数据。
                    // 消息组装。
                    Map<String, Object> paramsNew = new HashMap<>();
                    // 订单编号
                    paramsNew.put("thing13", "您有《无法排单》需再次联系客户");
                    // 名称
                    paramsNew.put("thing7", "请进入【我的订单--搁置单】操作处理");
                    paramsNew.put("character_string23", num);
                    // 预约时间
                    paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                    WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.DEFAULT_HANDLE_ORDER, paramsNew);

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setDeptId(worker.getDeptId());
            orderDetail.setOrderStatus(OrderStatus.RECEIVE.code());
            orderDetail.setWorkerId(worker.getWorkerId());
            orderDetail.setShelveStatus(0);
            LocalDateTime tomorrow = LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN);
            orderDetail.setOrderStatus(OrderStatus.GOING.code());
            orderDetail.setExpectTimeStart(Date.from(tomorrow.atZone(ZoneId.systemDefault()).toInstant()));
            tomorrow = LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MAX);
            orderDetail.setExpectTimeEnd(Date.from(tomorrow.atZone(ZoneId.systemDefault()).toInstant()));
            long tomorrowNum = orderDetailService.countOrderDetailList(orderDetail);
            log.info("明日单巡查超时数量{},超时师傅名称{}", tomorrowNum, worker.getName());
            if (tomorrowNum > 0) {
                log.info("订单[{}]明日订单通知", worker.getName());
                try {
                    // 推送公众号通知数据。
                    // 消息组装。
                    Map<String, Object> paramsNew = new HashMap<>();
                    // 订单编号
                    paramsNew.put("thing13", "您有订单，明日待上门/待服务");
                    // 名称
                    paramsNew.put("thing7", "进入【我的订单--明日单】查看准备");

                    paramsNew.put("character_string23", tomorrowNum);
                    // 预约时间
                    paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                    WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TOMORROW_ORDER, paramsNew);

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

            }
            orderListRequest = new OrderListRequest();
            orderListRequest.setDeptId(worker.getDeptId());
            orderListRequest.setWorkerId(worker.getWorkerId());
            orderListRequest.setIsMonitoredOrder(true);
            orderListRequest.setAllSelfAssigned(0);
            orderListRequest.setNeedImgs(false);
            AjaxResult afterListRes = this.appMixAfterList(orderListRequest);
            List<AfterServiceRecord> afterList = (List<AfterServiceRecord>) afterListRes.get("data");
            log.info("售后单巡查超时数量{},超时师傅名称{}", num, worker.getName());
            if (afterList.size() > 0) {
                log.info("订单[{}]售后巡查订单通知", worker.getName());
                try {
                    // 推送公众号通知数据。
                    // 消息组装。
                    Map<String, Object> paramsNew = new HashMap<>();
                    // 订单编号
                    paramsNew.put("thing13", "售后巡查，您或您下级售后单未完成");
                    // 名称
                    paramsNew.put("thing7", "请进入【我的订单--售后中】查看处理");
                    paramsNew.put("character_string23", afterList.size());
                    // 预约时间
                    paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                    WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.DEFAULT_HANDLE_ORDER, paramsNew);

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

    }


    public long appMixOrderCount(OrderListRequest orderListRequest) {
        long count = 0;

        // 校验参数
        Assert.notNull(orderListRequest.getWorkerId(), "师傅id不能为空");

        // 查询子单
        OrderDetail orderDetailReq = new OrderDetail();
        BeanUtils.copyProperties(orderListRequest, orderDetailReq);
        List<OrderDetail> list = orderDetailService.selectOrderDetailList(orderDetailReq);
        long size = list.stream()
                .filter(order -> order.getOrderStatus() != 6) // 先过滤状态不等于6的订单
                .filter(order -> order.getOrderStatus() != 5).count();
        count += size;
        List<OrderMaster> allList = new ArrayList<>();
        List<Long> masterIdSet = new ArrayList<Long>();
        if (orderListRequest.getTimeout() != null && orderListRequest.getTimeout() == 1) {
            // 增加主单下子单有超时的
            OrderMaster param = new OrderMaster();
            param.setWorkerId(orderListRequest.getWorkerId());
            List<OrderMaster> allOrderMaster = orderMasterService.selectOrderMasterList(param);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(allOrderMaster)) {
                OrderDetail countParam = new OrderDetail();
                countParam.setMasterIds(
                        allOrderMaster.stream()
                                .filter(order -> order.getOrderStatus() != 6) // 先过滤状态不等于6的订单
                                .filter(order -> order.getOrderStatus() != 5)
                                .map(OrderMaster::getId)                   // 再提取id
                                .collect(Collectors.toList())
                );
                if (org.apache.commons.collections.CollectionUtils.isEmpty(countParam.getMasterIds())) {
                    return count;
                }
                List<OrderDetail> orderDetails = orderDetailService.selectOrderDetailList(countParam);
                List<OrderDetail> result = orderDetails.stream().filter(s -> s.getTimeout().equals(1)).collect(Collectors.toList());
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(result)) {
                    masterIdSet = result.stream().map(OrderDetail::getOrderMasterId).collect(Collectors.toList());
                }
            }
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(masterIdSet)) {
                OrderMaster timeOutMaster = new OrderMaster();
                timeOutMaster.setOrderMasterIdList(masterIdSet);
                allList.addAll(orderMasterService.selectOrderMasterList(timeOutMaster));
            }
        }
        // 查询主单
        OrderMaster orderMasterReq = new OrderMaster();
        BeanUtils.copyProperties(orderListRequest, orderMasterReq);
        orderMasterReq.setExceptOrderMasterIds(masterIdSet);
        List<OrderMaster> masterList = orderMasterService.selectOrderMasterList(orderMasterReq);
        allList.addAll(masterList);
        // 超时查询需要排除同个师傅的主单子单同时出现
        if (orderListRequest.getTimeout() != null && orderListRequest.getTimeout() == 1) {
            // 需要排除同个师傅的主单子单同时出现
            List<OrderMaster> filteredMasterList = new ArrayList<OrderMaster>();
            for (OrderMaster master : allList) {
                boolean isKeep = false;
                // 查询该主单下所有售后中的子单
                OrderDetail detailAfterListOfMasterQry = new OrderDetail();
                detailAfterListOfMasterQry.setOrderMasterCode(master.getCode());
                List<OrderDetail> tmpDetailListOfMasters = orderDetailService.selectOrderDetailList(detailAfterListOfMasterQry);
                List<OrderListResponse> detailListOfMasters = new ArrayList<>();
                tmpDetailListOfMasters.forEach(model -> {
                    OrderListResponse response = new OrderListResponse();
                    BeanUtils.copyProperties(model, response);
                    detailListOfMasters.add(response);
                });
                for (OrderListResponse detailListOfMaster : detailListOfMasters) {
                    if (!detailListOfMaster.getWorkerId().equals(orderListRequest.getWorkerId())) {
                        isKeep = true;
                        break;
                    }
                }
                if (isKeep || org.apache.commons.collections.CollectionUtils.isEmpty(tmpDetailListOfMasters)) {
                    filteredMasterList.add(master);
                }

            }
            count += filteredMasterList.size();
            if (filteredMasterList.isEmpty()) {
                count += masterList.size();
            }
        } else {
            count += masterList.size();
        }
        return count;
    }

    public AjaxResult appMixAfterList(@RequestBody OrderListRequest orderListRequest) {
        List<OrderListResponse> orderListResponses = new ArrayList<>();

        // 校验参数
        Assert.notNull(orderListRequest.getWorkerId(), "师傅id不能为空");

        // 查询子单
        OrderDetail orderDetailReq = new OrderDetail();
        BeanUtils.copyProperties(orderListRequest, orderDetailReq);
        orderDetailReq.setNeedImgs(orderListRequest.getNeedImgs());
        List<OrderListResponse> detailList = this.getDetailAfterList(orderDetailReq);
        orderListResponses.addAll(detailList);

        // 查询主单
        OrderMaster orderMasterReq = new OrderMaster();
        BeanUtils.copyProperties(orderListRequest, orderMasterReq);
        List<OrderListResponse> masterList = this.getMasterAfterList(orderMasterReq);
        // 需要排除同个师傅的主单子单同时出现
        List<OrderListResponse> filteredMasterList = new ArrayList<OrderListResponse>();
        for (OrderListResponse master : masterList) {
            boolean isKeep = false;
            // 查询该主单下所有售后中的子单
            OrderDetail detailAfterListOfMasterQry = new OrderDetail();
            detailAfterListOfMasterQry.setOrderMasterCode(master.getOrderMasterCode());
            List<OrderListResponse> detailAfterListOfMasters = this.getDetailAfterList(detailAfterListOfMasterQry);
            for (OrderListResponse detailAfterListOfMaster : detailAfterListOfMasters) {
                if (!detailAfterListOfMaster.getWorkerId().equals(orderListRequest.getWorkerId())) {
                    isKeep = true;
                    break;
                }
            }
            long count = detailAfterListOfMasters.stream().filter(x -> (x.getAfterTimeout() != null && x.getAfterTimeout() == 1)).count();
            if (isKeep) {
                if (count > 0) {
                    master.setAfterTimeout(1);
                }
                filteredMasterList.add(master);
            }
        }
        orderListResponses.addAll(filteredMasterList);

        // 根据更新时间倒序排列
        Collections.sort(orderListResponses, new Comparator<OrderListResponse>() {
            @Override
            public int compare(OrderListResponse o1, OrderListResponse o2) {
                return o2.getUpdateTime().compareTo(o1.getUpdateTime());
            }
        });

        return AjaxResult.success(orderListResponses);
    }

    public List<OrderListResponse> getMasterAfterList(OrderMaster orderMaster) {

        // 查所有售后的单
        AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
        afterServiceRecord.setExcludeAfterServiceFinished(Boolean.TRUE);
        List<AfterServiceRecord> afterServiceRecordList = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecord);
        // 踢重后的子单ids
        List<Long> detailIds = afterServiceRecordList.stream().map(AfterServiceRecord::getOrderDetailId).distinct().collect(Collectors.toList());
        StringBuilder orderDetailIds = new StringBuilder();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setCustomerId(orderMaster.getCustomerId());
        orderDetail.setDeptId(orderMaster.getDeptId());
        detailIds.forEach(id -> {
            orderDetailIds.append(id).append(",");
        });
        String ids = orderDetailIds.toString();
        if (StringUtils.isNotEmpty(ids)) {
            orderDetail.setOrderDetailIds(ids.substring(0, ids.length() - 1));
        } else {
            orderDetail.setOrderDetailIds("0");
        }
        // 所有售后的子单
        List<OrderDetail> orderDetailList = orderDetailService.selectOrderDetailList(orderDetail);
        StringBuilder orderMasterIds = new StringBuilder();
        orderDetailList.stream().map(OrderDetail::getOrderMasterId).distinct()
                .collect(Collectors.toList()).forEach(id -> {
                    orderMasterIds.append(id).append(",");
                });
        String orderIds = orderMasterIds.toString();
        if (StringUtils.isNotEmpty(orderIds)) {
            orderMaster.setOrderMasterIds(orderIds.substring(0, orderIds.length() - 1));
        } else {
            orderMaster.setOrderMasterIds("0");
        }

        List<OrderListResponse> orderListResponses = new ArrayList<>();
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        list.forEach(master -> {
            //子单
            List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(master.getId());

            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

            // 师傅信息
            Worker worker = master.getWorkerId() != null ? workerService.selectById(master.getWorkerId()) : null;

            // 消费者信息
//            Customer customer = customerService.selectByCustomerId(master.getCustomerId());

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderMasterId(master.getId());

            // 商品信息
            GoodsStandard goodsStandard = goodsStandardService.selectById(orderStandardList.get(0).getGoodsStandardId());

            Goods goods = goodsService.selectById(goodsStandard.getGoodsId());

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
            BigDecimal totalPayMoney = financialMaster.getPayMoney();
//            BigDecimal totalChangeMoney = new BigDecimal(0);
//            for (OrderDetail detail: detailList) {
//                // 查询子单加价记录
//                FinancialChangeRecord changeRecordQry = new FinancialChangeRecord();
//                changeRecordQry.setOrderDetailId(detail.getId());
//                List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService.selectFinancialChangeRecordList(changeRecordQry);
//                if (CollectionUtils.isNotEmpty(financialChangeRecords)) {
//                    totalChangeMoney = totalChangeMoney.add(financialChangeRecords.get(0).getChangeMoney());
//                }
//            }
//            totalPayMoney = totalPayMoney.add(totalChangeMoney);

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());
            SysArea sysArea;
            if (customerAddress.getStreetId() != null) {
                sysArea = sysAreaService.selectById(customerAddress.getStreetId());
            } else {
                sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            }
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            // 查询售后记录
            List<AfterServiceRecord> afterServiceRecords = new ArrayList<>();
            List<OrderDetail> detailOrderList = orderDetailService.selectByOrderMasterId(master.getId());
            detailOrderList.stream().forEach(detail -> {
                AfterServiceRecord afterServiceRecordQry = new AfterServiceRecord();
                afterServiceRecordQry.setOrderDetailId(detail.getId());
                List<AfterServiceRecord> records = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecordQry);
                afterServiceRecords.addAll(records);
            });

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                standardList.add(orderStandard);
            }

            // 编辑返回属性
            orderListResponse.setGoodsBrand(master.getGoodsBrand());
            orderListResponse.setGoodsSpecification(master.getGoodsSpecification());
            orderListResponse.setOrderMasterId(master.getId());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialMaster.getDiscountMoney());
            orderListResponse.setTotalMoney(financialMaster.getTotalMoney());
            orderListResponse.setPayMoney(totalPayMoney);
//            orderListResponse.setChangeMoney(totalChangeMoney);
            orderListResponse.setWorkerName(worker == null ? "" : worker.getName());
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(StringUtils.isNotEmpty(master.getName()) ? master.getName() : customerAddress.getName());
            orderListResponse.setCustomerPhone(StringUtils.isNotEmpty(master.getPhone()) ? master.getPhone() : customerAddress.getPhone());
            orderListResponse.setServerTime(master.getRevTime());
            orderListResponse.setExpectTimeStart(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(master.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(master.getExpectTimeEnd());
            orderListResponse.setOrderStatus(master.getOrderStatus());
            orderListResponse.setPayStatus(master.getPayStatus());
            orderListResponse.setPayType(master.getPayType());
            orderListResponse.setOrderMasterCode(master.getCode());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(master.getRemark());
            orderListResponse.setTimeout(master.getTimeout());
            orderListResponse.setTimeoutFineTimes(master.getTimeoutFineTimes());
            orderListResponse.setAfterServiceRecordList(afterServiceRecords);
            orderListResponse.setCreateTime(master.getCreateTime());
            orderListResponse.setUpdateTime(master.getUpdateTime());
            orderListResponses.add(orderListResponse);

        });
        return orderListResponses;
    }

    public List<OrderListResponse> getDetailAfterList(OrderDetail orderDetail) {
        AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
        afterServiceRecord.setExcludeAfterServiceFinished(Boolean.TRUE);
        afterServiceRecord.setNeedImgs(orderDetail.getNeedImgs());
        List<AfterServiceRecord> afterServiceRecordList = afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecord);
        Map<Long, List<AfterServiceRecord>> detailRecordMap = afterServiceRecordList.stream().collect(Collectors.groupingBy(record -> record.getOrderDetailId()));
        // 踢重后的子单ids
        List<Long> detailIds = afterServiceRecordList.stream().map(AfterServiceRecord::getOrderDetailId).distinct().collect(Collectors.toList());
        StringBuilder orderDetailIds = new StringBuilder();
        detailIds.forEach(id -> {
            orderDetailIds.append(id).append(",");
        });
        String ids = orderDetailIds.toString();
        if (StringUtils.isNotEmpty(ids)) {
            orderDetail.setOrderDetailIds(ids.substring(0, ids.length() - 1));
        } else {
            orderDetail.setOrderDetailIds("0");
        }
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.selectOrderDetailList(orderDetail);
        list.forEach(detail -> {

            // 主单信息
            OrderMaster orderMaster = orderMasterService.selectById(detail.getOrderMasterId());
            // 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();

            // 师傅信息
            Worker worker = workerService.selectById(detail.getWorkerId());
            WorkerCertification workerRealInfo = null;
            String workerName = "";
            if (worker != null) {
                // 师傅实名信息
                workerRealInfo = workerCertificationService.selectByWorkerId(orderMaster.getWorkerId());
                workerName = workerRealInfo == null ? worker.getName() : workerRealInfo.getSurname() + workerRealInfo.getName();
            }

            // 消费者信息
//            Customer customer = customerService.selectByCustomerId(detail.getCustomerId());

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderDetailId(detail.getId());

            // 商品信息
            GoodsStandard goodsStandard = goodsStandardService.selectById(orderStandardList.get(0).getGoodsStandardId());

            Goods goods = goodsService.selectById(goodsStandard.getGoodsId());

            // 财务信息
            FinancialDetail financialDetail = financialDetailService.selectByOrderDetailId(detail.getId());
            BigDecimal detailPayMoney = financialDetail.getPayMoney();

            // 查询子单加价记录
            FinancialChangeRecord financialChangeRecord = financialChangeRecordService.selectNotPayRecordByDetailId(detail.getId());
            BigDecimal changeMoney = financialChangeRecord == null ? BigDecimal.ZERO : financialChangeRecord.getChangeMoney();

            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(orderMaster.getAddressId());
            SysArea sysArea;
            if (customerAddress.getStreetId() != null) {
                sysArea = sysAreaService.selectById(customerAddress.getStreetId());
            } else {
                sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            }
            String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                orderStandard.setServerNum(orderGoods.getServerGoodsNum());
                orderStandard.setFinishTime(orderGoods.getFinishTime());
                orderStandard.setWaitServerNum(orderGoods.getGoodsNum() - orderGoods.getServerGoodsNum());
                standardList.add(orderStandard);
            }

            if (this.checkIsOnlyServer(orderMaster.getId(), detail.getWorkerId())) {
                FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(detail.getOrderMasterId());
                BigDecimal workerFee = financialMaster.getPayMoney();
                List<FinancialDetail> financialDetailList = financialDetailService.selectByFinancialMasterId(financialMaster.getId());
                for (FinancialDetail param : financialDetailList) {
                    if (!detail.getWorkerId().equals(param.getPayeeId())) {
                        workerFee = workerFee.subtract(param.getPayMoney());
                    }
                }
                orderListResponse.setPayMoney(workerFee);
                orderListResponse.setIsOnlyServ(Boolean.TRUE);
            } else {
                orderListResponse.setPayMoney(detailPayMoney);
                orderListResponse.setIsOnlyServ(Boolean.FALSE);
            }


            // 编辑返回属性
            orderListResponse.setGoodsBrand(orderMaster.getGoodsBrand());
            orderListResponse.setGoodsSpecification(orderMaster.getGoodsSpecification());
            orderListResponse.setOrderDetailId(detail.getId());
            orderListResponse.setOrderDetailCode(detail.getCode());
            orderListResponse.setOrderMasterId(detail.getOrderMasterId());
            orderListResponse.setOrderMasterCode(detail.getOrderMasterCode());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialDetail.getDiscountMoney());
            orderListResponse.setTotalMoney(financialDetail.getTotalMoney());
            orderListResponse.setWorkerId(detail.getWorkerId());
            orderListResponse.setWorkerName(workerName);
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(StringUtils.isNotEmpty(orderMaster.getName()) ? orderMaster.getName() : customerAddress.getName());
            orderListResponse.setCustomerPhone(StringUtils.isNotEmpty(orderMaster.getPhone()) ? orderMaster.getPhone() : customerAddress.getPhone());
            orderListResponse.setOrderStatus(detail.getOrderStatus());
            orderListResponse.setPayStatus(orderMaster.getPayStatus());
            orderListResponse.setPayType(orderMaster.getPayType());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setServerTime(detail.getRevTime());
            orderListResponse.setExpectTimeStart(detail.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(detail.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(detail.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(detail.getExpectTimeEnd());
            orderListResponse.setWorkBeginTime(detail.getWorkBeginTime());
            orderListResponse.setWorkFinishTime(detail.getWorkFinishTime());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            orderListResponse.setOrderType(detail.getOrderType());
            orderListResponse.setTimeout(detail.getTimeout());
            orderListResponse.setAfterTimeout(detail.getAfterTimeout());
            orderListResponse.setAfterServiceRecordList(detailRecordMap.get(detail.getId()));
            orderListResponse.setChangeMoney(changeMoney);
            orderListResponse.setDrawCashStatus(detail.getDrawCashStatus());
            orderListResponse.setDrawCashTime(detail.getDrawCashTime());
            orderListResponse.setCreateTime(detail.getCreateTime());
            orderListResponse.setUpdateTime(detail.getUpdateTime());
            orderListResponses.add(orderListResponse);
        });
        return orderListResponses;
    }

    private boolean checkIsOnlyServer(Long orderMasterId, Long workId) {
        // 找出原单的数量
        List<OrderGoods> orderGoodsList = orderGoodsService.selectByOrderMasterId(orderMasterId);
        // 找出原单关联的细单的商品数量
        List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(orderMasterId);
        for (OrderDetail detail : orderDetailList) {
            // 非一个师傅接单
            if (!workId.equals(detail.getWorkerId())) {
                return false;
            }
            // 子单数量
            List<OrderGoods> orderDetailGoodsList = orderGoodsService.selectByOrderDetailId(detail.getId());
            // 计算剩余未分配的商品数量
            for (OrderGoods detailGoods : orderDetailGoodsList) {
                for (OrderGoods masterGoods : orderGoodsList) {
                    if (Objects.equals(masterGoods.getGoodsStandardId(), detailGoods.getGoodsStandardId())) {
                        masterGoods.setGoodsNum(masterGoods.getGoodsNum() - detailGoods.getGoodsNum());
                    }
                }
            }
        }
        // 有单派完.
        for (OrderGoods orderGoods : orderGoodsList) {
            if (orderGoods.getGoodsNum() > 0) {
                return false;
            }
        }
        return true;
    }

    /*判断超时4小时的时间 如果超过晚上八点则剩余的时间从第二天早上开始计时*/
    public static Date calculateOverTime(Date updateTime) {
        // 1. 增加4小时
        LocalDateTime overTime = updateTime.toInstant()
                .atZone(java.time.ZoneId.systemDefault())
                .toLocalDateTime()
                .plusHours(4);

        // 2. 判断是否超过20:00
        LocalTime cutoff = LocalTime.of(20, 0);
        LocalTime timePart = overTime.toLocalTime();

        if (timePart.isAfter(cutoff)) {
            // 3. 计算超时部分时长
            Duration excess = Duration.between(cutoff, timePart);

            // 4. 重置到次日8:00并加上超时时长
            LocalDateTime nextDay = overTime.toLocalDate().plusDays(1).atStartOfDay();
            LocalDateTime adjustedTime = LocalDateTime.of(LocalDate.from(nextDay), LocalTime.of(8, 0)).plus(excess);

            return Date.from(adjustedTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
        }
        return Date.from(overTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
    }

    //单独处理待上门通知
    public void checkTimeoutDoor(OrderDetail order) {
        //log.info("子单超时开始:单号:{}, 内容:{}", order.getCode(), order);
        Date now = new Date();
        // 是否超时
        boolean timeout = ONE.equals(order.getTimeout());
        // 超时扣款次数
        Integer times = order.getTimeoutFineTimes();
        // 判断是否是售后订单
        AfterServiceRecord afterParam = new AfterServiceRecord();
        afterParam.setOrderDetailId(order.getId());
        if (!timeout) {
            log.info("单号:{},状态:{},创建时间:{},更新时间:{}", order.getCode(), order.getOrderStatus(), order.getCreateTime(), order.getUpdateTime());
            // 待上门超时
            if (order.getOrderStatus().equals(OrderStatus.GOING.code())) {
                // 服务中状态要按预计上门时间计算4h超时
                Date overTime = DateUtils.addMilliseconds(order.getExpectTimeStart(), 30 * 60 * 1000);

                Date oneHourTime = DateUtils.addMilliseconds(order.getExpectTimeStart(), -60 * 60 * 1000);
                log.info("待上门订单开始前一个小时 订单号：[{}]时间：{} 当前时间 {} 是否为同一时间小时{} 分钟{}", order.getId(), oneHourTime, now, oneHourTime.getHours(), oneHourTime.getMinutes());
                log.info("待上门订单[{}]服务中预计超时时间{},是否已经超时{}", order.getId(), overTime, overTime.before(now));
                LocalTime currentTime = LocalTime.now(); // 当前系统时间
                if (overTime.before(now)) {
                    log.info("订单[{}]待上门状态超时30分钟", order.getId());
                    OrderTimeoutRecord record = new OrderTimeoutRecord(order.getId(), order.getWorkerId(), order.getDeptId(), order.getOrderStatus());
                    record.setPayMoney(getFineMoney(order));
                    record.setFineStatus(0);
//                    orderFineRecordMapper.insert(record);
                    orderDetailService.updateTimeout(order.getId(), 1, 1);
                    // 超时未上门通知
                    // 通知师傅新订单
                    try {
                        // 推送公众号通知数据。
                        Worker worker = workerService.selectById(order.getWorkerId());
                        OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
                        // 消息组装。
                        Map<String, Object> paramsNew = new HashMap<>();
                        // 订单编号
                        paramsNew.put("thing9", "您有1条订单超时未上门/未服务");
                        // 名称
                        paramsNew.put("thing10", "进入【我的订单--待上门】处理");
                        CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                        paramsNew.put("thing2", address.getName());
                        // 预约时间
                        paramsNew.put("time8", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                        WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.TIMEOUT_ORDER, paramsNew);

                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
                if (isInTimeRange(currentTime, oneHourTime.getHours(), oneHourTime.getMinutes()) && isSameYearMonthDay(now, oneHourTime)) {
                    log.info("订单[{}]约一小时上门服务", order.getId());
                    try {
                        // 推送公众号通知数据。
                        Worker worker = workerService.selectById(order.getWorkerId());
                        OrderMaster orderMaster = orderMasterService.selectById(order.getOrderMasterId());
                        // 消息组装。
                        Map<String, Object> paramsNew = new HashMap<>();
                        // 订单编号
                        paramsNew.put("thing13", "您有订单约1小时后上门/服务");
                        // 名称
                        paramsNew.put("thing7", "进入【我的订单--待上门】查看和准备");
                        CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                        paramsNew.put("thing9", address.getName());
                        // 预约时间
                        paramsNew.put("time27", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                        WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.ONEHOUR_ORDER, paramsNew);

                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }

            }
            return;
        }

    }

    public static boolean isSameYearMonthDay(Date date1, Date date2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化为本地时间的字符串（忽略时间部分）
        String dateStr1 = sdf.format(date1);
        String dateStr2 = sdf.format(date2);
        return dateStr1.equals(dateStr2);
    }

    @Override
    public void orderServerToFinishCheck() {
        List<OrderDetail> orderDetails = orderDetailService.selectByStatus(Collections.singletonList(OrderStatus.SERVER.code()));
        Date now = new Date();

        for (OrderDetail orderDetail : orderDetails) {
            try {
                OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
               
                if (orderMaster == null) {
                    continue;
                }
                AfterServiceRecord unfinished = afterServiceRecordService.unfinished(orderDetail.getId());
                if (unfinished != null) {
                    log.debug("子订单[id={}, code={}]存在售后记录，跳过自动完成", orderDetail.getId(), orderDetail.getCode());
                    continue;
                }
                Date targetTime;
                String logType = "已设置";

                // 优先使用已设置的确认截止时间
                if (orderDetail.getConfirmStartTime() != null) {
                    targetTime = orderDetail.getConfirmStartTime();
                    log.debug("订单[{}]使用已设置的确认截止时间：{}", orderDetail.getCode(),
                            com.ghy.common.utils.DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", targetTime));
                } else {
                    // 兼容旧数据，重新计算确认截止时间
                    Date updateTime = orderDetail.getUpdateTime();
                    if (updateTime == null) {
                        log.warn("订单[{}]更新时间为空，跳过处理", orderDetail.getCode());
                        continue;
                    }

                    long waitTimeMillis;
                    
                    // 获取发货类型并检查是否为null
                    Integer deliveryType = orderMaster.getDeliveryType();
                    if (deliveryType == null) {
                        log.warn("订单[{}]发货类型为null，跳过处理", orderDetail.getCode());
                        continue;
                    }

                    // 根据发货类型判断等待时间
                    if (deliveryType == 2 || deliveryType == 3) {
                        // 送货上门或自提：8小时
                        waitTimeMillis = 8 * 60 * 60 * 1000L; // 8小时的毫秒数
                        logType = deliveryType == 2 ? "送货上门" : "自提";
                    } else if (deliveryType == 1) {
                        // 发快递/物流：4天
                        waitTimeMillis = 4 * 24 * 60 * 60 * 1000L; // 4天的毫秒数
                        logType = "发快递/物流";
                    } else {
                        // 未知发货类型，跳过处理
                        log.warn("订单[{}]发货类型未知[{}]，跳过处理", orderDetail.getCode(), deliveryType);
                        continue;
                    }

                    // 计算确认截止时间
                    targetTime = new Date(updateTime.getTime() + waitTimeMillis);

                    // 回写到数据库，避免下次重复计算
                    OrderDetail updateOrderDetail = new OrderDetail();
                    updateOrderDetail.setId(orderDetail.getId());
                    updateOrderDetail.setConfirmStartTime(targetTime);
                    orderDetailService.updateOrderDetail(updateOrderDetail);

                    log.info("订单[{}]补充设置确认截止时间，发货类型[{}]，截止时间：{}",
                            orderDetail.getCode(), logType,
                            com.ghy.common.utils.DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", targetTime));
                }

                // 检查是否到达目标时间
                if (now.after(targetTime) && orderMaster.getPayStatus() == 1) {
                    // 检查是否存在对应的服务订单，如果存在则必须也是确认中状态
                    if (orderMaster.getHasServiceOrder() != null && orderMaster.getHasServiceOrder() == 1) {
                        OrderMaster serviceOrderMaster = orderMasterService.selectByGoodsOrderMasterId(orderMaster.getId());
                        if (serviceOrderMaster != null) {
                            if (serviceOrderMaster.getOrderStatus() != OrderStatus.FINISH_CHECK.code()) {
                                log.info("订单[{}]对应的服务订单[{}]尚未进入确认中状态，跳过商品订单状态更新", 
                                        orderDetail.getCode(), serviceOrderMaster.getCode());
                                continue;
                            } else {
                                log.info("订单[{}]对应的服务订单[{}]已进入确认中状态，可以更新商品订单状态", 
                                        orderDetail.getCode(), serviceOrderMaster.getCode());
                            }
                        }
                    }
                    
                    log.info("订单[{}]确认截止时间已到，开始转为确认中状态", orderDetail.getCode());
                    Date workFinishTime = new Date();
                    orderDetail.setWorkFinishTime(workFinishTime);
                    
                    // 查询订单商品对应的类目倒计时小时数，计算分账倒计时结束时间
                    try {
                        List<OrderGoods> orderGoodsList = orderGoodsService.selectByOrderDetailId(orderDetail.getId());
                        if (orderGoodsList.size()>0) {
                            // 取第一个商品的规格ID查询类目信息
                            OrderGoods firstOrderGoods = orderGoodsList.get(0);
                            GoodsStandard goodsStandard = goodsStandardService.selectById(firstOrderGoods.getGoodsStandardId());
                            if (goodsStandard != null && goodsStandard.getDeptGoodsCategoryId() != null) {
                                // 递归查找类目的倒计时小时数
                                Integer countdownHours = deptGoodsCategoryService.findCountdownHoursRecursively(goodsStandard.getDeptGoodsCategoryId());
                                if (countdownHours != null) {
                                    // 计算分账倒计时结束时间：workFinishTime + 倒计时小时数
                                    long countdownMillis = countdownHours * 60 * 60 * 1000L;
                                    Date shareAccountCountdownEndTime = new Date(workFinishTime.getTime() + countdownMillis);
                                    
                                    orderDetail.setShareAccountCountdownEndTime(shareAccountCountdownEndTime);
                                    orderDetail.setShareAccountCountdownDuration(countdownHours);
                                    
                                    log.info("订单[{}]设置分账倒计时：完单时间={}, 倒计时小时数={}, 分账倒计时结束时间={}", 
                                            orderDetail.getCode(), workFinishTime, countdownHours, shareAccountCountdownEndTime);
                                } else {
                                    log.warn("订单[{}]未找到类目倒计时小时数配置，跳过分账倒计时设置", orderDetail.getCode());
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("设置分账倒计时失败，订单ID：{}", orderDetail.getId(), e);
                    }
                    
                    orderDetailService.updateOrderDetail(orderDetail);
                    // 更新订单状态为确认中
                    int result = orderDetailService.updateStatus(orderDetail.getId(), OrderStatus.FINISH_CHECK.code());

                    if (result > 0) {
                        log.info("订单[{}]状态已成功更新为确认中", orderDetail.getCode());
                    } else {
                        log.error("订单[{}]状态更新失败", orderDetail.getCode());
                    }
                } else {
                    log.debug("订单[{}]尚未到达确认截止时间，截止时间:{}",
                            orderDetail.getCode(),
                            com.ghy.common.utils.DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", targetTime));
                }

            } catch (Exception e) {
                log.error("处理订单[{}]自动转确认中状态时发生异常", orderDetail.getCode(), e);
            }
        }
    }
}
