package com.ghy.web.controller.order;

import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.domain.entity.SysUser;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.enums.*;
import com.ghy.common.utils.WechatMsgUtils;
import com.ghy.customer.domain.Customer;
import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.customer.service.CustomerService;
import com.ghy.goods.domain.*;
import com.ghy.goods.request.AppGoodsRequest;
import com.ghy.goods.service.*;
import com.ghy.order.domain.*;
import com.ghy.order.request.AppOrderAssignRequest;
import com.ghy.order.request.AppOrderRequest;
import com.ghy.order.request.SysOrderAssignRequest;
import com.ghy.order.request.SysOrderGoodsStandards;
import com.ghy.order.request.LogisticsQueryRequest;
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.service.FinancialChangeRecordService;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.payment.service.OrderFineRecordService;
import com.ghy.shop.domain.Shop;
import com.ghy.shop.service.ShopService;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import com.ghy.system.service.IWxMsgService;
import com.ghy.web.pojo.vo.*;
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 com.huifu.adapay.core.exception.BaseAdaPayException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author clunt
 *         下单接口
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerAddressService customerAddressService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;
    @Resource
    private WorkerService workerService;
    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private FinancialDetailService financialDetailService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private CustomerAddressService addressService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private FinancialChangeRecordService financialChangeRecordService;
    @Resource
    private IWorkerCertificationService workerCertificationService;
    @Resource
    private IAfterServiceRecordService afterServiceRecordService;
    @Resource
    private OrderBehaviorService orderBehaviorService;
    @Resource
    private IWxMsgService wxMsgService;
    @Resource
    private IOrderCallRecordService orderCallRecordService;
    @Resource
    private GoodsImgsService goodsImgsService;

    @Resource
    private GoodsCategoryService goodsCategoryService;

    @Resource
    private IInsuranceManagerService insuranceManagerService;

    @Resource
    private LogisticsService logisticsService;

    @Resource
    private ShopService shopService;

    @Resource
    private OrderFineRecordService orderFineRecordService;

    @GetMapping("/imgs")
    public String orderImgs(Long orderId, ModelMap mmap) {
        mmap.put("orderId", orderId);
        return "order/imgs";
    }

    @PostMapping("/imgs/list")
    @ResponseBody
    public TableDataInfo list(GoodsImgs goodsImgs) {
        List<OrderDetail> details = orderDetailService.selectByOrderMasterId(Long.valueOf(goodsImgs.getRemark()));
        List<Long> ids = details.stream().map(OrderDetail::getId).collect(Collectors.toList());
        goodsImgs.setRemark(null);
        goodsImgs.setRemarks(ids);
        goodsImgs.setImgType(ImgType.FINISH_IMG.getId());
        List<GoodsImgs> list = goodsImgsService.qryGoodsImgs(goodsImgs);
        return getDataTable(list);
    }

    @GetMapping("/popup/editServingInfo")
    public String record(Long orderId, String pageCode, ModelMap mmap) {
        mmap.put("orderId", orderId);
        mmap.put("pageCode", pageCode);
        return "order/popup/editServingInfo";
    }

    /**
     * 可派单商品数量
     */
    @PostMapping("/can/assign")
    @ResponseBody
    public AjaxResult canAssign(@RequestBody AppOrderAssignRequest request) {
        try {
            // 找出原单的数量
            List<OrderGoods> orderGoodsList = orderGoodsService.selectByOrderMasterId(request.getOrderMasterId());
            
            if (request.getGenerateServiceOrder()!=null&&request.getGenerateServiceOrder() == 1) {
                return AjaxResult.success(orderGoodsList);
            }
            // 找出原单关联的细单的商品数量
            List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(request.getOrderMasterId());
            for (OrderDetail orderDetail : orderDetailList) {
                // 子单数量
                List<OrderGoods> orderDetailGoodsList = orderGoodsService.selectByOrderDetailId(orderDetail.getId());

                // 计算剩余未分配的商品数量
                for (OrderGoods detailGoods : orderDetailGoodsList) {
                    for (OrderGoods masterGoods : orderGoodsList) {
                        if (Objects.equals(masterGoods.getGoodsStandardId(), detailGoods.getGoodsStandardId())) {
                            masterGoods.setGoodsNum(masterGoods.getGoodsNum() - detailGoods.getGoodsNum());
                        }
                    }
                }
            }
            // 计算新单的数量
            return AjaxResult.success(orderGoodsList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("派单失败:" + ExceptionUtils.getMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 后台批量下单
     */
    @PostMapping("/sys/order")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult sysOrder(@RequestBody SysOrderAssignRequest request) {

        // 判断传递价格是否有小数
        if (new BigDecimal(request.getPrice().intValue()).compareTo(request.getPrice()) != 0) {
            return AjaxResult.error("后台发单金额不能含有小数!");
        }

        // 判断是否有客户
        SysUser sysUser = getSysUser();
        Long deptId = sysUser.getDept().getDeptId();
        String loginName = sysUser.getLoginName();
        Customer customer = customerService.selectByAccount("sys_" + loginName);
        if (customer == null) {
            customer = new Customer();
            customer.setAccount("sys_" + loginName);
            customer.setName("平台用户_" + loginName);
            customerService.insertCustomer(customer);
        }

        // 判断是否有客户地址
        if (request.getProvinceId() == null || request.getCityId() == null || request.getDistrictId() == null
                || StringUtils.isBlank(request.getFullAddress())) {
            return AjaxResult.error("请填写地址");
        }
        CustomerAddress customerAddress = new CustomerAddress();
        customerAddress.setCustomerId(customer.getCustomerId());
        customerAddress.setProvinceId(request.getProvinceId());
        customerAddress.setCityId(request.getCityId());
        customerAddress.setCountryId(request.getDistrictId());
        customerAddress.setAddress(request.getFullAddress());
        customerAddress.setStreetId(request.getStreetId());
        customerAddress.setIsDefault(0);
        customerAddress.setPhone(request.getCustomerPhone());
        customerAddress.setName(request.getCustomerName());
        customerAddressService.insertCustomerAddress(customerAddress);

        // 订单总价 不能小于0
        BigDecimal orderPrice = request.getPrice().max(BigDecimal.ZERO);
        Integer totalNum = 0;
        for (SysOrderGoodsStandards model : request.getOrderGoodsStandards()) {
            totalNum = totalNum + model.getGoodsStandardNum();
        }
        // 商品单价
        BigDecimal goodsPrice = orderPrice.divide(BigDecimal.valueOf(totalNum), RoundingMode.HALF_UP);

        // 增加商品
        Goods goods = new Goods();
        goods.setDeptId(deptId);
        // 后续改成 三级类目+品牌
        goods.setGoodsName(request.getGoodsBrand());
        goods.setGoodsImgUrl(request.getImageUrl());
        goods.setGoodsVideoUrl(request.getVideoUrl());
        goods.setDeptGoodsCategoryId(request.getCategoryId3());
        goods.setStatus(1);
        goods.setRemark(request.getRemark());
        goodsService.insertGoods(goods);

        List<GoodsStandard> goodsStandards = new ArrayList<>();
        // TODO 生成规格 -- orderGoods完成后未会写规格id
        request.getOrderGoodsStandards().forEach(list -> {
            DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(list.getDeptCategoryId());
            GoodsStandard standard = new GoodsStandard();
            standard.setGoodsStandardName(deptGoodsCategory.getGoodsCategoryName());
            standard.setDeptGoodsCategoryId(deptGoodsCategory.getDeptGoodsCategoryId());
            standard.setGoodsCategoryName(deptGoodsCategory.getGoodsCategoryName());
            standard.setGoodsPrice(goodsPrice);
            standard.setGoodsId(goods.getGoodsId());
            standard.setExtMoney(BigDecimal.ZERO);
            standard.setGoodsNum(list.getGoodsStandardNum());
            standard.setSaleNum(0);
            goodsStandardService.insertGoodsStandard(standard);
            goodsStandards.add(standard);
        });

        // 生成主单
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setDeptId(deptId);
        orderMaster.setCode(orderMasterService.createOrderCode());
        orderMaster.setOrderType(0);
        orderMaster.setOrderStatus(OrderStatus.RECEIVE.code());
        orderMaster.setAddressId(customerAddress.getCustomerAddressId());
        orderMaster.setPayStatus(PayStatus.WAIT_PAY.getCode());
        orderMaster.setCreateTime(new Date());
        orderMaster.setCustomerId(customer.getCustomerId());
        orderMaster.setGoodsId(goods.getGoodsId());
        orderMaster.setPayType(0);
        orderMaster.setOrderMode(request.getOrderMode());
        orderMaster.setPayMode(request.getPayMode());
        orderMaster.setGoodsBrand(request.getGoodsBrand());
        orderMaster.setGoodsSpecification(request.getGoodsSpecification());
        orderMaster.setConsultMode(request.getConsultMode());
        orderMaster.setRemark(request.getRemark());
        orderMaster.setOrderImages(request.getOrderImages());

        orderMaster.setProvinceId(request.getProvinceId());
        orderMaster.setCityId(request.getCityId());
        orderMaster.setCountryId(request.getDistrictId());
        orderMaster.setAddress(request.getFullAddress());
        orderMaster.setPhone(customerAddress.getPhone());
        orderMaster.setName(customerAddress.getName());
        orderMaster.setProvinceName(customerAddress.getProvinceName());
        orderMaster.setCityName(customerAddress.getCityName());
        orderMaster.setCountryName(customerAddress.getCountryName());
        orderMaster.setStreetId(request.getStreetId());
        orderMaster.setStreetName(customerAddress.getStreetName());

        if ("01".equalsIgnoreCase(orderMaster.getConsultMode())) {
            orderMaster.setOrderMode("02");
            orderMaster.setPayMode("01");
        }
        // 存在登陆用户的情况下
        if (getSysUser() != null) {
            orderMaster.setCreateBy(getSysUser().getUserId().toString());
        }
        // 服务时间
        String[] split = request.getServTime().split("-");
        try {
            orderMaster.setExpectTimeStart(
                    DateUtils.parseDate(request.getServDate() + " " + split[0], "yyyy-MM-dd hh:mm"));
            orderMaster
                    .setExpectTimeEnd(DateUtils.parseDate(request.getServDate() + " " + split[1], "yyyy-MM-dd hh:mm"));
        } catch (Exception e) {

        }
        orderMasterService.insertOrderMaster(orderMaster);
        Assert.notNull(orderMaster.getId(), "OrderMaster.id is null!");

        // 生成财务主单
        FinancialMaster financialMaster = new FinancialMaster(financialMasterService.createCode(), deptId,
                orderMaster.getId(), orderMaster.getCode(), request.getPrice(), BigDecimal.ZERO, request.getPrice());
        financialMaster.setServerMoney(financialMaster.getTotalMoney());
        financialMasterService.insertFinancialMaster(financialMaster);
        Assert.notNull(financialMaster.getId(), "FinancialMaster.id is null!");

        // 生成提成类子财务单
        createDeptFinancialDetail(goodsStandards.get(0), deptId, financialMaster);

        // 生成商品订单
        goodsStandards.forEach(goodsStandard -> {
            OrderGoods orderGoods = new OrderGoods(orderMaster.getId(), goodsStandard.getGoodsStandardId(),
                    goodsStandard.getGoodsStandardName(), goodsStandard.getGoodsNum(), 0);
            orderGoodsService.insertOrderGoods(orderGoods);
        });

        // 推送公众号通知数据。
        try {
            Worker assignWorker = workerService.selectById(orderMaster.getWorkerId());
            // 消息组装。
            Map<String, Object> params = new HashMap<>();
            // 订单编号
            params.put("character_string6", orderMaster.getCode());
            // 名称
            params.put("thing14", customer.getName());
            // 预约时间
            params.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm",
                    orderMaster.getExpectTimeStart()));
            // 消息推送
            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), assignWorker.getWxOpenId(), WxMsgEnum.TEXT, params);
        } catch (Exception e) {
            // 暂时不做任何操作。
            logger.error(e.getMessage(), e);
        }
        return AjaxResult.success("下单成功");
    }

    /**
     * 平台下单时生成子财务单的方法
     * 只有平台扣点和截流扣点
     *
     * @param goodsStandard   商品 -- 第一个商品的规格来设置扣点
     * @param deptId          企业ID
     * @param financialMaster 主财务单
     */
    private void createDeptFinancialDetail(GoodsStandard goodsStandard, Long deptId, FinancialMaster financialMaster) {
        // 平台
        BigDecimal deptMoney = BigDecimal.ZERO;
        // 截流扣点
        BigDecimal specialMoney = BigDecimal.ZERO;
        // 服务金额
        BigDecimal serverMoney = financialMaster.getServerMoney();
        // 扣点设置类目
        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
        // 平台扣点 = 平台金额 + 商品单价 * 扣点比例
        deptMoney = deptMoney.add(deptGoodsCategory.getPcDeptMoney())
                .add(financialMaster.getPayMoney()
                        .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getPcDeptRate()))));
        // 截流扣点 = 截流金额 + 商品单价 * 扣点比例
        specialMoney = specialMoney.add(deptGoodsCategory.getPcRetainMoney())
                .add(financialMaster.getPayMoney()
                        .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getPcRetainRate()))));
        // 平台扣点记录
        FinancialDetail deptDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), deptMoney,
                FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(deptDetail);
        // 剩余服务金额
        serverMoney = serverMoney.subtract(deptMoney);

        // 截流扣点记录
        FinancialDetail retainDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), specialMoney,
                FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(retainDetail);
        // 剩余服务金额
        serverMoney = serverMoney.subtract(specialMoney);

        FinancialMaster fmUpdate = new FinancialMaster();
        fmUpdate.setId(financialMaster.getId());
        fmUpdate.setServerMoney(serverMoney);
        financialMasterService.updateFinancialMaster(fmUpdate);
    }

    /**
     * 分配订单
     */
    @PostMapping("/assign")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult assign(@RequestBody AppOrderAssignRequest request) throws BaseAdaPayException {
        logger.info("分配订单请求参数:{}", request);
        OrderMaster om = orderMasterService.selectById(request.getOrderMasterId());
        Assert.notNull(om, "订单不存在");
        FinancialMaster fm = financialMasterService.selectByOrderMasterId(om.getId());
        Assert.notNull(fm, "找不到对应的订单");
        // 派单师傅
        Worker assignWorker = workerService.selectById(om.getWorkerId());
        Assert.notNull(assignWorker, "找不到师傅信息");
        // 接单师傅
        Worker acceptWorker = workerService.selectById(request.getWorkerId());
        Assert.notNull(acceptWorker, "查询接单师傅信息失败");

        // 校验接单师傅和派单师傅是不是同一个Team
        if (om.getWorkerId().equals(request.getWorkerId())) {
            // 自己接单 子单金额=0
            request.setTotalPay(BigDecimal.ZERO);
        } else {
            if (fm.getServerMoney().compareTo(request.getTotalPay()) < 0) {
                logger.warn("派单金额[{}]大于订单总金额[{}]", request.getTotalPay(), fm.getServerMoney());
                return AjaxResult.error("派单金额不能大于订单总金额");
            }
            boolean checkInTeam = workerService.checkInTeam(assignWorker.getWorkerId(), acceptWorker.getWorkerId());
            // Assert.isTrue(checkInTeam, "接单师傅不在本团队");
        }
        // 创建子订单
        OrderDetail od = new OrderDetail();
        od.setDeptId(om.getDeptId());
        od.setCode(orderDetailService.createCode(om.getCode()));
        od.setOrderMasterId(om.getId());
        od.setOrderMasterCode(om.getCode());
        od.setCustomerId(om.getCustomerId());
        od.setOrderType(om.getOrderType());

        if (request.getIsQuicklyDelivery() != null && request.getIsQuicklyDelivery() == 1) {
            od.setOrderStatus(OrderStatus.SERVER.code());
            od.setDeliveryImages(om.getDeliveryImages());
            od.setDeliveryType(om.getDeliveryType());
            od.setDeliveryRemark(om.getDeliveryRemark());
            od.setTrackingNumber(om.getTrackingNumber());

            // 立即发货时，计算确认截止时间并设置到confirmStartTime字段
            Date now = new Date();
            long waitTimeMillis;
            String logType;

            // 根据发货类型判断等待时间
            if (om.getDeliveryType() != null) {
                if (om.getDeliveryType() == 2 || om.getDeliveryType() == 3) {
                    // 送货上门或自提：8小时
                    waitTimeMillis = 8 * 60 * 60 * 1000L; // 8小时的毫秒数
                    logType = om.getDeliveryType() == 2 ? "送货上门" : "自提";
                } else if (om.getDeliveryType() == 1) {
                    // 发快递/物流：4天
                    waitTimeMillis = 4 * 24 * 60 * 60 * 1000L; // 4天的毫秒数
                    logType = "发快递/物流";
                } else {
                    // 未知发货类型，默认8小时
                    waitTimeMillis = 8 * 60 * 60 * 1000L;
                    logType = "未知类型(默认8小时)";
                    logger.warn("订单[{}]发货类型未知[{}]，使用默认8小时", od.getCode(), om.getDeliveryType());
                }

                // 计算确认截止时间
                Date confirmDeadlineTime = new Date(now.getTime() + waitTimeMillis);
                od.setConfirmStartTime(confirmDeadlineTime);

                logger.info("立即发货订单[{}]发货类型[{}]，确认截止时间：{}",
                        od.getCode(), logType,
                        com.ghy.common.utils.DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", confirmDeadlineTime));
            } else {
                logger.warn("订单[{}]发货类型为null，未设置确认截止时间", od.getCode());
            }
        } else {
            od.setOrderStatus(request.getWorkerId().equals(om.getWorkerId()) ? OrderStatus.GOING.code()
                    : OrderStatus.RECEIVE.code());
        }
        od.setWorkerId(request.getWorkerId());
        od.setRevTime(om.getRevTime());
        od.setExpectTimeStart(om.getExpectTimeStart());
        od.setExpectTimeEnd(om.getExpectTimeEnd());
        od.setWorkBeginTime(new Date());
        // 将主单的客户备注和订单图片复制到子单
        // od.setCustomerRemark(om.getCustomerRemark());
        od.setOrderImages(om.getOrderImages());
        // 将主单的师傅备注复制到子单
        if(request.getWorkerId().equals(om.getWorkerId())) {
            od.setWorkerRemark(om.getWorkerRemark());

        }
        orderDetailService.insertOrderDetail(od);
        logger.info("子订单是否创建完成{}商品详情{}分配参数详情{}", od, request.getGoodsList(), request);
        // 批量生成订单商品
        request.getGoodsList().forEach(goods -> {
            // 查询规格信息
            GoodsStandard goodsStandard = goodsStandardService.selectById(goods.getGoodsStandardId());
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setGoodsStandardId(goods.getGoodsStandardId());
            orderGoods.setGoodsNum(goods.getNum());
            orderGoods.setGoodsName(goodsStandard.getGoodsStandardName());
            orderGoods.setOrderDetailId(od.getId());
            logger.info("是否为立即发货{}", request.getIsQuicklyDelivery());
            // 立即发货时，计算可发货数量（主单商品数量减去已分配给其他子单的数量）；否则设置为0
            if (request.getIsQuicklyDelivery() != null && request.getIsQuicklyDelivery() == 1) {
                // 获取主单中该商品的总数量
                List<OrderGoods> masterOrderGoodsList = orderGoodsService.selectByOrderMasterId(om.getId());
                Integer masterGoodsNum = 0;
                OrderGoods mastGoods = null;
                for (OrderGoods masterOrderGoods : masterOrderGoodsList) {
                    if (Objects.equals(masterOrderGoods.getGoodsStandardId(), goods.getGoodsStandardId())) {
                        masterGoodsNum = masterOrderGoods.getGoodsNum();
                        mastGoods = masterOrderGoods;
                        break;
                    }
                }

                // 获取该商品已经分配给其他子单的数量
                List<OrderDetail> existingOrderDetails = orderDetailService.selectByOrderMasterId(om.getId());
                Integer allocatedGoodsNum = 0;
                for (OrderDetail existingDetail : existingOrderDetails) {
                    // 排除当前正在创建的子单
                    if (!existingDetail.getId().equals(od.getId())) {
                        List<OrderGoods> existingOrderGoods = orderGoodsService
                                .selectByOrderDetailId(existingDetail.getId());
                        for (OrderGoods existingGoods : existingOrderGoods) {
                            if (Objects.equals(existingGoods.getGoodsStandardId(), goods.getGoodsStandardId())) {
                                allocatedGoodsNum += existingGoods.getGoodsNum();
                            }
                        }
                    }
                }

                // 计算剩余可发货数量 = 主单商品数量 - 已分配给其他子单的数量
                Integer availableGoodsNum = masterGoodsNum - allocatedGoodsNum;
                // 取当前子单商品数量和剩余可发货数量的最小值
                Integer serverGoodsNum = Math.min(goods.getNum(), Math.max(0, availableGoodsNum));

                if (mastGoods != null) {
                    mastGoods.setServerGoodsNum(serverGoodsNum);
                    orderGoodsService.updateOrderGoods(mastGoods);
                }
                orderGoods.setServerGoodsNum(serverGoodsNum);
                logger.info("立即发货订单[{}]商品[{}]主单总数量：{}，已分配数量：{}，当前子单数量：{}，设置已发货数量：{}",
                        od.getCode(), goodsStandard.getGoodsStandardName(), masterGoodsNum, allocatedGoodsNum,
                        goods.getNum(), serverGoodsNum);
            } else {
                orderGoods.setServerGoodsNum(0);
            }

            // orderGoods.setOrderId(om.getId());
            orderGoodsService.insertOrderGoods(orderGoods);
        });

        // 为接单师傅生成子财务单
        FinancialDetail fd = new FinancialDetail(fm.getDeptId(), financialDetailService.createCode(), fm.getId(),
                fm.getCode(), od.getId(), od.getCode(), request.getTotalPay(), FinancialDetailType.ORDER_FEE.getCode(),
                acceptWorker.getWorkerId(),
                fm.getPayType(), fm.getPayStatus(), fm.getPayTime());
        financialDetailService.insertFinancialDetail(fd);

        if (!BigDecimal.ZERO.equals(request.getTotalPay())) {
            // 更新财务主单服务金额
            FinancialMaster fm2up = new FinancialMaster();
            fm2up.setId(fm.getId());
            fm2up.setServerMoney(fm.getServerMoney().subtract(request.getTotalPay()));
            financialMasterService.updateFinancialMaster(fm2up);
        }

        // 保存订单操作记录
        OrderBehavior orderBehavior = new OrderBehavior().setOrderMasterId(om.getId()).setOrderMasterCode(om.getCode())
                .setWorkerId(assignWorker.getWorkerId()).setWorkerName(assignWorker.getName())
                .setBehavior(OrderBehaviorEnum.ASSIGN_ORDER);
        orderBehaviorService.insert(orderBehavior);

        // 更新主订单
        OrderMaster om2up = new OrderMaster();
        om2up.setId(om.getId());
        // 判断是否全部派完
        if (orderMasterService.isAllAssign(om.getId())) {
            Set<Long> workIds = orderDetailService.selectByOrderMasterId(om.getId()).stream()
                    .map(OrderDetail::getWorkerId).collect(Collectors.toSet());
            if (workIds.size() > 1 || !workIds.contains(om.getWorkerId())) {
                // 派完单 并且有其他师傅接单（包含其他人，监控单需要显示）
                om2up.setHasDispatchedAll(1);
                om2up.setAllSelfAssigned(0); // 保持原有含义：0表示有其他师傅参与
                om2up.setShowInMonitor(1); // 新字段：1表示显示在监控单
                om2up.setOrderStatus(OrderStatus.PLAIN.code());
            } else {
                // 派完单 但是只有自己接单（只有自己，监控单不显示）
                om2up.setHasDispatchedAll(1);
                om2up.setAllSelfAssigned(1); // 保持原有含义：1表示只有自己承接
                om2up.setShowInMonitor(0); // 新字段：0表示不显示在监控单
                if (request.getIsQuicklyDelivery() != null && request.getIsQuicklyDelivery() == 1) {
                    om2up.setOrderStatus(OrderStatus.SERVER.code());
                } else {
                    om2up.setOrderStatus(OrderStatus.GOING.code());
                }
            }
        } else {
            // 未派完单，但需要检查是否派给了非自己的师傅
            Set<Long> assignedWorkIds = orderDetailService.selectByOrderMasterId(om.getId()).stream()
                    .map(OrderDetail::getWorkerId).collect(Collectors.toSet());
            
            if (assignedWorkIds.size() > 1 || (assignedWorkIds.size() == 1 && !assignedWorkIds.contains(om.getWorkerId()))) {
                // 未派完单但派给了非自己的师傅，需要显示在监控单
                om2up.setAllSelfAssigned(0); // 保持原有含义：0表示有其他师傅参与
                om2up.setShowInMonitor(1); // 新字段：1表示显示在监控单
                om2up.setHasDispatchedAll(0);
                om2up.setOrderStatus(OrderStatus.PLAIN.code());
            } else {
                // 未派完单且只派给了自己或还没有派单，不显示在监控单
                om2up.setAllSelfAssigned(1); // 保持原有含义：1示未完成派单或只有自己
                om2up.setShowInMonitor(0); // 新字段：0表示不显示在监控单
                om2up.setHasDispatchedAll(0);
                om2up.setOrderStatus(OrderStatus.PLAIN.code());
            }
        }
        orderMasterService.updateOrderMaster(om2up);
        logger.info("是否已经全部派完单{}", om2up);
        // 通知师傅新订单
        try {
            logger.info("派单测试派单人员{}", acceptWorker.getName());
            // 推送公众号通知数据。
            // 消息组装。
            Map<String, Object> paramsNew = new HashMap<>();
            // 订单编号
            paramsNew.put("thing21", "您帐号收到1条新订单");
            // 名称
            paramsNew.put("thing31", "请进入【我的订单--新订单】操作处理");
            CustomerAddress address = customerAddressService.selectByCustomerAddressId(om.getAddressId());
            paramsNew.put("thing14", address.getName());
            // 预约时间
            paramsNew.put("time4",
                    com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", om.getExpectTimeStart()));
            // 非自己承接的订单需要通知
            logger.info("主订单师傅{}，派单师傅{}", om.getWorkerId(), request.getWorkerId());
            if (!om.getWorkerId().equals(request.getWorkerId())) {
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), acceptWorker.getWxOpenId(),
                        WxMsgEnum.NORMAL_ORDER, paramsNew);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return AjaxResult.success();
    }

    /**
     * 更新订单商品的已发货数量
     * 
     * @param orderDetailId 子订单ID
     * @param isIncrement   是否增加数量（true：增加，false：重置为0）
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderGoodsServerNum(Long orderDetailId, boolean isIncrement) {
        try {
            // 获取子订单商品列表
            List<OrderGoods> orderGoodsList = orderGoodsService.selectByOrderDetailId(orderDetailId);

            if (CollectionUtils.isEmpty(orderGoodsList)) {
                logger.warn("订单详情[{}]未找到关联商品", orderDetailId);
                return;
            }

            // 更新每个商品的已发货数量
            for (OrderGoods orderGoods : orderGoodsList) {
                if (isIncrement) {
                    // 增加已发货数量（设置为商品总数量）
                    orderGoods.setServerGoodsNum(orderGoods.getGoodsNum());
                    logger.info("订单商品[{}]已发货数量更新为：{}", orderGoods.getGoodsName(), orderGoods.getGoodsNum());
                } else {
                    // 重置已发货数量为0
                    orderGoods.setServerGoodsNum(0);
                    logger.info("订单商品[{}]已发货数量重置为：0", orderGoods.getGoodsName());
                }

                // 更新数据库
                int updateResult = orderGoodsService.updateOrderGoods(orderGoods);
                if (updateResult <= 0) {
                    logger.error("更新订单商品[{}]已发货数量失败", orderGoods.getGoodsName());
                    throw new RuntimeException("更新订单商品已发货数量失败");
                }
            }

            logger.info("订单详情[{}]商品已发货数量更新完成，共更新{}个商品", orderDetailId, orderGoodsList.size());

        } catch (Exception e) {
            logger.error("更新订单详情[{}]商品已发货数量异常：{}", orderDetailId, e.getMessage(), e);
            throw new RuntimeException("更新商品已发货数量失败：" + e.getMessage());
        }
    }

    @PostMapping("/server/app")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult appOrder(@RequestBody AppOrderRequest appOrderRequest) throws ParseException {
        // 校验用户信息
        Customer customer = customerService.selectByCustomerId(appOrderRequest.getCustomerId());
        if (customer == null) {
            return AjaxResult.error("用户不存在!");
        }
        List<AppGoodsRequest> appGoodsList = appOrderRequest.getGoodsList();
        // 校验商品信息(库存)
        boolean flag = goodsService.checkStore(appGoodsList);
        if (!flag) {
            return AjaxResult.error("库存不足!");
        }
        // 计算商品费用
        BigDecimal totalPay = goodsService.calculate(appGoodsList);
        logger.info("获取到的商品：{},计算的商品价值{}", appGoodsList, totalPay);
        // 所有商品的ID
        Set<Long> goodsStandardIds = appGoodsList.stream().map(AppGoodsRequest::getGoodsStandardId)
                .collect(Collectors.toSet());
        // 所有商品
        List<GoodsStandard> goodsList = goodsStandardService.selectByIds(goodsStandardIds);
        logger.info("商品信息{}", goodsList);
        
        // 扣减库存
        Map<Long, GoodsStandard> goodsStandardMap = goodsList.stream()
                .collect(Collectors.toMap(GoodsStandard::getGoodsStandardId, gs -> gs));
        for (AppGoodsRequest appGoods : appGoodsList) {
            GoodsStandard goodsStandard = goodsStandardMap.get(appGoods.getGoodsStandardId());
            if (goodsStandard != null && goodsStandard.getGoodsNum() != null) {
                // 记录扣减前的库存
                Integer oldStock = goodsStandard.getGoodsNum();
                // 扣减库存
                Integer newStock = oldStock - appGoods.getNum();
                if (newStock < 0) {
                    logger.error("库存扣减异常，商品规格ID: {}, 当前库存: {}, 扣减数量: {}", 
                            appGoods.getGoodsStandardId(), oldStock, appGoods.getNum());
                    return AjaxResult.error("库存不足，扣减失败!");
                }
                goodsStandard.setGoodsNum(newStock);
                goodsStandardService.update(goodsStandard);
                logger.info("商品规格ID: {} 库存扣减成功，扣减前: {}, 扣减数量: {}, 扣减后: {}", 
                        appGoods.getGoodsStandardId(), oldStock, appGoods.getNum(), newStock);
            }
        }
        // 商品所属师傅
        // 获取商品信息
        Goods goods = goodsService.selectById(goodsList.get(0).getGoodsId());
        logger.info("下单后的师傅信息{}", goods);
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderType(0);
        // 判断是否是配件商品
        if (goods.getType() != null && goods.getType() == 2) {
            // 配件商品，需要获取对应的服务商品
            orderMaster.setOrderType(1);
        }

        // // 通过商品的类目ID获取类目信息
        // DeptGoodsCategory deptGoodsCategory =
        // deptGoodsCategoryService.selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
        // if (deptGoodsCategory != null && deptGoodsCategory.getServiceCategoryId() !=
        // null) {
        // logger.info("配件商品的服务类目ID: {}", deptGoodsCategory.getServiceCategoryId());

        // // 通过服务类目ID查询对应的服务商品
        // Goods serviceGoodsQuery = new Goods();
        // serviceGoodsQuery.setDeptGoodsCategoryId(deptGoodsCategory.getServiceCategoryId());
        // serviceGoodsQuery.setType(1); // 服务商品类型
        // serviceGoodsQuery.setStatus(0); // 上架状态
        // List<Goods> serviceGoodsList =
        // goodsService.selectGoodsList(serviceGoodsQuery);
        // if (CollectionUtils.isNotEmpty(serviceGoodsList)) {
        // Goods serviceGoods = serviceGoodsList.get(0); // 取第一个服务商品
        // logger.info("找到对应的服务商品: {}", serviceGoods);
        // orderMaster.setServerGoodsId(serviceGoods.getGoodsId());

        // // 设置服务店铺ID
        // if (serviceGoods.getShopId() != null) {
        // orderMaster.setServiceShopId(serviceGoods.getShopId());
        // logger.info("设置服务店铺ID: {}", serviceGoods.getShopId());
        // }
        // } else {
        // logger.warn("未找到服务类目ID为 {} 的服务商品", deptGoodsCategory.getServiceCategoryId());
        // }
        // } else {
        // logger.warn("配件商品的类目信息中未配置服务类目ID");
        // }
        // }
        // 师傅信息
        Worker worker = workerService.selectById(goods.getWorkerId());
        // 商户ID
        Long deptId = appOrderRequest.getDeptId();
        Assert.notNull(deptId, "deptId is null!");

        // 生成主单
        orderMaster.setIsDeliveryToStore(appOrderRequest.getIsDeliveryToStore());
        orderMaster.setOrderImages(appOrderRequest.getOrderImages());
        orderMaster.setServiceShopId(appOrderRequest.getServiceShopId());
        orderMaster.setDeptId(deptId);
        orderMaster.setIsNeedBill(appOrderRequest.getIsNeedBill());
        orderMaster.setCode(orderMasterService.createOrderCode());
        orderMaster.setPayType(appOrderRequest.getPayType());
        orderMaster.setOrderStatus(OrderStatus.RECEIVE.code());
        orderMaster.setCustomerId(appOrderRequest.getCustomerId());
        orderMaster.setAddressId(appOrderRequest.getAddressId());
        orderMaster.setPayStatus(PayStatus.WAIT_PAY.getCode());
        orderMaster.setCreateTime(new Date());
        orderMaster.setWorkerId(goods.getWorkerId());
        orderMaster.setGoodsId(appOrderRequest.getGoodsId());
        // orderMaster.setRevTime(DateUtils.parseDate(appOrderRequest.getServerTime(),
        // com.ghy.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));
        orderMaster.setRemark(appOrderRequest.getRemark());
        orderMaster.setExpectTimeStart(DateUtils.parseDate(appOrderRequest.getExpectTimeStart(),
                com.ghy.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));
        orderMaster.setExpectTimeEnd(DateUtils.parseDate(appOrderRequest.getExpectTimeEnd(),
                com.ghy.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS));
        orderMaster.setInsuranceId(appOrderRequest.getInsuranceId());

        // 处理新增订单的地址
        CustomerAddress customerAddress = customerAddressService
                .selectByCustomerAddressId(appOrderRequest.getAddressId());
        SysArea sysArea = sysAreaService.selectById(customerAddress.getStreetId());
        String addressSysArea = sysArea.getMergerName();
        String[] array = addressSysArea.split(",");
        logger.info("下单后的地址信息{}", array);
        orderMaster.setProvinceId(customerAddress.getProvinceId());
        orderMaster.setCityId(customerAddress.getCityId());
        orderMaster.setCountryId(customerAddress.getCountryId());
        orderMaster.setStreetId(customerAddress.getStreetId());
        orderMaster.setAddress(customerAddress.getAddress());
        orderMaster.setName(customerAddress.getName());
        orderMaster.setPhone(customerAddress.getPhone());
        orderMaster.setProvinceName(array[0]);
        orderMaster.setCityName(array[1]);
        orderMaster.setCountryName(array[2]);
        orderMaster.setStreetId(customerAddress.getStreetId());
        orderMaster.setStreetName(array[3]);

        // TODO 优惠金额不知道咋算 暂时先给0
        BigDecimal discountMoney = BigDecimal.ZERO;
        BigDecimal payMoney = totalPay.subtract(discountMoney);
        BigDecimal insuranceMoney = BigDecimal.ZERO;

        // 保险金额
        if (appOrderRequest.getInsuranceId() != null) {
            InsuranceManager manager = insuranceManagerService
                    .selectInsuranceManagerById(appOrderRequest.getInsuranceId());
            if (manager != null) {
                payMoney = payMoney.add(manager.getInsuranceAmount());
                insuranceMoney = insuranceMoney.add(manager.getInsuranceAmount());
                orderMaster.setInsuranceId(manager.getId());
            }
        }
        logger.info("是否有保险金额{}", payMoney);
        orderMasterService.insertOrderMaster(orderMaster);
        Assert.notNull(orderMaster.getId(), "OrderMaster.id is null!");

        // 当实付金额payType<=0时 使payType=BigDecimal.ZERO
        payMoney = BigDecimal.ZERO.max(payMoney);

        // 生成财务主单
        FinancialMaster financialMaster = new FinancialMaster(financialMasterService.createCode(), deptId,
                orderMaster.getId(), orderMaster.getCode(), totalPay, discountMoney, payMoney);
        financialMaster.setServerMoney(financialMaster.getTotalMoney());
        financialMasterService.insertFinancialMaster(financialMaster);
        Assert.notNull(financialMaster.getId(), "FinancialMaster.id is null!");

        // createFinancialDetail(goodsList.get(0).getDeptGoodsCategoryId(), deptId,
        // customer, payMoney, financialMaster);

        // 生成财务子单
        createFinancialDetail(appGoodsList, deptId, customer, payMoney, financialMaster, insuranceMoney);

        // 生成商品订单
        Map<Long, GoodsStandard> goodsMap = goodsList.stream().filter(Objects::nonNull)
                .collect(Collectors.toMap(GoodsStandard::getGoodsStandardId, x -> x));
        for (AppGoodsRequest appGoods : appGoodsList) {
            GoodsStandard goodsStandard = goodsMap.get(appGoods.getGoodsStandardId());
            OrderGoods orderGoods = new OrderGoods(orderMaster.getId(), goodsStandard.getGoodsStandardId(),
                    goodsStandard.getGoodsStandardName(), appGoods.getNum(), 0);
            orderGoodsService.insertOrderGoods(orderGoods);
        }
        // 通知师傅新订单
        try {
            // 推送公众号通知数据。
            // 消息组装。
            Map<String, Object> paramsNew = new HashMap<>();
            // 订单编号
            paramsNew.put("thing21", "您帐号收到1条新订单");
            // 名称
            paramsNew.put("thing31", "请进入【我的订单--新订单】操作处理");
            CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
            paramsNew.put("thing14", address.getName());
            // 预约时间
            paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.NORMAL_ORDER,
                    paramsNew);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return AjaxResult.success(orderMaster);
    }

    private void createFinancialDetail(List<AppGoodsRequest> appGoodsList, Long deptId, Customer customer,
            BigDecimal serverMoney, FinancialMaster financialMaster, BigDecimal insuranceMoney) {
        // 平台
        BigDecimal deptMoney = BigDecimal.ZERO;
        // 一级分销
        BigDecimal oneMoney = BigDecimal.ZERO;
        // 二级分销
        BigDecimal twoMoney = BigDecimal.ZERO;
        // 三级分销
        BigDecimal threeMoney = BigDecimal.ZERO;
        // 截流扣点
        BigDecimal specialMoney = BigDecimal.ZERO;
        for (AppGoodsRequest goodsRequest : appGoodsList) {
            // 商品规格-提成额
            GoodsStandard goodsStandard = goodsStandardService.selectById(goodsRequest.getGoodsStandardId());
            // 扣点设置类目
            DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
            for (int index = 0; index < goodsRequest.getNum(); index++) {
                // 一级分销 = 商品单价 * 扣点比例
                oneMoney = oneMoney
                        .add(goodsStandard.getGoodsPrice()
                                .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getOneRate()))));
                // 二级分销 = 商品单价 * 扣点比例
                twoMoney = twoMoney.add(goodsStandard.getGoodsPrice()
                        .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getTwoRate()))));
                // 三级分销 = 提成额 + 商品单价 * 扣点比例
                threeMoney = threeMoney.add(goodsStandard.getExtMoney())
                        .add(goodsStandard.getGoodsPrice()
                                .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getThreeRate()))));
                // 平台扣点 = 平台金额 + 商品单价 * 扣点比例
                deptMoney = deptMoney.add(deptGoodsCategory.getDeptMoney())
                        .add(goodsStandard.getGoodsPrice()
                                .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getDeptRate()))));
                // 截流扣点 = 截流金额 + 商品单价 * 扣点比例
                specialMoney = specialMoney.add(deptGoodsCategory.getRetainMoney())
                        .add(goodsStandard.getGoodsPrice()
                                .multiply(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getRetainRate()))));
            }
        }
        // logger.info("一二三级平台节流扣点分别为【{}】【{}】【{}】【{}】[{}]",oneMoney,twoMoney,threeMoney,deptMoney,specialMoney);
        // 平台扣除保险 --
        deptMoney = deptMoney.add(insuranceMoney);

        // 平台扣点记录
        FinancialDetail deptDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), deptMoney,
                FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(deptDetail);

        // 剩余服务金额
        serverMoney = serverMoney.subtract(deptMoney);

        // 截流扣点记录
        FinancialDetail retainDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), specialMoney,
                FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(retainDetail);

        // 剩余服务金额
        serverMoney = serverMoney.subtract(specialMoney);

        // 分销扣点记录
        Long customerPlaceId = customer.getCustomerPlace();
        Long parentCustomerPlaceId = customer.getParentCustomerPlace();
        Long reparentCustomerPlaceId = null;
        if (customer.getParentCustomerPlace() != null) {
            Customer parentPlaceCustomer = customerService.selectByCustomerId(customer.getParentCustomerPlace());
            if (parentPlaceCustomer != null) {
                reparentCustomerPlaceId = parentPlaceCustomer.getCustomerPlace();
            }
        }

        // 一级分销
        if (customerPlaceId != null) {
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), threeMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), customerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);

            // 剩余服务金额
            serverMoney = serverMoney.subtract(threeMoney);
        }

        // 二级分销
        if (parentCustomerPlaceId != null) {
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), twoMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), parentCustomerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);

            // 剩余服务金额
            serverMoney = serverMoney.subtract(twoMoney);
        } else if (customerPlaceId != null) {
            // 二级没有，且三级有
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), twoMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), customerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);

            // 剩余服务金额
            serverMoney = serverMoney.subtract(twoMoney);
        }

        // 最上级分，没有则给下级，再没有再给下级
        if (reparentCustomerPlaceId != null) {
            // 平台分销
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), oneMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), reparentCustomerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);

            // 剩余服务金额
            serverMoney = serverMoney.subtract(oneMoney);
        } else if (parentCustomerPlaceId != null) {
            // 平台分销
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), oneMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), parentCustomerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);

            // 剩余服务金额
            serverMoney = serverMoney.subtract(oneMoney);
        } else if (customerPlaceId != null) {
            // 平台分销
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), oneMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), customerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);

            // 剩余服务金额
            serverMoney = serverMoney.subtract(oneMoney);
        }

        financialMaster.setServerMoney(serverMoney);
        financialMasterService.updateFinancialMaster(financialMaster);
    }

    /**
     * 生成财务子单
     *
     * @param deptGoodsCategoryId 商品类目id
     * @param deptId              商户ID
     * @param customer            消费者
     * @param payMoney            实付金额
     * @param financialMaster     财务主单
     */
    private void createFinancialDetail(Long deptGoodsCategoryId, Long deptId, Customer customer, BigDecimal payMoney,
            FinancialMaster financialMaster) {
        // 是否为0元购 是的话下面就不用多级分销了
        if (BigDecimal.ZERO.compareTo(payMoney) == 0) {
            return;
        }

        /* 1 平台服务服务费 */
        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(deptGoodsCategoryId);
        BigDecimal deptRate = new BigDecimal(deptGoodsCategory.getDeptRate());
        BigDecimal deptMoney = deptGoodsCategory.getDeptMoney();

        BigDecimal deptTotal = payMoney.multiply(deptRate).add(deptMoney);

        FinancialDetail deptDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), deptTotal,
                FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(deptDetail);

        /* 2 截留扣点 */
        BigDecimal retainRate = new BigDecimal(deptGoodsCategory.getRetainRate());
        BigDecimal retainMoney = deptGoodsCategory.getRetainMoney();

        BigDecimal retainTotal = payMoney.multiply(retainRate).add(retainMoney);

        FinancialDetail retainDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), retainTotal,
                FinancialDetailType.PLATFORM_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(retainDetail);

        /* 3 分销扣点 */
        BigDecimal deptPlaceTotal = BigDecimal.ZERO;

        Long customerPlaceId = customer.getCustomerPlace();
        BigDecimal onePlaceMoney = payMoney.multiply(new BigDecimal(deptGoodsCategory.getOneRate()));
        BigDecimal twoPlaceMoney = payMoney.multiply(new BigDecimal(deptGoodsCategory.getTwoRate()));
        BigDecimal threePlaceMoney = payMoney.multiply(new BigDecimal(deptGoodsCategory.getThreeRate()));

        // 一级分销
        if (customerPlaceId != null) {
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), onePlaceMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), customerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);
        } else {
            deptPlaceTotal = deptPlaceTotal.add(onePlaceMoney);
        }

        // 二级分销
        Long parentCustomerPlaceId = customer.getParentCustomerPlace();
        if (parentCustomerPlaceId != null) {
            FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                    financialMaster.getId(), financialMaster.getCode(), twoPlaceMoney,
                    FinancialDetailType.PLACE_FEE.getCode(), parentCustomerPlaceId);
            financialDetailService.insertFinancialDetail(financialDetail);
        } else {
            deptPlaceTotal = deptPlaceTotal.add(twoPlaceMoney);
        }

        // 平台分销
        deptPlaceTotal = deptPlaceTotal.add(threePlaceMoney);
        FinancialDetail financialDetail = new FinancialDetail(deptId, financialDetailService.createCode(),
                financialMaster.getId(), financialMaster.getCode(), deptPlaceTotal,
                FinancialDetailType.PLACE_FEE.getCode(), null);
        financialDetailService.insertFinancialDetail(financialDetail);

        // 更新订单服务金额
        financialMaster.setServerMoney(financialMaster.getServerMoney().subtract(deptTotal)
                .subtract(retainTotal).subtract(deptPlaceTotal));
        financialMasterService.updateFinancialMaster(financialMaster);
    }

    /**
     * 订单统计
     */
    @PostMapping("/app/statistics")
    @ResponseBody
    public AjaxResult orderStatistics(@RequestBody OrderStatisticsRequest request) {
        OrderStatisticsResponse response = new OrderStatisticsResponse();

        try {
            OrderMaster orderMaster = new OrderMaster();
            orderMaster.setDeptId(request.getDeptId());
            orderMaster.setOrderStatus(OrderStatus.RECEIVE.code());
            orderMaster.setWorkerId(request.getWorkerId());
            orderMaster.setOrderType(request.getOrderType());
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setDeptId(request.getDeptId());
            orderDetail.setOrderStatus(OrderStatus.RECEIVE.code());
            orderDetail.setWorkerId(request.getWorkerId());
            orderDetail.setShelveStatus(0);
            orderDetail.setOrderType(request.getOrderType());
            Long newMasterOrderCount = orderMasterService.countOrderMasterList(orderMaster);
            Long newDetailOrderCount = orderDetailService.countOrderDetailList(orderDetail);
            // 统计新订单的单量
            response.setNewOrderNum(newMasterOrderCount + newDetailOrderCount);
            // 统计未排的单量
            orderMaster.setOrderStatus(OrderStatus.PLAIN.code());
            // 如果查询的是未约未排状态，只查询未全部派完的主单
            orderMaster.setHasDispatchedAll(0);
            orderDetail.setOrderStatus(OrderStatus.PLAIN.code());
            Long planMasterOrderCount = orderMasterService.countOrderMasterList(orderMaster);
            Long planDetailOrderCount = orderDetailService.countOrderDetailList(orderDetail);
            response.setPlanOrderNum(planMasterOrderCount + planDetailOrderCount);
            orderMaster.setHasDispatchedAll(null);
            // 统计待上门单量
            orderDetail.setOrderStatus(OrderStatus.GOING.code());
            response.setWaitServOrderNum(orderDetailService.countOrderDetailList(orderDetail));
            // 统计服务中单量
            orderDetail.setOrderStatus(OrderStatus.SERVER.code());
            response.setServingOrderNum(orderDetailService.countOrderDetailList(orderDetail));
            // 统计待确认单量
            orderDetail.setOrderStatus(null);
            orderDetail.setOrderStatusList(new ArrayList<Integer>() {
                {
                    add(4);
                    add(5);
                }
            });
            orderDetail.setWorkFinishTimeExisted(true);
            orderDetail.setDrawCashStatusList(new ArrayList<Integer>() {
                {
                    add(0);
                    add(1);
                }
            });
            response.setWaitSureOrderNum(orderDetailService.countOrderDetailList(orderDetail));
            orderDetail.setOrderStatusList(null);
            // 统计已完成子单量
            orderDetail.setOrderStatus(OrderStatus.FINISH.code());
            orderDetail.setDrawCashStatusList(new ArrayList<Integer>() {
                {
                    add(2);
                }
            });
            response.setFinishedOrderNum(orderDetailService.countOrderDetailList(orderDetail));
            orderDetail.setWorkFinishTimeExisted(false);
            orderDetail.setDrawCashStatusList(null);
            // 统计已完成主单量
            orderMaster.setOrderStatus(OrderStatus.FINISH.code());
            response.setFinishedMasterOrderNum(orderMasterService.countOrderMasterList(orderMaster));
            // 统计监控单量
            orderMaster.setOrderStatus(null);
            orderMaster.setIsMonitoredOrder(true);
            orderMaster.setAllSelfAssigned(0);
            Long monitoredOrderNum = orderMasterService.countOrderMasterList(orderMaster);
            if (orderMaster.getOrderType()!=null&&orderMaster.getOrderType() == 0) {
                OrderMaster origiOrderMaster = new OrderMaster();
                origiOrderMaster.setOriginalWorkerId(orderMaster.getWorkerId());
                origiOrderMaster.setOrderStatuses("0,1,2,3,4");
                List<OrderMaster> originalList = orderMasterService.selectOrderMasterList(origiOrderMaster);
                monitoredOrderNum += originalList.size();
            }

            response.setMonitoredOrderNum(monitoredOrderNum);
            orderMaster.setIsMonitoredOrder(false);
            orderMaster.setAllSelfAssigned(null);
            // 统计搁置单量
            OrderDetail orderDetail1 = new OrderDetail();
            orderDetail1.setDeptId(request.getDeptId());
            orderDetail1.setWorkerId(request.getWorkerId());
            orderDetail1.setShelveStatus(1);
            orderDetail1.setOrderType(request.getOrderType());
            response.setShelvedOrderNum(orderDetailService.countOrderDetailList(orderDetail1));
            // 统计售后中单量
            OrderListRequest orderListRequest = new OrderListRequest();
            orderListRequest.setDeptId(request.getDeptId());
            orderListRequest.setWorkerId(request.getWorkerId());
            orderListRequest.setIsMonitoredOrder(true);
            orderListRequest.setAllSelfAssigned(0);
            orderListRequest.setNeedImgs(false);
            orderListRequest.setOrderType(request.getOrderType());
            AjaxResult afterListRes = this.appMixAfterList(orderListRequest);
            List<AfterServiceRecord> afterList = (List<AfterServiceRecord>) afterListRes.get("data");
            response.setAfterListNum(afterList.size());
            // 统计超时单量
            orderListRequest = new OrderListRequest();
            orderListRequest.setDeptId(request.getDeptId());
            orderListRequest.setTimeout(1);
            orderListRequest.setWorkerId(request.getWorkerId());
            // orderListRequest.setIsMonitoredOrder(true);
            orderListRequest.setNeedImgs(false);
            orderListRequest.setOrderType(request.getOrderType());
            response.setOverTimeOrderNum(this.appMixOrderCount(orderListRequest));
            // 统计今日单量
            LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
            orderDetail.setOrderStatus(OrderStatus.GOING.code());
            orderDetail.setExpectTimeStart(Date.from(today.atZone(ZoneId.systemDefault()).toInstant()));
            today = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
            orderDetail.setExpectTimeEnd(Date.from(today.atZone(ZoneId.systemDefault()).toInstant()));
            response.setTodayOrderNum(orderDetailService.countOrderDetailList(orderDetail));
            // 统计明日单量
            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()));
            response.setTomorrowOrderNum(orderDetailService.countOrderDetailList(orderDetail));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getStackTrace(e));
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(response);
    }

    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) // 排除已取消的订单
                .filter(order -> order.getOrderStatus() != 5) // 排除已完成的订单
                // 排除商品订单中“服务中(3)”状态：保留非商品订单，或商品订单且状态 != 服务中
                .filter(order -> order.getOrderType() != 1 ||
                        order.getOrderStatus() != OrderStatus.SERVER.code())
                .count();
        count += size;
        logger.info("子单超时数量{}", count);
        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());
            param.setOrderType(orderListRequest.getOrderType());
            List<OrderMaster> allOrderMaster = orderMasterService.selectOrderMasterList(param);
            if (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 (CollectionUtils.isEmpty(countParam.getMasterIds())) {
                    return count;
                }
                logger.info("符合条件的主单超时参数{},count{}", countParam, count);
                List<OrderDetail> orderDetails = orderDetailService.selectOrderDetailList(countParam);
                List<OrderDetail> result = orderDetails.stream().filter(s -> s.getTimeout().equals(1))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(result)) {
                    masterIdSet = result.stream().map(OrderDetail::getOrderMasterId).collect(Collectors.toList());
                }
            }
            if (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);
        allList=allList.stream()
                .filter(order -> order.getOrderStatus() != 6) // 排除已取消的订单
                .filter(order -> order.getOrderStatus() != 5) // 排除已完成的订单
                // 排除商品订单中“服务中(3)”状态：保留非商品订单，或商品订单且状态 != 服务中
                .filter(order -> order.getOrderType() != 1 ||
                        order.getOrderStatus() != OrderStatus.SERVER.code())
                .filter(order -> order.getHasDispatchedAll()!=null&&order.getHasDispatchedAll()==0)
                .collect(Collectors.toList());
        List<Long> mateIds = allList.stream().map(OrderMaster::getId)
                .collect(Collectors.toList());
       // logger.info("查询符合条件的主单条件{}总数{}allList的数量{}allist的主单id{}", orderMasterReq, count, allList.size(), mateIds);
        // 超时查询需要排除同个师傅的主单子单同时出现
        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());
                BeanUtils.copyProperties(orderListRequest, detailAfterListOfMasterQry);
                detailAfterListOfMasterQry.setOrderMasterCode(master.getCode()); // 确保使用主单code
                List<OrderDetail> tmpDetailListOfMasters = orderDetailService
                        .selectOrderDetailList(detailAfterListOfMasterQry);
                
                // 如果主单下没有符合条件的子单，保留主单（因为子单没有被统计，不存在重复计数）
                if (CollectionUtils.isEmpty(tmpDetailListOfMasters)) {
                    filteredMasterList.add(master);
                    continue;
                }
                
                List<OrderListResponse> detailListOfMasters = new ArrayList<>();
                tmpDetailListOfMasters.forEach(model -> {
                    OrderListResponse response = new OrderListResponse();
                    BeanUtils.copyProperties(model, response);
                    detailListOfMasters.add(response);
                });
                
                // 检查是否有其他师傅的子单（排除同个师傅的主单子单同时出现）
                for (OrderListResponse detailListOfMaster : detailListOfMasters) {
                    // 修复空指针问题：检查workerId是否为null
                    if (detailListOfMaster.getWorkerId() != null 
                            && orderListRequest.getWorkerId() != null
                            && !detailListOfMaster.getWorkerId().equals(orderListRequest.getWorkerId())) {
                        isKeep = true;
                        break;
                    }
                }
                
                logger.info("主单id{},符合条件的子单数量{},是否有其他师傅的子单:{}", master.getId(), detailListOfMasters.size(), isKeep);
                
                // 如果有其他师傅的子单，保留主单
                // 如果所有子单都是同一个师傅（等于请求的workerId），且这些子单已经在前面统计过了，排除主单（避免重复计数）
                if (isKeep) {
                    filteredMasterList.add(master);
                }
                // 如果所有子单都是同一个师傅，且这些子单已经在前面统计过了，不添加到filteredMasterList（排除主单）
            }
            count += filteredMasterList.size();
            mateIds = filteredMasterList.stream().map(OrderMaster::getId)
                    .collect(Collectors.toList());
            logger.info("主单filteredMasterList超时数量{}总数{},filteredMasterList的id集合{}", filteredMasterList.size(), count,
                    mateIds);
        } else {
            count += masterList.size();
        }
        logger.info("主单超时数量{}总数{}", masterList.size(), count);
        return count;
    }

    /**
     * 查询主单子单的混合列表
     */
    @PostMapping("/app/mix/order/list")
    @ResponseBody
    public AjaxResult appMixOrderList(@RequestBody OrderListRequest orderListRequest) {
        List<OrderListResponse> orderListResponses = new ArrayList<>();

        logger.info("查询不同订单的传入参数{}", orderListRequest);
        // 校验参数
        Assert.notNull(orderListRequest.getWorkerId(), "师傅id不能为空");

        // 查询子单
        OrderDetail orderDetailReq = new OrderDetail();
        BeanUtils.copyProperties(orderListRequest, orderDetailReq);
        // 当查询超时订单时，需要同时考虑订单服务超时和售后超时
        if (orderListRequest.getTimeout() != null && orderListRequest.getTimeout() == 1) {
            orderDetailReq.setIncludeAfterTimeout(true);
        }
        // 拿到所有正常筛选出来的子单
        List<OrderListResponse> detailList = this.getDetailList(orderDetailReq);
        orderListResponses.addAll(detailList);
        // List<OrderListResponse> 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(CollectionUtils.isNotEmpty(allOrderMaster)){
        // OrderDetail countParam = new OrderDetail();
        // countParam.setMasterIds(allOrderMaster.stream().map(OrderMaster::getId).collect(Collectors.toList()));
        // List<OrderDetail> orderDetails =
        // orderDetailService.selectOrderDetailList(countParam);
        // List<OrderDetail> result = orderDetails.stream().filter(s ->
        // s.getTimeout().equals(1)).collect(Collectors.toList());
        // if (CollectionUtils.isNotEmpty(result)) {
        // masterIdSet =
        // result.stream().map(OrderDetail::getOrderMasterId).collect(Collectors.toList());
        // }
        // }
        // if (CollectionUtils.isNotEmpty(masterIdSet)) {
        // OrderMaster timeOutMaster = new OrderMaster();
        // timeOutMaster.setOrderMasterIdList(masterIdSet);
        // allList.addAll(this.getMasterList(timeOutMaster));
        // }
        // }

        // 查询主单
        OrderMaster orderMasterReq = new OrderMaster();
        BeanUtils.copyProperties(orderListRequest, orderMasterReq);
        // orderMasterReq.setExceptOrderMasterIds(masterIdSet);
        orderMasterReq.setGoodsName(null);
        List<OrderListResponse> masterList = this.getMasterList(orderMasterReq);

        // allList.addAll(masterList);
        // 超时查询需要排除同个师傅的主单子单同时出现
        // if (orderListRequest.getTimeout() != null && orderListRequest.getTimeout() ==
        // 1) {
        // // 需要排除同个师傅的主单子单同时出现
        // List<OrderListResponse> filteredMasterList = new
        // ArrayList<OrderListResponse>();
        // for (OrderListResponse master : allList) {
        // boolean isKeep = false;
        // // 查询该主单下所有售后中的子单
        // OrderDetail detailAfterListOfMasterQry = new OrderDetail();
        // detailAfterListOfMasterQry.setOrderMasterCode(master.getOrderMasterCode());
        // List<OrderListResponse> detailListOfMasters =
        // this.getDetailList(detailAfterListOfMasterQry);
        // for (OrderListResponse detailListOfMaster : detailListOfMasters) {
        // if (!detailListOfMaster.getWorkerId().equals(orderListRequest.getWorkerId()))
        // {
        // isKeep = true;
        // break;
        // }
        // }
        // if (isKeep) {
        // filteredMasterList.add(master);
        // }
        // }
        // orderListResponses.addAll(filteredMasterList);
        // } else {
        orderListResponses.addAll(masterList);
        // }
        //logger.info("未处理的订单{}", orderListResponses);
        if (orderListRequest.getTimeout() != null && orderListRequest.getTimeout() == 1) {
            if (orderListResponses.size() > 0) {
                orderListResponses = orderListResponses.stream()
                        .filter(order -> order.getOrderStatus() != 5 && order.getOrderStatus() != 6)
                        .collect(Collectors.toList());
            }
            logger.info("处理已完成及已取消的订单: {}", orderListResponses);
        }

         if(CollectionUtils.isNotEmpty(orderListResponses)){
            // 如果传入的参数是商品订单且timeout为1，则排除orderStatus为3、5、6的订单
            if (orderListRequest.getOrderType() != null && orderListRequest.getOrderType() == 1 
                    && orderListRequest.getTimeout() != null && orderListRequest.getTimeout() == 1) {
                orderListResponses = orderListResponses.stream()
                        .filter(order -> order.getOrderStatus() != 3 
                                && order.getOrderStatus() != 5 
                                && order.getOrderStatus() != 6)
                        .collect(Collectors.toList());
            } 
         }

        // 查询新订单列表根据创建时间倒叙排列，查询其他根据更新时间倒序排列
        Collections.sort(orderListResponses, new Comparator<OrderListResponse>() {
            @Override
            public int compare(OrderListResponse o1, OrderListResponse o2) {
                if (Objects.equals(orderListRequest.getOrderStatus(), 0)) {
                    return o2.getCreateTime().compareTo(o1.getCreateTime());
                } else if (Objects.equals(orderListRequest.getTimeout(), 1)) {
                    // 超时订单按超时时间倒序排列，如果超时时间为空则按创建时间倒序
                    if (o1.getTimeoutTime() != null && o2.getTimeoutTime() != null) {
                        return o2.getTimeoutTime().compareTo(o1.getTimeoutTime());
                    } else if (o1.getTimeoutTime() != null) {
                        return -1; // o1有超时时间，o2没有，o1排前面
                    } else if (o2.getTimeoutTime() != null) {
                        return 1; // o2有超时时间，o1没有，o2排前面
                    } else {
                        return o2.getCreateTime().compareTo(o1.getCreateTime()); // 都没有超时时间，按创建时间倒序
                    }
                } else {
                    // 如果updateTime为null，则使用createTime代替
                    Date o1Time = o1.getUpdateTime() != null ? o1.getUpdateTime() : o1.getCreateTime();
                    Date o2Time = o2.getUpdateTime() != null ? o2.getUpdateTime() : o2.getCreateTime();
                    return o2Time.compareTo(o1Time);
                }
            }
        });

        return AjaxResult.success(orderListResponses);
    }

    @PostMapping("/app/mix/after/list")
    @ResponseBody
    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);

       // 查询售后记录
        AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
        afterServiceRecord.setExcludeAfterServiceFinished(Boolean.TRUE);
        List<AfterServiceRecord> afterServiceRecordList = afterServiceRecordService
                .selectAfterServiceRecordList(afterServiceRecord);
        
        // 按子单ID分组售后记录
        Map<Long, List<AfterServiceRecord>> detailRecordMap = afterServiceRecordList.stream()
                .collect(Collectors.groupingBy(record -> record.getOrderDetailId()));
        
        // 获取有售后记录的子单ID列表
        List<Long> detailIds = afterServiceRecordList.stream()
                .map(AfterServiceRecord::getOrderDetailId)
                .distinct()
                .collect(Collectors.toList());


        // 需要排除同个师傅的主单子单同时出现
        List<OrderListResponse> filteredMasterList = masterList.stream()
                .filter(master -> {
                    // 查询该主单下所有售后中的子单
                    OrderDetail detailAfterListOfMasterQry = new OrderDetail();
                    detailAfterListOfMasterQry.setOrderMasterCode(master.getOrderMasterCode());
                    // 注意：这里使用getDetailAfterListLite方法，该方法只返回必要字段，性能更好
                    List<OrderListResponse> detailAfterList = this.getDetailAfterListLite(detailAfterListOfMasterQry, detailRecordMap,detailIds);
                  //  List<OrderListResponse> detailAfterList = this.getDetailAfterList(detailAfterListOfMasterQry);
                    
                    // 检查是否有其他师傅的售后单
                    boolean hasOtherWorkerAfterService = detailAfterList.stream()
                            .anyMatch(detail -> !detail.getWorkerId().equals(orderListRequest.getWorkerId()));
                    
                    if (hasOtherWorkerAfterService) {
                        // 检查是否有超时的售后单，如果有则标记主单为超时
                        boolean hasTimeout = detailAfterList.stream()
                                .anyMatch(detail -> detail.getAfterTimeout() != null && detail.getAfterTimeout() == 1);
                        if (hasTimeout) {
                            master.setAfterTimeout(1);
                        }
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());
        orderListResponses.addAll(filteredMasterList);

        // 根据更新时间倒序排列
        Collections.sort(orderListResponses, new Comparator<OrderListResponse>() {
            @Override
            public int compare(OrderListResponse o1, OrderListResponse o2) {
                // 如果updateTime为null，则使用createTime代替
                Date o1Time = o1.getUpdateTime() != null ? o1.getUpdateTime() : o1.getCreateTime();
                Date o2Time = o2.getUpdateTime() != null ? o2.getUpdateTime() : o2.getCreateTime();
                return o2Time.compareTo(o1Time);
            }
        });

        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(master.getGoodsId());
            if (goods.getDeptGoodsCategoryId() != null) {
                Long categoryId = null;
                // 前端发单和后台派单
                if (com.ghy.common.utils.StringUtils.isEmpty(orderMaster.getOrderMode())) {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                            .selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                } else {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                }
                if (categoryId != null) {
                    GoodsCategory one = goodsCategoryService.selectById(categoryId);
                    if (one != null && one.getParentCategoryId() != null) {
                        GoodsCategory two = goodsCategoryService.selectById(one.getParentCategoryId());
                        if (two != null && two.getParentCategoryId() != null) {
                            GoodsCategory three = goodsCategoryService.selectById(two.getParentCategoryId());
                            if (three != null) {
                                goods.setGoodsName(three.getGoodsCategoryName()
                                        + "-" + two.getGoodsCategoryName()
                                        + "-" + one.getGoodsCategoryName());
                            }
                        }
                    }
                }
            }
            // 财务信息
            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<AfterServiceRecord> mewAfterServiceRecords = new ArrayList<>();
            List<OrderDetail> detailOrderList = orderDetailService.selectByOrderMasterId(master.getId());
            boolean hasMatchingAfterService = false;
            detailOrderList.stream().forEach(detail -> {
                AfterServiceRecord afterServiceRecordQry = new AfterServiceRecord();
                afterServiceRecordQry.setOrderDetailId(detail.getId());
                afterServiceRecordQry.setExcludeAfterServiceFinished(Boolean.TRUE);
                List<AfterServiceRecord> records = afterServiceRecordService
                        .selectAfterServiceRecordList(afterServiceRecordQry);
                // 检查子单师傅ID是否与主单师傅ID一致且有售后记录
                afterServiceRecords.addAll(records);
                if (detail.getWorkerId() != null && detail.getWorkerId().equals(master.getWorkerId()) && !records.isEmpty()) {
                  mewAfterServiceRecords.addAll(records);
                }
            });
            // 设置是否显示售后记录字段
            if (!mewAfterServiceRecords.isEmpty()) {
                // 检查售后记录状态，如果存在afterServiceStatus不为1的记录，则显示售后记录按钮
                for (AfterServiceRecord record : mewAfterServiceRecords) {
                    if (record.getAfterServiceStatus() == null ||(record.getAfterServiceStatus() != 1 && record.getAfterServiceStatus() != 2)) {
                        hasMatchingAfterService = true;
                        break;
                    }
                }
            }

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

            if (worker != null) {
                orderListResponse.setWorkerId(worker.getWorkerId());
            }
            // 编辑返回属性
            orderListResponse.setIsNeedBill(master.getIsNeedBill());
            orderListResponse.setIsMonitoredOrder(master.getIsMonitoredOrder());
            orderListResponse.setOrderImages(master.getOrderImages());
            orderListResponse.setIsInvoiced(master.getIsInvoiced());
            orderListResponse.setOriginalWorkerId(master.getOriginalWorkerId());

            orderListResponse.setOrderType(master.getOrderType());
            orderListResponse.setHasServiceOrder(master.getHasServiceOrder());

            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.setRefundPayStatus(master.getRefundPayStatus());
            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.setShowAfterServiceRecord(hasMatchingAfterService ? 1 : 0);
            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(orderMaster.getGoodsId());
            if (goods.getDeptGoodsCategoryId() != null) {
                Long categoryId = null;
                // 前端发单和后台派单
                if (com.ghy.common.utils.StringUtils.isEmpty(orderMaster.getOrderMode())) {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                            .selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                } else {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                }
                if (categoryId != null) {
                    GoodsCategory one = goodsCategoryService.selectById(categoryId);
                    if (one != null && one.getParentCategoryId() != null) {
                        GoodsCategory two = goodsCategoryService.selectById(one.getParentCategoryId());
                        if (two != null && two.getParentCategoryId() != null) {
                            GoodsCategory three = goodsCategoryService.selectById(two.getParentCategoryId());
                            if (three != null) {
                                goods.setGoodsName(three.getGoodsCategoryName()
                                        + "-" + two.getGoodsCategoryName()
                                        + "-" + one.getGoodsCategoryName());
                            }
                        }
                    }
                }
            }
            // 财务信息
            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);
            }


            // 检查售后记录状态，决定是否显示售后记录按钮
            List<AfterServiceRecord> currentDetailRecords = detailRecordMap.get(detail.getId());
            int showAfterServiceRecord = 0;
            if (currentDetailRecords != null && !currentDetailRecords.isEmpty()) {
                // 遍历售后记录，如果存在afterServiceStatus不为1的记录，则显示售后记录按钮
                for (AfterServiceRecord record : currentDetailRecords) {
                    if (record.getAfterServiceStatus() == null ||
        (record.getAfterServiceStatus() != 1 && record.getAfterServiceStatus() != 2)) {
                        showAfterServiceRecord = 1;
                        break;
                    }
                }
            }
            orderListResponse.setShowAfterServiceRecord(showAfterServiceRecord);
            // 编辑返回属性
            orderListResponse.setRefundPayStatus(orderMaster.getRefundPayStatus());
            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());
            orderListResponse.setServiceShopId(orderMaster.getServiceShopId());
            orderListResponses.add(orderListResponse);
        });
        return orderListResponses;
    }

    /**
     * 轻量级售后订单查询方法
     * 只返回必要字段，提高查询性能
     * @param orderDetail 查询条件
     * @return 轻量级订单响应列表
     */
    public List<OrderListResponse> getDetailAfterListLite(OrderDetail orderDetail,Map<Long, List<AfterServiceRecord>> detailRecordMap,List<Long> detailIds) {
      
        
        // 设置查询条件
        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<OrderDetail> orderDetailList = orderDetailService.selectOrderDetailList(orderDetail);
        List<OrderListResponse> responseList = new ArrayList<>();
        
        for (OrderDetail detail : orderDetailList) {
            // 查询主单基本信息
            OrderMaster orderMaster = orderMasterService.selectById(detail.getOrderMasterId());
            if (orderMaster == null) continue;
            
            // 查询师傅信息
            Worker worker = workerService.selectById(detail.getWorkerId());
            String workerName = "";
            String workerId = "";
            if (worker != null) {
                workerId = worker.getWorkerId().toString();
               
            }
            
           
            
            // 检查是否显示售后记录和超时状态
            List<AfterServiceRecord> currentDetailRecords = detailRecordMap.get(detail.getId());
            int showAfterServiceRecord = 0;
            Integer afterTimeout = null;
            if (currentDetailRecords != null && !currentDetailRecords.isEmpty()) {
                for (AfterServiceRecord record : currentDetailRecords) {
                    if (record.getAfterServiceStatus() == null ||(record.getAfterServiceStatus() != 1 && record.getAfterServiceStatus() != 2)) {
                        showAfterServiceRecord = 1;
                    }
                 
                }
            }
            
            // 构建轻量级响应对象，只设置必要字段
            OrderListResponse response = new OrderListResponse();
            response.setOrderDetailId(detail.getId());
            response.setOrderMasterId(detail.getOrderMasterId());
            response.setOrderDetailCode(detail.getCode());
            response.setOrderMasterCode(detail.getOrderMasterCode());
            
            response.setWorkerName(workerName);
            response.setWorkerId(Long.valueOf(workerId)); // 必需字段，用于hasOtherWorkerAfterService判断
            
            response.setOrderStatus(detail.getOrderStatus());
            
            response.setShowAfterServiceRecord(showAfterServiceRecord);
            response.setAfterServiceRecordList(currentDetailRecords);
            response.setAfterTimeout(afterTimeout); // 必需字段，用于hasTimeout判断
            
            responseList.add(response);
        }
        
        return responseList;
    }

    public List<OrderListResponse> getMasterList(OrderMaster orderMaster) {
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        // 如果查询的是未约未排状态，只查询未全部派完的主单
        if (orderMaster.getOrderStatus() != null && OrderStatus.PLAIN.code() == orderMaster.getOrderStatus()) {
            orderMaster.setHasDispatchedAll(0);
        }
        
        if(orderMaster.getTimeout()!=null && orderMaster.getTimeout()>0){
            orderMaster.setOrderStatuses("1,2,4");
        }
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        List<Long> orderMasterIds = list.stream().map(OrderMaster::getId).collect(Collectors.toList());
        // 缓存 orderDetailMap
        OrderDetail masterIdsParam = new OrderDetail();
        masterIdsParam.setMasterIds(orderMasterIds);
        List<OrderDetail> orderDetailsList = orderDetailService.selectOrderDetailList(masterIdsParam);
        Map<Long, List<OrderDetail>> orderMasterIdsMap = orderDetailsList.stream()
                .collect(Collectors.groupingBy(OrderDetail::getOrderMasterId));

        // -- 都是同一个师傅的,师傅信息
        Worker worker = orderMaster.getWorkerId() != null ? workerService.selectById(orderMaster.getWorkerId()) : null;

        for (OrderMaster master : list) {// 初始化属性
            OrderListResponse orderListResponse = new OrderListResponse();
            List<OrderStandard> standardList = new ArrayList<>();
            // 查询所有子单
            List<OrderDetail> orderDetails = orderMasterIdsMap.get(master.getId());
            if (CollectionUtils.isEmpty(orderDetails)) {
                orderDetails = new ArrayList<>();
            }
            List<Long> orderDetailIds = orderDetails.stream().map(OrderDetail::getId).collect(Collectors.toList());

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

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

            Goods goods = goodsService.selectById(master.getGoodsId());
            // 填充商品三级类目
            if (goods.getDeptGoodsCategoryId() != null) {
                Long categoryId = null;
                // 前端发单和后台派单
                if (com.ghy.common.utils.StringUtils.isEmpty(orderMaster.getOrderMode())
                        || "01".equals(orderMaster.getConsultMode())) {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                            .selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                } else {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                }
                if (categoryId != null) {
                    GoodsCategory one = goodsCategoryService.selectById(categoryId);
                    if (one != null && one.getParentCategoryId() != null) {
                        GoodsCategory two = goodsCategoryService.selectById(one.getParentCategoryId());
                        if (two != null && two.getParentCategoryId() != null) {
                            GoodsCategory three = goodsCategoryService.selectById(two.getParentCategoryId());
                            if (three != null) {
                                goods.setGoodsName(three.getGoodsCategoryName()
                                        + "-" + two.getGoodsCategoryName()
                                        + "-" + one.getGoodsCategoryName());
                            }
                        }
                    }
                }
            }

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());

            // 查询加价价格
            BigDecimal changeMoney = BigDecimal.ZERO;
            List<FinancialChangeRecord> changeRecords = financialChangeRecordService
                    .selectByDetailIds(StringUtils.join(orderDetailIds, ","));
            for (FinancialChangeRecord changeRecord : changeRecords) {
                if (PayStatus.WAIT_PAY.getCode().equals(changeRecord.getPayStatus())) {
                    changeMoney = changeMoney.add(changeRecord.getChangeMoney());
                }
            }
            worker=workerService.selectById(master.getWorkerId());
            // 地址信息
            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<AfterServiceRecord> mewAfterServiceRecords = new ArrayList<>();
            List<OrderDetail> detailOrderList = orderDetailService.selectByOrderMasterId(master.getId());
            boolean hasMatchingAfterService = false;
            detailOrderList.stream().forEach(detail -> {
                AfterServiceRecord afterServiceRecordQry = new AfterServiceRecord();
                afterServiceRecordQry.setOrderDetailId(detail.getId());
                afterServiceRecordQry.setExcludeAfterServiceFinished(Boolean.TRUE);
                List<AfterServiceRecord> records = afterServiceRecordService
                        .selectAfterServiceRecordList(afterServiceRecordQry);
                // 检查子单师傅ID是否与主单师傅ID一致且有售后记录
                afterServiceRecords.addAll(records);
                if (detail.getWorkerId() != null && detail.getWorkerId()== master.getWorkerId()) {
                  mewAfterServiceRecords.addAll(records);
                }
            });
            // 设置是否显示售后记录字段
            if (!mewAfterServiceRecords.isEmpty()) {
                hasMatchingAfterService = true;
            }

            for (OrderGoods orderGoods : orderStandardList) {
                OrderStandard orderStandard = new OrderStandard();
                orderStandard.setStandardName(orderGoods.getGoodsName());
                orderStandard.setStandardNum(orderGoods.getGoodsNum());
                standardList.add(orderStandard);
            }
            boolean condition = (master.getAllSelfAssigned() == null || master.getAllSelfAssigned() == 0)
                    && (master.getOrderStatus() != null
                            && (master.getOrderStatus() == 0
                                    || master.getOrderStatus() == 1
                                    || master.getOrderStatus() == 2
                                    || master.getOrderStatus() == 3
                                    || master.getOrderStatus() == 4))
                    && master.getWorkerId() != null;

            orderListResponse.setIsDeliveryToStore(master.getIsDeliveryToStore());
            orderListResponse.setServiceShop(shopService.getShop(master.getServiceShopId()));



            // 编辑返回属性
            orderListResponse.setRefundPayStatus(master.getRefundPayStatus());
            orderListResponse.setServiceCancelled(master.getServiceCancelled());
            orderListResponse.setAfterPlatformServiceStatus(master.getAfterServiceStatus());
            orderListResponse.setShowInMonitor(master.getShowInMonitor());
            orderListResponse.setShowAfterServiceRecord(hasMatchingAfterService ? 1 : 0);
            orderListResponse.setWorkerRemark(master.getWorkerRemark());
            orderListResponse.setGoods(goods);
            orderListResponse.setIsNeedBill(master.getIsNeedBill());
            orderListResponse.setIsMonitoredOrder(master.getIsMonitoredOrder());
            orderListResponse.setOrderImages(master.getOrderImages());
            orderListResponse.setIsInvoiced(master.getIsInvoiced());
            orderListResponse.setOriginalWorkerId(master.getOriginalWorkerId());
            orderListResponse.setGoodsId(master.getGoodsId());
            orderListResponse.setServerGoodsId(master.getServerGoodsId());
            orderListResponse.setServiceShopId(master.getServiceShopId());
            orderListResponse.setOrderType(master.getOrderType());
            orderListResponse.setHasServiceOrder(master.getHasServiceOrder());
            orderListResponse.setIsMonitoredOrder(condition);
            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(financialMaster.getPayMoney());
            orderListResponse.setWorkerName(worker == null ? "" : worker.getName());
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            if (worker != null) {
                orderListResponse.setWorkerId(worker.getWorkerId());
            }
            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.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(master.getRemark());
            orderListResponse.setTimeout(master.getTimeout());
            orderListResponse.setTimeoutFineTimes(master.getTimeoutFineTimes());
            orderListResponse.setChangeMoney(changeMoney);
            orderListResponse.setServerMoney(financialMaster.getServerMoney());
            orderListResponse.setAfterServiceRecordList(afterServiceRecords);
            orderListResponse.setCreateTime(master.getCreateTime());
            orderListResponse.setUpdateTime(master.getUpdateTime());
            orderListResponse.setIsCall(master.getIsCall());
            orderListResponse.setConsultMode(master.getConsultMode());
            orderListResponse.setInsuranceId(master.getInsuranceId());
            if (master.getInsuranceId() != null) {
                InsuranceManager manager = insuranceManagerService.selectInsuranceManagerById(master.getInsuranceId());
                if (manager != null) {
                    orderListResponse.setInsuranceManager(manager);
                }
            }

            orderListResponse.setProvinceName(master.getProvinceName());
            orderListResponse.setCityName(master.getCityName());
            orderListResponse.setCountryName(master.getCountryName());
            orderListResponse.setStreetName(master.getStreetName());
            orderListResponse.setProvinceId(master.getProvinceId());
            orderListResponse.setCityId(master.getCityId());
            orderListResponse.setCountryId(master.getCountryId());
            orderListResponse.setStreetId(master.getStreetId());
            orderListResponse.setPhone(master.getPhone());
            orderListResponse.setName(master.getName());
            orderListResponse.setCustomerName(
                    StringUtils.isNotEmpty(master.getName()) ? master.getName() : customerAddress.getName());
            orderListResponse.setCustomerPhone(
                    StringUtils.isNotEmpty(master.getPhone()) ? master.getPhone() : customerAddress.getPhone());
            orderListResponse.setAddress(master.getAddress());
            String addressSysArea = sysArea.getMergerName();
            String[] array = addressSysArea.split(",");
            if (StringUtils.isEmpty(master.getProvinceName())) {
                orderListResponse.setProvinceName(array[0]);
                orderListResponse.setCityName(array[1]);
                orderListResponse.setCountryName(array[2]);
                if (array.length > 3) {
                    orderListResponse.setStreetName(array[3]);
                }
                orderListResponse.setProvinceId(customerAddress.getProvinceId());
                orderListResponse.setCityId(customerAddress.getCityId());
                orderListResponse.setCountryId(customerAddress.getCountryId());
                orderListResponse.setStreetId(customerAddress.getStreetId());
                orderListResponse.setPhone(customerAddress.getPhone());
                orderListResponse.setName(customerAddress.getName());
                orderListResponse.setAddress(completeAddress);
            }

            orderListResponses.add(orderListResponse);

        }
        return orderListResponses;
    }

    public List<OrderListResponse> getDetailList(OrderDetail orderDetail) {
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        List<OrderDetail> list = orderDetailService.selectOrderDetailList(orderDetail);
        for (OrderDetail detail : list) {// 主单信息
            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();
            }
            String masterWorkerName = "";
            String masterCompanyName = "";
            String masterCompanyPhone="";
            Worker masterWorker = workerService.selectById(orderMaster.getWorkerId());
            Worker goodsWorker =new Worker();
            OrderMaster goodsOrderMaster =null;
            WorkerCertification goodsWorkerRealInfo = null;
          
            // 消费者信息
            // Customer customer =
            // customerService.selectByCustomerId(orderMaster.getCustomerId());

            // 商品规格及信息
            if (orderMaster.getGoodsOrderMasterId() != null) {
                // 子单商品规格及信息
                goodsOrderMaster = orderMasterService.selectById(orderMaster.getGoodsOrderMasterId());
                goodsWorker = workerService.selectById(goodsOrderMaster.getWorkerId());
                goodsWorkerRealInfo = workerCertificationService.selectByWorkerId(goodsOrderMaster.getWorkerId());
                orderListResponse.setOriginalOrderMasterCode(goodsOrderMaster.getCode());
            }
            if (masterWorker != null) {
                // 大师傅实名信息
                workerRealInfo = workerCertificationService.selectByWorkerId(orderMaster.getWorkerId());
                masterWorkerName = workerRealInfo == null ? masterWorker.getName()
                        : workerRealInfo.getSurname() + workerRealInfo.getName();
                if (orderMaster.getGoodsOrderMasterId() != null) {
                    workerRealInfo=goodsWorkerRealInfo;
                }
                masterCompanyName = workerRealInfo == null ? null : workerRealInfo.getCompanyName();
                masterCompanyPhone=goodsWorker.getPhone();
                
            }
            orderListResponse.setMasterCompanyName(masterCompanyName);
            orderListResponse.setMasterCompanyPhone(masterCompanyPhone);
            orderListResponse.setMasterWorkerId(orderMaster.getWorkerId());
            orderListResponse.setMasterWorkerName(masterWorkerName);
            orderListResponse.setMasterWorkerPhone(masterWorker.getPhone());
            // 消费者信息
            // 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(orderMaster.getGoodsId());
            // 填充商品三级类目
            if (goods.getDeptGoodsCategoryId() != null) {
                Long categoryId = null;
                // 前端发单和后台派单
                if (com.ghy.common.utils.StringUtils.isEmpty(orderMaster.getOrderMode())) {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                            .selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                } else {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    }
                }
                if (categoryId != null) {
                    GoodsCategory one = goodsCategoryService.selectById(categoryId);
                    if (one != null && one.getParentCategoryId() != null) {
                        GoodsCategory two = goodsCategoryService.selectById(one.getParentCategoryId());
                        if (two != null && two.getParentCategoryId() != null) {
                            GoodsCategory three = goodsCategoryService.selectById(two.getParentCategoryId());
                            if (three != null) {
                                goods.setGoodsName(three.getGoodsCategoryName()
                                        + "-" + two.getGoodsCategoryName()
                                        + "-" + one.getGoodsCategoryName());
                            }
                        }
                    }
                }
            }

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

            // 查询子单加价记录
            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);
            }

            // 查询是否有拨号记录
            OrderCallRecord param = new OrderCallRecord();
            param.setOrderId(detail.getId());
            List<OrderCallRecord> callList = orderCallRecordService.selectOrderCallRecordList(param);
            if (CollectionUtils.isNotEmpty(callList)) {
                orderListResponse.setIsCall("02");
            } else {
                orderListResponse.setIsCall("1");
            }

            // 售后记录
            AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
            afterServiceRecord.setOrderDetailId(detail.getId());
         //   afterServiceRecord.setExcludeAfterServiceFinished(true);
            List<AfterServiceRecord> afterServiceRecordList
            =afterServiceRecordService.selectAfterServiceRecordList(afterServiceRecord);     
          
            int showAfterServiceRecord = 0;
            if (afterServiceRecordList != null && !afterServiceRecordList.isEmpty()) {
                // 遍历售后记录，如果存在afterServiceStatus不为1且不为2的记录，则显示售后记录按钮
                for (AfterServiceRecord record : afterServiceRecordList) {
                    if (record.getAfterServiceStatus() == null || 
                        (record.getAfterServiceStatus() != 1 && record.getAfterServiceStatus() != 2)) {
                        showAfterServiceRecord = 1;
                        break;
                    }
                }
            }
            orderListResponse.setShowAfterServiceRecord(showAfterServiceRecord);
            if(orderMaster.getIsDeliveryToStore()!=null&&orderMaster.getIsDeliveryToStore()==1){
                orderListResponse.setIsDeliveryToStore(1);
                orderListResponse.setServiceShopId(orderMaster.getServiceShopId());
                orderListResponse.setServiceShop(shopService.getShop(orderMaster.getServiceShopId()));
            }
             
            // 编辑返回属性
            orderListResponse.setRefundPayStatus(orderMaster.getRefundPayStatus());
            orderListResponse.setAfterPlatformServiceStatus(detail.getAfterServiceStatus());
            orderListResponse.setWorkerRemark(detail.getWorkerRemark());
            orderListResponse.setGoods(goods);
            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.setPayMoney(financialDetail.getPayMoney());
            orderListResponse.setWorkerName(worker.getName());
            orderListResponse.setWorkerPhone(worker.getPhone());
            orderListResponse.setWorkerId(detail.getWorkerId());
            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.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.setClockInLocation(detail.getClockInLocation());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            orderListResponse.setOrderType(detail.getOrderType());
            orderListResponse.setTimeout(detail.getTimeout());
            orderListResponse.setTimeoutFineTimes(detail.getTimeoutFineTimes());
            orderListResponse.setAfterTimeout(detail.getAfterTimeout());
            orderListResponse.setChangeMoney(changeMoney);
            orderListResponse.setCreateTime(detail.getCreateTime());
            orderListResponse.setUpdateTime(detail.getUpdateTime());
            
            // 查询最新超时时间
            OrderTimeoutRecord timeoutRecord = orderFineRecordService.selectByDetailIdAndStatus(detail.getId(), null);
            List<OrderTimeoutRecord> timeoutRecords = timeoutRecord == null ? Collections.emptyList() : Collections.singletonList(timeoutRecord);
            if (CollectionUtils.isNotEmpty(timeoutRecords)) {
                // 按创建时间倒序排列，取最新的超时记录
                timeoutRecords.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
                orderListResponse.setTimeoutTime(timeoutRecords.get(0).getCreateTime());
            }
            orderListResponse.setConsultMode(orderMaster.getConsultMode());
            orderListResponse.setInsuranceId(orderMaster.getInsuranceId());

            orderListResponse.setProvinceName(orderMaster.getProvinceName());
            orderListResponse.setCityName(orderMaster.getCityName());
            orderListResponse.setCountryName(orderMaster.getCountryName());
            orderListResponse.setStreetName(orderMaster.getStreetName());
            orderListResponse.setProvinceId(orderMaster.getProvinceId());
            orderListResponse.setCityId(orderMaster.getCityId());
            orderListResponse.setCountryId(orderMaster.getCountryId());
            orderListResponse.setStreetId(orderMaster.getStreetId());
            orderListResponse.setPhone(orderMaster.getPhone());
            orderListResponse.setName(orderMaster.getName());
            orderListResponse.setCustomerName(orderMaster.getName());
            orderListResponse.setCustomerPhone(orderMaster.getPhone());
            orderListResponse.setAddress(orderMaster.getAddress());
            String addressSysArea = sysArea.getMergerName();
            String[] array = addressSysArea.split(",");
            if (StringUtils.isEmpty(orderMaster.getProvinceName())) {
                orderListResponse.setProvinceName(array[0]);
                orderListResponse.setCityName(array[1]);
                orderListResponse.setCountryName(array[2]);
                if (array.length > 3) {
                    orderListResponse.setStreetName(array[3]);
                }
                orderListResponse.setProvinceId(customerAddress.getProvinceId());
                orderListResponse.setCityId(customerAddress.getCityId());
                orderListResponse.setCountryId(customerAddress.getCountryId());
                orderListResponse.setStreetId(customerAddress.getStreetId());
                orderListResponse.setPhone(customerAddress.getPhone());
                orderListResponse.setName(customerAddress.getName());
                orderListResponse.setAddress(completeAddress);
            }

            if (orderMaster.getInsuranceId() != null) {
                InsuranceManager manager = insuranceManagerService
                        .selectInsuranceManagerById(orderMaster.getInsuranceId());
                if (manager != null) {
                    orderListResponse.setInsuranceManager(manager);
                }
            }
             orderListResponse.setAfterServiceRecordList(afterServiceRecordList);
            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;
    }

    /**
     * 为配件订单生成对应的服务订单
     *
     * @param request 包含主单ID和服务金额的请求参数
     * @return AjaxResult 返回生成的服务订单信息
     */
    @PostMapping("/generate/service/order")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult generateServiceOrder(@RequestBody OrderMaster request) {
        try {
            Long orderMasterId = request.getId();
            BigDecimal serviceMoney = request.getServerGoodsMoney();
            Long serviceShopId = request.getServiceShopId();

            // 校验参数
            if (orderMasterId == null) {
                return AjaxResult.error("主单ID不能为空");
            }

            if (serviceMoney == null || serviceMoney.compareTo(BigDecimal.ZERO) < 0) {
                return AjaxResult.error("服务金额不能为空且不能为负数");
            }

            if (serviceShopId == null) {
                return AjaxResult.error("服务店铺ID不能为空");
            }

            // 查询配件主单信息
            OrderMaster accessoryOrderMaster = orderMasterService.selectById(orderMasterId);
            if (accessoryOrderMaster == null) {
                return AjaxResult.error("主单不存在");
            }
            // 判断是否为配件订单
            if (accessoryOrderMaster.getOrderType() == null || accessoryOrderMaster.getOrderType() != 1) {
                return AjaxResult.error("当前订单不是配件订单，无法生成服务订单");
            }

            // 检查是否已经派发过服务订单
            if (accessoryOrderMaster.getHasServiceOrder() != null && accessoryOrderMaster.getHasServiceOrder() == 1) {
                return AjaxResult.error("该配件订单已经派发过服务订单，不能重复操作");
            }

            Worker worker = workerService.selectById(accessoryOrderMaster.getWorkerId());
            String phone = worker.getPhone();

            // 获取服务店铺信息
            Shop serviceShop = shopService.getShop(serviceShopId);
            if (serviceShop == null) {
                return AjaxResult.error("服务店铺不存在");
            }

            accessoryOrderMaster.setServiceShopId(serviceShopId);
            // 设置服务主单未撤销标识
            accessoryOrderMaster.setServiceCancelled(0);
            orderMasterService.updateOrderMaster(accessoryOrderMaster);

            // 获取服务店铺的师傅信息（创建店铺的师傅）
            Worker serviceWorker = workerService.selectById(serviceShop.getWorkerId());
            if (serviceWorker == null) {
                return AjaxResult.error("服务店铺未关联师傅信息");
            }

            // 获取服务店铺的第一个服务商品并生成OrderGoods
            // 查询服务店铺的服务商品
            Goods queryGoods = new Goods();
            queryGoods.setShopId(serviceShopId);
            queryGoods.setType(1); // 1表示服务类型
            List<Goods> serviceGoodsList = goodsService.selectGoodsList(queryGoods);

            // 创建服务主单
            OrderMaster serviceOrderMaster = new OrderMaster();
            serviceOrderMaster.setGoodsId(serviceGoodsList.size() > 0 ? serviceGoodsList.get(0).getGoodsId() : null);
            serviceOrderMaster.setGoods(serviceGoodsList.size() > 0 ? serviceGoodsList.get(0) : null);
            serviceOrderMaster.setDeptId(accessoryOrderMaster.getDeptId());
            serviceOrderMaster.setCode(orderMasterService.createOrderCode());
            serviceOrderMaster.setOrderType(0); // 服务订单类型为0
            serviceOrderMaster.setPayType(accessoryOrderMaster.getPayType());
            serviceOrderMaster.setOrderStatus(OrderStatus.RECEIVE.code());
            serviceOrderMaster.setCustomerId(accessoryOrderMaster.getCustomerId());
            serviceOrderMaster.setAddressId(accessoryOrderMaster.getAddressId());
            serviceOrderMaster.setPayStatus(PayStatus.WAIT_PAY.getCode());
            serviceOrderMaster.setCreateTime(new Date());
            serviceOrderMaster.setUpdateTime(new Date());
            serviceOrderMaster.setWorkerId(serviceWorker.getWorkerId()); // 使用服务店铺的师傅ID
            serviceOrderMaster.setServiceShopId(serviceShopId); // 设置服务店铺ID
            serviceOrderMaster.setRemark("由配件订单[" + accessoryOrderMaster.getCode()
                    + "]自动生成的服务订单，接单后请约客户上门服务，服务费用已在订单内，完单后会自行结算，请勿重复向客户收取。服务时不要讲产品负面话题，不要生硬推销！杜绝一切不合常理的行为！服务客户过程中有任何问题可致电商品/配件店铺"
                    + phone + "【致电时按商品信息说明是该商品安装服务方】");
            serviceOrderMaster.setExpectTimeStart(accessoryOrderMaster.getExpectTimeStart());
            serviceOrderMaster.setExpectTimeEnd(accessoryOrderMaster.getExpectTimeEnd());
            serviceOrderMaster.setInsuranceId(accessoryOrderMaster.getInsuranceId());
            serviceOrderMaster.setGoodsOrderMasterId(orderMasterId);
            // 设置原始师傅ID（配件订单的师傅ID）
            serviceOrderMaster.setOriginalWorkerId(accessoryOrderMaster.getWorkerId());
            // 设置服务商品金额
            serviceOrderMaster.setServerGoodsMoney(serviceMoney);
            

            // 复制地址信息
            serviceOrderMaster.setProvinceId(accessoryOrderMaster.getProvinceId());
            serviceOrderMaster.setCityId(accessoryOrderMaster.getCityId());
            serviceOrderMaster.setCountryId(accessoryOrderMaster.getCountryId());
            serviceOrderMaster.setStreetId(accessoryOrderMaster.getStreetId());
            serviceOrderMaster.setAddress(accessoryOrderMaster.getAddress());
            serviceOrderMaster.setName(accessoryOrderMaster.getName());
            serviceOrderMaster.setPhone(accessoryOrderMaster.getPhone());
            serviceOrderMaster.setProvinceName(accessoryOrderMaster.getProvinceName());
            serviceOrderMaster.setCityName(accessoryOrderMaster.getCityName());
            serviceOrderMaster.setCountryName(accessoryOrderMaster.getCountryName());
            serviceOrderMaster.setStreetName(accessoryOrderMaster.getStreetName());

            // 保存服务主单
            orderMasterService.insertOrderMaster(serviceOrderMaster);
            Assert.notNull(serviceOrderMaster.getId(), "ServiceOrderMaster.id is null!");

            // 生成财务主单（使用传入的服务金额）
            FinancialMaster serviceFinancialMaster = new FinancialMaster(
                    financialMasterService.createCode(),
                    accessoryOrderMaster.getDeptId(),
                    serviceOrderMaster.getId(),
                    serviceOrderMaster.getCode(),
                    serviceMoney,
                    BigDecimal.ZERO,
                    serviceMoney);
            serviceFinancialMaster.setServerMoney(serviceMoney);
            financialMasterService.insertFinancialMaster(serviceFinancialMaster);
            Assert.notNull(serviceFinancialMaster.getId(), "ServiceFinancialMaster.id is null!");

            // 从配件订单财务主单中扣除服务金额
            FinancialMaster accessoryFinancialMaster = financialMasterService.selectByOrderMasterId(accessoryOrderMaster.getId());
            if (accessoryFinancialMaster != null) {
                BigDecimal currentServerMoney = accessoryFinancialMaster.getServerMoney();
                if (currentServerMoney == null) {
                    currentServerMoney = BigDecimal.ZERO;
                }
                
                // 检查扣除后金额是否为负数
                BigDecimal newServerMoney = currentServerMoney.subtract(serviceMoney);
                if (newServerMoney.compareTo(BigDecimal.ZERO) < 0) {
                    throw new RuntimeException("配件订单财务主单服务金额不足，无法扣除服务金额。当前服务金额：" + currentServerMoney + "，需扣除：" + serviceMoney);
                }
                
                // 更新配件订单财务主单的serverMoney
                accessoryFinancialMaster.setServerMoney(newServerMoney);
                financialMasterService.updateFinancialMaster(accessoryFinancialMaster);
                
                
            } else {
                logger.warn("配件订单[{}]未找到对应的财务主单，无法扣除服务金额", accessoryOrderMaster.getCode());
            }

            // 获取配件订单的商品信息
            List<OrderGoods> accessoryOrderGoodsList = orderGoodsService.selectByOrderMasterId(accessoryOrderMaster.getId());
            if (!CollectionUtils.isEmpty(accessoryOrderGoodsList)) {
                OrderGoods firstAccessoryGoods = accessoryOrderGoodsList.get(0); // 取第一个配件商品
                OrderGoods serviceOrderGoods = new OrderGoods();
                serviceOrderGoods.setOrderId(serviceOrderMaster.getId());
                serviceOrderGoods.setGoodsStandardId(firstAccessoryGoods.getGoodsStandardId()); // 使用配件商品的标准ID
                serviceOrderGoods.setGoodsName(firstAccessoryGoods.getGoodsName()); // 使用配件商品的名称
                serviceOrderGoods.setGoodsNum(firstAccessoryGoods.getGoodsNum()); // 使用配件商品的数量
                serviceOrderGoods.setRemark("由配件订单[" + accessoryOrderMaster.getCode() + "]自动生成的服务商品，服务金额：" + serviceMoney);
                serviceOrderGoods.setCreateTime(new Date());

                // 保存OrderGoods
                orderGoodsService.insertOrderGoods(serviceOrderGoods);
                logger.info("为服务订单[{}]生成服务商品[{}]，商品标准ID：{}，数量：{}，金额：{}",
                        serviceOrderMaster.getCode(), firstAccessoryGoods.getGoodsName(),
                        firstAccessoryGoods.getGoodsStandardId(), firstAccessoryGoods.getGoodsNum(), serviceMoney);
            } else {
                logger.warn("配件订单[{}]没有找到商品信息，无法生成OrderGoods", accessoryOrderMaster.getCode());
            }

            // 更新配件主单，关联生成的服务订单并标记已派发服务订单
            OrderMaster accessoryUpdate = new OrderMaster();
            accessoryUpdate.setId(accessoryOrderMaster.getId());
            accessoryUpdate.setRemark(accessoryOrderMaster.getRemark() + " [已生成服务订单:" + serviceOrderMaster.getCode()
                    + "，服务金额：" + serviceMoney + "]");
            accessoryUpdate.setHasServiceOrder(1); // 标记已派发服务订单
            orderMasterService.updateOrderMaster(accessoryUpdate);

            // 通知服务师傅新订单
            try {
                Map<String, Object> paramsNew = new HashMap<>();
                paramsNew.put("thing21", "您帐号收到1条新服务订单");
                paramsNew.put("thing31", "请进入【我的订单--新订单】操作处理");
                CustomerAddress address = customerAddressService
                        .selectByCustomerAddressId(serviceOrderMaster.getAddressId());
                paramsNew.put("thing14", address.getName());
                paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), serviceWorker.getWxOpenId(),
                        WxMsgEnum.NORMAL_ORDER, paramsNew);
            } catch (Exception e) {
                logger.error("发送微信通知失败: {}", e.getMessage(), e);
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("accessoryOrderId", accessoryOrderMaster.getId());
            result.put("accessoryOrderCode", accessoryOrderMaster.getCode());
            result.put("serviceOrderId", serviceOrderMaster.getId());
            result.put("serviceOrderCode", serviceOrderMaster.getCode());
            result.put("serviceFee", serviceMoney);
            result.put("serviceShopId", serviceShopId);
            result.put("serviceShopName", serviceShop.getShopName());
            result.put("serviceWorkerId", serviceWorker.getWorkerId());
            result.put("serviceWorkerName", serviceWorker.getName());
            result.put("serviceWorkerPhone", serviceWorker.getPhone());

            logger.info("成功为配件订单[{}]生成服务订单[{}]，服务金额：{}，服务店铺：{},更新时间为{}",
                    accessoryOrderMaster.getCode(), serviceOrderMaster.getCode(), serviceMoney,
                    serviceShop.getShopName(), serviceOrderMaster.getUpdateTime());

            return AjaxResult.success("服务订单生成成功", result);

        } catch (Exception e) {
            logger.error("生成服务订单失败: {}", e.getMessage(), e);
            return AjaxResult.error("生成服务订单失败: " + e.getMessage());
        }
    }

    /**
     * 根据快递单号查询物流信息
     *
     * @param request 物流查询请求
     * @return 物流信息
     */
    @PostMapping("/logistics/query")
    @ResponseBody
    public AjaxResult queryLogistics(@RequestBody LogisticsQueryRequest request) {
        try {
            LogisticsInfo logisticsInfo = logisticsService.queryLogistics(request);
            return AjaxResult.success("查询成功", logisticsInfo);
        } catch (Exception e) {
            logger.error("查询物流信息失败: {}", e.getMessage(), e);
            return AjaxResult.error("查询物流信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据快递单号查询物流信息（简化版）
     *
     * @param trackingNumber 快递单号
     * @return 物流信息
     */
    @GetMapping("/logistics/query/{trackingNumber}")
    @ResponseBody
    public AjaxResult queryLogisticsByNumber(@PathVariable String trackingNumber) {
        try {
            LogisticsInfo logisticsInfo = logisticsService.queryLogistics(trackingNumber);
            return AjaxResult.success("查询成功", logisticsInfo);
        } catch (Exception e) {
            logger.error("查询物流信息失败: {}", e.getMessage(), e);
            return AjaxResult.error("查询物流信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据订单ID查询物流信息
     *
     * @param orderId 订单ID
     * @return 物流信息
     */
    @GetMapping("/logistics/query/order/{orderId}")
    @ResponseBody
    public AjaxResult queryLogisticsByOrderId(@PathVariable Long orderId) {
        try {
            LogisticsInfo logisticsInfo = logisticsService.queryLogisticsByOrderId(orderId);
            return AjaxResult.success("查询成功", logisticsInfo);
        } catch (Exception e) {
            logger.error("查询物流信息失败: {}", e.getMessage(), e);
            return AjaxResult.error("查询物流信息失败: " + e.getMessage());
        }
    }
}
