package com.ghy.web.controller.order;

import cn.hutool.core.date.DateUtil;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.annotation.Log;
import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.PageDomain;
import com.ghy.common.core.page.TableSupport;
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.*;
import com.ghy.common.utils.poi.ExcelUtil;
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.service.*;
import com.ghy.order.domain.*;
import com.ghy.order.request.OrderChangePriceReq;
import com.ghy.order.request.SysOrderAssignRequest;
import com.ghy.order.request.SysOrderGoodsStandards;
import com.ghy.order.request.TransferOrderRequest;
import com.ghy.order.service.*;

import com.ghy.payment.domain.FinancialChangeRecord;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.ghy.payment.service.AdapayService;
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.web.pojo.vo.*;
import com.ghy.web.service.InsuranceService;
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 io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 主订单API
 *
 * @author HH 2022/4/25
 */
@Controller
@RequestMapping("/order/master")
public class OrderMasterController extends BaseController {

    /**
     * 批量下单导入模板下载（服务端转发，避免浏览器混合内容限制）
     */
    @GetMapping("/importTemplate")
    public void downloadBatchImportTemplate(HttpServletResponse response) throws IOException {
        String remoteUrl = "https://gqz.opsoul.com/%E6%89%B9%E9%87%8F%E4%B8%8B%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls";

        HttpURLConnection conn = null;
        InputStream in = null;
        ServletOutputStream out = null;
        try {
            URL url = new URL(remoteUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);
            conn.setRequestMethod("GET");

            int status = conn.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK) {
                response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "远程模板下载失败");
                return;
            }

            response.setContentType("application/vnd.ms-excel");
            String fileName = "批量下单导入模板.xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            in = conn.getInputStream();
            out = response.getOutputStream();

            byte[] buffer = new byte[8192];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    private final String prefix = "order/master";

    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private GoodsAreaService goodsAreaService;
    @Resource
    private WorkerService workerService;
    @Resource
    private IWorkerCertificationService workerCertificationService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private CustomerAddressService addressService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsImgsService goodsImgsService;
    @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;
    @Resource
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private IOrderCallRecordService orderCallRecordService;

    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private FinancialDetailService financialDetailService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private OrderFineRecordService orderFineRecordService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private IAfterServiceRecordService afterServiceRecordService;
    @Resource
    private FinancialChangeRecordService financialChangeRecordService;
    @Resource
    private CustomerAddressService customerAddressService;
    @Resource
    private AdapayService adapayService;
    @Resource
    private IOrderAttachmentRecordService orderAttachmentRecordService;
    @Resource
    private InsuranceService insuranceService;
    @Resource
    private ShopService shopService;
    @Autowired
    private BaiduMapUtils baiduMapUtils;
    @Resource
    private IInsuranceManagerService insuranceManagerService;

    @PostMapping("/orderInsurance")
    @ResponseBody
    public AjaxResult orderInsurance(@RequestParam(value = "orderCode") String orderCode) {
        try {
            insuranceService.orderInsurance(orderCode);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("保险未响应，请再次点击操作，或稍等再试【本单联通保险公司系统，操作此按键时开始投保，偶遇未响应，请间隔一两分钟再次点接单即可！】");
        }
    }

    @GetMapping("/changePrice/{orderIds}")
    public String changePrice(@PathVariable("orderIds") String orderIds, ModelMap mmap) {
        mmap.put("orderIds", orderIds);
        return "order/batchChangePrice";
    }

    @PostMapping(value = "batchChangePrice")
    @ResponseBody
    public AjaxResult batchChangePrice(@Validated OrderChangePriceReq changePriceReq) {
        return orderMasterService.batchChangePrice(changePriceReq);
    }

    // @RequiresPermissions("order:master:view")
    @GetMapping()
    public String orderMaster() {
        return prefix;
    }

    @PostMapping("/changeIsCharge")
    @ResponseBody
    public AjaxResult changeIsCharge(OrderMaster orderMaster) {
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

    @PostMapping("/changeIsContact")
    @ResponseBody
    public AjaxResult changeIsContact(OrderMaster orderMaster) {
        return toAjax(orderMasterService.updateOrderMaster(orderMaster));
    }

    /**
     * 修改订单开票状态
     *
     * @param orderMaster 订单对象，包含id和isInvoiced字段
     * @return 操作结果
     */
    @PostMapping("/changeInvoiceStatus")
    @ResponseBody
    @Log(title = "订单开票状态管理", businessType = BusinessType.UPDATE)
    public AjaxResult changeInvoiceStatus(@RequestBody OrderMaster orderMaster) {
        try {
            if (orderMaster.getId() == null) {
                return AjaxResult.error("订单ID不能为空");
            }
            if (orderMaster.getIsInvoiced() == null) {
                return AjaxResult.error("开票状态不能为空");
            }

            // 只更新开票状态字段
            OrderMaster updateOrder = new OrderMaster();
            updateOrder.setId(orderMaster.getId());
            updateOrder.setIsInvoiced(orderMaster.getIsInvoiced());
            // updateOrder.setUpdateBy(getLoginName());

            int result = orderMasterService.updateOrderMaster(updateOrder);
            if (result > 0) {
                String statusDesc = orderMaster.getIsInvoiced() == 1 ? "已开票" : "未开票";
                return AjaxResult.success("订单开票状态已更新为：" + statusDesc);
            } else {
                return AjaxResult.error("更新失败，请检查订单是否存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 修改订单是否需要开票状态
     *
     * @param orderMaster 订单对象，包含id和isNeedBill字段
     * @return 操作结果
     */
    @PostMapping("/changeNeedBillStatus")
    @ResponseBody
    @Log(title = "订单是否需要开票状态管理", businessType = BusinessType.UPDATE)
    public AjaxResult changeNeedBillStatus(@RequestBody OrderMaster orderMaster) {
        try {
            if (orderMaster.getId() == null) {
                return AjaxResult.error("订单ID不能为空");
            }
            if (orderMaster.getIsNeedBill() == null) {
                return AjaxResult.error("是否需要开票状态不能为空");
            }

            // 只更新是否需要开票状态字段
            OrderMaster updateOrder = new OrderMaster();
            updateOrder.setId(orderMaster.getId());
            updateOrder.setIsNeedBill(orderMaster.getIsNeedBill());
            updateOrder.setUpdateBy(getLoginName());

            int result = orderMasterService.updateOrderMaster(updateOrder);
            if (result > 0) {
                String statusDesc = orderMaster.getIsNeedBill() == 1 ? "需要开票" : "不需要开票";
                return AjaxResult.success("订单是否需要开票状态已更新为：" + statusDesc);
            } else {
                return AjaxResult.error("更新失败，请检查订单是否存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 订单转单功能
     *
     * @param request 转单请求对象
     * @return 操作结果
     */
    @PostMapping("/transferOrder")
    @ResponseBody
    @Log(title = "订单转单管理", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult transferOrder(@RequestBody TransferOrderRequest request) {
        try {
            // 参数校验
            if (request.getOrderId() == null) {
                return AjaxResult.error("订单ID不能为空");
            }

            // 查询原订单信息
            OrderMaster originalOrder = orderMasterService.selectById(request.getOrderId());
            if (originalOrder == null) {
                return AjaxResult.error("订单不存在");
            }

            // 检查订单状态是否允许转单
            if (originalOrder.getOrderStatus() == null || originalOrder.getOrderStatus() > OrderStatus.RECEIVE.code()) {
                return AjaxResult.error("订单状态不允许转单，只有待接单、已接单、待上门、进行中状态的订单可以转单");
            }

            // 如果指定了新师傅，检查新师傅是否存在
            Worker newWorker = null;
            if (request.getNewWorkerId() != null) {
                newWorker = workerService.selectById(request.getNewWorkerId());
                if (newWorker == null) {
                    return AjaxResult.error("新师傅不存在");
                }

                // 如果原师傅和新师傅相同，则不允许转单
                if (originalOrder.getWorkerId() != null
                        && originalOrder.getWorkerId().equals(request.getNewWorkerId())) {
                    return AjaxResult.error("新师傅不能与原师傅相同");
                }
            }

            // 查询原财务主单
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(request.getOrderId());
            if (financialMaster == null) {
                return AjaxResult.error("订单财务信息不存在");
            }

            // 处理转单金额
            if (request.getTransferAmount() != null) {
                BigDecimal originalAmount = financialMaster.getServerMoney();
                BigDecimal transferAmount = request.getTransferAmount();

                // 验证转单金额
                if (transferAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    return AjaxResult.error("转单金额必须大于0");
                }
                if (transferAmount.compareTo(originalAmount) > 0) {
                    return AjaxResult.error("转单金额不能超过原订单金额");
                }

                // 计算差价
                BigDecimal differenceAmount = originalAmount.subtract(transferAmount);

                // 更新主单金额
                financialMaster.setServerMoney(transferAmount);
                financialMaster.setPayMoney(transferAmount);
                financialMaster.setRemark("订单转单，原金额：" + originalAmount + "，新金额：" + transferAmount);
                financialMasterService.updateFinancialMaster(financialMaster);

                // 如果有差价，创建差额子单记录
                if (differenceAmount.compareTo(BigDecimal.ZERO) > 0 && originalOrder.getWorkerId() != null) {
                    FinancialDetail differenceDetail = new FinancialDetail();
                    differenceDetail.setFinancialMasterId(financialMaster.getId());
                    differenceDetail.setPayeeId(originalOrder.getWorkerId()); // 原师傅
                    differenceDetail.setPayMoney(differenceAmount);
                    differenceDetail.setFinancialDetailType(FinancialDetailType.TRANSFER_DIFFERENCE_FEE.getCode());
                    differenceDetail.setRemark("转单差价，原师傅获得");
                    financialDetailService.insertFinancialDetail(differenceDetail);

                    logger.info("创建转单差价记录：订单ID={}, 原师傅ID={}, 差价金额={}",
                            request.getOrderId(), originalOrder.getWorkerId(), differenceAmount);
                }
            }

            // 执行转单操作
            OrderMaster updateOrder = new OrderMaster();
            updateOrder.setId(request.getOrderId());

            // 保存原师傅ID到originalWorkerId字段
            if (originalOrder.getWorkerId() != null) {
                updateOrder.setOriginalWorkerId(originalOrder.getWorkerId());
            }

            // 设置新师傅ID（可以为null，表示进入接单大厅）
            if (request.getNewWorkerId() == null) {
                updateOrder.setWorkerId(-1L);
            } else {
                updateOrder.setWorkerId(request.getNewWorkerId());
            }
            // updateOrder.setUpdateBy(getLoginName());

            // 构建转单备注
            String newRemark = originalOrder.getRemark() != null ? originalOrder.getRemark() : "";
            String transferInfo = "【转单记录：" +
                    "于" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date());

            if (request.getNewWorkerId() != null) {
                transferInfo += "转单给师傅ID:" + request.getNewWorkerId();
            } else {
                transferInfo += "转单到接单大厅";
            }

            if (request.getTransferAmount() != null) {
                transferInfo += "，转单金额:" + request.getTransferAmount();
            }

            if (StringUtils.isNotEmpty(request.getTransferReason())) {
                transferInfo += "，原因:" + request.getTransferReason();
            }

            transferInfo += "】";
            updateOrder.setRemark(newRemark + transferInfo);

            int result = orderMasterService.updateOrderMaster(updateOrder);

            if (result > 0) {
                // 记录转单日志
                logger.info("订单转单成功：订单ID={}, 原师傅ID={}, 新师傅ID={}, 转单金额={}, 操作人={}",
                        request.getOrderId(),
                        originalOrder.getWorkerId(),
                        request.getNewWorkerId(),
                        request.getTransferAmount());

                String message;
                if (request.getNewWorkerId() != null) {
                    message = String.format("转单成功！订单已从师傅[%s]转给师傅[%s]",
                            originalOrder.getWorkerId() != null ? originalOrder.getWorkerId() : "无",
                            newWorker.getName());
                } else {
                    message = "转单成功！订单已转入接单大厅";
                }

                if (request.getTransferAmount() != null) {
                    message += "，转单金额：" + request.getTransferAmount();
                }

                return AjaxResult.success(message);
            } else {
                return AjaxResult.error("转单失败，请重试");
            }
        } catch (Exception e) {
            logger.error("订单转单失败：{}", e.getMessage(), e);
            return AjaxResult.error("转单失败：" + e.getMessage());
        }
    }

    /**
     * 修改详细订单
     */
    @GetMapping("/payQrcode/{orderId}")
    public String payQrcode(@PathVariable("orderId") String orderId, ModelMap mmap) {
        mmap.put("orderId", orderId);
        return "order/master-qrcode";
    }

    @GetMapping("/pc")
    public String orderPcMaster() {
        return "order/pc-master";
    }

    @GetMapping("/manager")
    public String orderManager() {
        return "order/orderManager";
    }

    @GetMapping("/pcOrderWorker/{orderIds}")
    public String addMasterQrPay(@PathVariable(value = "orderIds") String orderIds, ModelMap mmap) {
        // 不知道为啥参数可能会带上双引号 这里去掉再转Long
        orderIds = orderIds.replace("\"", "");
        List<Worker> workList = workerService.getWorkList(new Worker());
        mmap.put("orderIds", orderIds);
        mmap.put("workers", workList);
        return "order/pcOrderWorker";
    }

    @GetMapping("/batchChangeInsurance/{orderIds}")
    public String batchChangeInsurance(@PathVariable(value = "orderIds") String orderIds, ModelMap mmap) {
        // 不知道为啥参数可能会带上双引号 这里去掉再转Long
        orderIds = orderIds.replace("\"", "");
        List<InsuranceManager> insuranceManagers = insuranceManagerService
                .selectInsuranceManagerList(new InsuranceManager());
        mmap.put("orderIds", orderIds);
        mmap.put("insurances", insuranceManagers);
        return "order/batchPcOrderInsurance";
    }

    @GetMapping("/pcOrderInsurance/{orderIds}")
    public String pcOrderInsurance(@PathVariable(value = "orderIds") String orderIds, ModelMap mmap) {
        // 不知道为啥参数可能会带上双引号 这里去掉再转Long
        orderIds = orderIds.replace("\"", "");
        List<InsuranceManager> insuranceManagers = insuranceManagerService
                .selectInsuranceManagerList(new InsuranceManager());
        mmap.put("orderIds", orderIds);
        mmap.put("insurances", insuranceManagers);
        return "order/pcOrderInsurance";
    }

    @PostMapping("/pcOrderWorker/batchChangeInsurance")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchChangeInsurance(OrderMaster orderMaster) {
        String[] orderIdArr = orderMaster.getOrderMasterIds().split(",");
        for (String id : orderIdArr) {
            // 原单
            OrderMaster master = orderMasterService.selectById(Long.valueOf(id));
            if (master == null || master.getInsuranceId() != null) {
                return AjaxResult.error(master.getCode() + "订单已经选择过保险了!");
            }
        }
        // 查询保险信息
        InsuranceManager insuranceManager = insuranceManagerService
                .selectInsuranceManagerById(orderMaster.getInsuranceId());
        if (insuranceManager == null) {
            return AjaxResult.error("保险信息有误!");
        }

        for (String id : orderIdArr) {
            // 原单
            OrderMaster master = orderMasterService.selectById(Long.valueOf(id));
            if (master == null || master.getInsuranceId() != null) {
                return AjaxResult.error(master.getCode() + "订单已经选择过保险了!");
            }
            // 修改主单金额 财务单总金额增加 平台金额增加
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
            financialMaster.setPayMoney(financialMaster.getPayMoney().add(insuranceManager.getInsuranceAmount()));
            financialMaster.setTotalMoney(financialMaster.getTotalMoney().add(insuranceManager.getInsuranceAmount()));
            financialMasterService.updateFinancialMaster(financialMaster);
            // 修改子单
            List<FinancialDetail> details = financialDetailService.selectByFinancialMasterIdAndType(
                    financialMaster.getId(), FinancialDetailType.PLATFORM_FEE.getCode());
            if (CollectionUtils.isNotEmpty(details)) {
                FinancialDetail detail = details.get(0);
                detail.setPayMoney(detail.getPayMoney().add(insuranceManager.getInsuranceAmount()));
                financialDetailService.updateFinancialDetail(detail);
            }
            // 修改主单保险内容
            OrderMaster param = new OrderMaster();
            param.setId(master.getId());
            param.setInsuranceId(orderMaster.getInsuranceId());
            orderMasterService.updateOrderMaster(param);
        }
        return AjaxResult.success();
    }

    @PostMapping("/pcOrderWorker/changeInsurance")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeInsurance(OrderMaster orderMaster) {
        // 原单
        OrderMaster master = orderMasterService.selectById(orderMaster.getId());
        if (master == null || master.getInsuranceId() != null) {
            return AjaxResult.error("订单已经选择过保险了!");
        }
        // 查询保险信息
        InsuranceManager insuranceManager = insuranceManagerService
                .selectInsuranceManagerById(orderMaster.getInsuranceId());
        if (insuranceManager == null) {
            return AjaxResult.error("保险信息有误!");
        }
        // 修改主单金额 财务单总金额增加 平台金额增加
        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
        financialMaster.setPayMoney(financialMaster.getPayMoney().add(insuranceManager.getInsuranceAmount()));
        financialMaster.setTotalMoney(financialMaster.getTotalMoney().add(insuranceManager.getInsuranceAmount()));
        financialMasterService.updateFinancialMaster(financialMaster);
        // 修改子单
        List<FinancialDetail> details = financialDetailService.selectByFinancialMasterIdAndType(financialMaster.getId(),
                FinancialDetailType.PLATFORM_FEE.getCode());
        if (CollectionUtils.isNotEmpty(details)) {
            FinancialDetail detail = details.get(0);
            detail.setPayMoney(detail.getPayMoney().add(insuranceManager.getInsuranceAmount()));
            financialDetailService.updateFinancialDetail(detail);
        }
        // 修改主单保险内容
        orderMasterService.updateOrderMaster(orderMaster);
        return AjaxResult.success();
    }

    @PostMapping("/assign")
    @ResponseBody
    public AjaxResult assign(@RequestBody OrderMaster orderMaster) {
        OrderMaster param = new OrderMaster();
        param.setOrderMasterIds(orderMaster.getOrderMasterIds());
        List<OrderMaster> masters = orderMasterService.selectOrderMasterList(param);
        long count = masters.stream().filter(x -> !x.getOrderStatus().equals(OrderStatus.RECEIVE.code())).count();
        if (count > 0) {
            return AjaxResult.error("请选择待接单且无师傅接单订单指派");
        }
        masters.forEach(master -> {
            OrderMaster updateEntity = new OrderMaster();
            updateEntity.setId(master.getId());
            updateEntity.setWorkerId(orderMaster.getWorkerId());
            orderMasterService.updateOrderMaster(updateEntity);
            // 推送公众号通知数据。
            try {
                Worker assignWorker = workerService.selectById(orderMaster.getWorkerId());
                // 消息组装。
                Map<String, Object> paramsNew = new HashMap<>();
                // 订单编号
                paramsNew.put("thing21", "您帐号收到1条新订单");
                // 名称
                paramsNew.put("thing31", "请进入【我的订单--新订单】操作处理");
                CustomerAddress address = customerAddressService.selectByCustomerAddressId(master.getAddressId());
                paramsNew.put("thing14", address.getName());
                // 预约时间
                paramsNew.put("time4", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm",
                        master.getExpectTimeStart()));
                // 消息推送
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), assignWorker.getWxOpenId(),
                        WxMsgEnum.NORMAL_ORDER, paramsNew);
            } catch (Exception e) {
                // 暂时不做任何操作。
                logger.error(e.getMessage(), e);
            }

        });
        return AjaxResult.success();
    }

    @PostMapping("/importData")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysOrderRequest> util = new ExcelUtil<SysOrderRequest>(SysOrderRequest.class);
        List<SysOrderRequest> jsonObjects = util.importExcel(file.getInputStream());
        boolean flag = false;
        for (SysOrderRequest model : jsonObjects) {
            if ("序号".equals(model.getSeq())) {
                flag = true;
                continue;
            }
            if (flag) {
                sysOrder(format(model));
            }
        }
        return AjaxResult.success(jsonObjects);
    }

    public SysOrderAssignRequest format(SysOrderRequest orderRequest) throws Exception {
        SysOrderAssignRequest request = new SysOrderAssignRequest();
        if (StringUtils.isEmpty(orderRequest.getSeq())) {
            throw new Exception("导入表格序号,序号不能为空!");
        }
        if (StringUtils.isEmpty(orderRequest.getName())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",姓名不能为空!");
        }
        if (StringUtils.isEmpty(orderRequest.getPrice())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",I列，发布价格填写不能为空！");
        }
        try {
            Integer.parseInt(orderRequest.getPrice());
        } catch (Exception e) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",I列，发布价格不能有小数点！");
        }
        if (StringUtils.isEmpty(orderRequest.getNum())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",H列，数量填写不能为空！");
        }
        try {
            Integer.parseInt(orderRequest.getNum());
        } catch (Exception e) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",H列，数量不能含小数点。");
        }
        if (StringUtils.isEmpty(orderRequest.getLastCategory())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",C列，四级类目不能为空！");
        }
        request.setCustomerName(orderRequest.getName());
        if (StringUtils.isEmpty(orderRequest.getPhone())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",导入手机号不能为空!");
        }
        request.setCustomerPhone(orderRequest.getPhone());
        request.setServDate(orderRequest.getDate());
        request.setServTime(orderRequest.getTime());
        request.setGoodsBrand(orderRequest.getBrand());
        request.setRemark(orderRequest.getRemark());
        if (StringUtils.isEmpty(orderRequest.getMode())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",G列，下单模式名称有误/或带有其它字符！");
        } else {
            if (orderRequest.getMode().contains("-")) {
                String orderModel = orderRequest.getMode().split("-")[0];
                String payType = orderRequest.getMode().split("-")[1];
                if ("带价下单".equals(orderModel)) {
                    request.setOrderMode("02");
                } else if ("一票价".equals(orderModel)) {
                    request.setOrderMode("01");
                } else {
                    throw new Exception("导入表格序号" + orderRequest.getSeq() + ",G列，下单模式名称有误/或带有其它字符！");
                }
                if ("到付".equals(payType)) {
                    request.setPayMode("01");
                } else {
                    request.setPayMode("02");
                }
            } else {
                if ("带价下单".equals(orderRequest.getMode())) {
                    request.setOrderMode("02");
                    request.setPayMode("02");
                } else if ("一票价".equals(orderRequest.getMode())) {
                    request.setOrderMode("01");
                    request.setPayMode("02");
                } else {
                    throw new Exception("导入表格序号" + orderRequest.getSeq() + ",G列，下单模式名称有误/或带有其它字符！");
                }
            }

        }

        if (StringUtils.isEmpty(orderRequest.getPrice())) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",I列，发布价格填写不能为空！\n");
        }
        request.setPrice(new BigDecimal(orderRequest.getPrice()));
        request.setVideoUrl(orderRequest.getUrl());
        request.setImageUrl("https://gqz.opsoul.com/default.jpeg");
        List<SysOrderGoodsStandards> goodsStandards = new ArrayList<>();
        String[] categoryNames = orderRequest.getCategory().split("-");
        if (categoryNames.length != 3) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",B列，三级类目名称有误/或格式有误！");
        } else {
            if (StringUtils.isEmpty(categoryNames[0]) || StringUtils.isEmpty(categoryNames[1])
                    || StringUtils.isEmpty(categoryNames[2])) {
                throw new Exception("导入表格序号" + orderRequest.getSeq() + ",B列，三级类目名称有误/或格式有误！");
            }
            try {
                // 第一层
                GoodsCategory param1 = new GoodsCategory();
                param1.setGoodsCategoryName(categoryNames[0]);
                GoodsCategory category1 = goodsCategoryService.selectGoodsCategoryList(param1).get(0);
                // 第二层
                GoodsCategory param2 = new GoodsCategory();
                param2.setParentCategoryId(category1.getGoodsCategoryId());
                param2.setGoodsCategoryName(categoryNames[1]);
                GoodsCategory category2 = goodsCategoryService.selectGoodsCategoryList(param2).get(0);
                // 第三层
                GoodsCategory param3 = new GoodsCategory();
                param3.setParentCategoryId(category2.getGoodsCategoryId());
                param3.setGoodsCategoryName(categoryNames[2]);
                GoodsCategory category3 = goodsCategoryService.selectGoodsCategoryList(param3).get(0);

                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                        .selectOneByGoodsCategoryId(category3.getGoodsCategoryId());
                request.setCategoryId3(deptGoodsCategory.getDeptGoodsCategoryId());

                // 第四层
                GoodsCategory param4 = new GoodsCategory();
                param4.setParentCategoryId(category3.getGoodsCategoryId());
                param4.setGoodsCategoryName(orderRequest.getLastCategory());
                List<GoodsCategory> categories = goodsCategoryService.selectGoodsCategoryList(param4);
                if (CollectionUtils.isEmpty(categories)) {
                    param4.setGoodsCategoryName(null);
                    categories = goodsCategoryService.selectGoodsCategoryList(param4);
                }
                GoodsCategory category4 = categories.get(0);

                SysOrderGoodsStandards standards = new SysOrderGoodsStandards();
                DeptGoodsCategory deptGoodsCategory2 = deptGoodsCategoryService
                        .selectOneByGoodsCategoryId(category4.getGoodsCategoryId());
                standards.setDeptCategoryId(deptGoodsCategory2.getDeptGoodsCategoryId());
                standards.setGoodsStandardNum(Integer.parseInt(orderRequest.getNum()));
                standards.setGoodsStandardName(orderRequest.getLastCategory());
                goodsStandards.add(standards);
            } catch (Exception e) {
                throw new Exception("导入表格序号" + orderRequest.getSeq() + ",B列，三级类目名称有误/或格式有误！");
            }

        }
        request.setOrderGoodsStandards(goodsStandards);
        String[] addressName = orderRequest.getAddress().split("-");
        if (addressName.length == 1) {
            addressName = orderRequest.getAddress().split("，");
            if (addressName.length == 1) {
                addressName = orderRequest.getAddress().split(" ");
            }
            if (addressName.length == 1) {
                addressName = orderRequest.getAddress().split("/");
            }
        }
        if (addressName.length < 4) {
            throw new Exception("导入表格序号" + orderRequest.getSeq() + ",L列，服务地址不能为空或分隔符不能少于3个！");
        } else {
            // 省
            SysArea param1 = new SysArea();
            param1.setAreaName(addressName[0]);
            SysArea area1 = sysAreaService.selectSysAreaList(param1).get(0);
            request.setProvinceId(area1.getAreaId());

            // 市
            SysArea param2 = new SysArea();
            param2.setAreaName(addressName[1]);
            param2.setParentCode(area1.getAreaCode());
            SysArea area2 = sysAreaService.selectSysAreaList(param2).get(0);
            request.setCityId(area2.getAreaId());

            // 区
            SysArea param3 = new SysArea();
            param3.setAreaName(addressName[2]);
            param3.setParentCode(area2.getAreaCode());
            SysArea area3 = sysAreaService.selectSysAreaList(param3).get(0);
            request.setDistrictId(area3.getAreaId());

            // 详细地址
            if (addressName.length == 5) {
                request.setFullAddress(addressName[3] + addressName[4]);
            } else {
                request.setFullAddress(addressName[3]);
            }

        }
        return request;
    }

    public synchronized void sysOrder(@RequestBody SysOrderAssignRequest request) throws Exception {

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

        // 判断是否有客户
        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
                || org.apache.commons.lang3.StringUtils.isBlank(request.getFullAddress())) {
            throw new Exception("请填写地址");
        }

        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.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(list.getGoodsStandardName());
            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.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 (getSysUser() != null) {
            orderMaster.setCreateBy(getSysUser().getUserId().toString());
        }
        if (StringUtils.isEmpty(request.getServDate())) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 1);
            String dateStr = DateUtil.format(calendar.getTime(), "yyyy-MM-dd");
            orderMaster.setExpectTimeStart(DateUtil.parse(dateStr + " 08:00", "yyyy-MM-dd HH:mm"));
            orderMaster.setExpectTimeEnd(DateUtil.parse(dateStr + " 10:00", "yyyy-MM-dd HH:mm"));
        } else {
            // 服务时间
            String[] split = request.getServTime().split("-");
            try {
                orderMaster.setExpectTimeStart(org.apache.commons.lang3.time.DateUtils
                        .parseDate(request.getServDate() + " " + split[0], "yyyy-MM-dd hh:mm"));
                orderMaster.setExpectTimeEnd(org.apache.commons.lang3.time.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);
        }
        logger.info("下单成成");
    }

    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);
    }

    @GetMapping("/orderWorker/{orderId}")
    public String orderWorker(@PathVariable("orderId") Long orderId, ModelMap mmap) {
        List<Worker> workList = workerService.getWorkList(new Worker());
        mmap.put("orderId", orderId);
        mmap.put("workers", workList);
        return "order/orderWorker";
    }

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

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody OrderMaster orderMaster) {
        logger.info("appList orderMaster:{}", orderMaster);
        // TableDataInfo rspData = new TableDataInfo();
        List<OrderListResponse> orderListResponses = new ArrayList<>();
        // 入参中的城市id存在时，查询符合条件的地址id
        if (CollectionUtils.isNotEmpty(orderMaster.getDistrictIds())
                || CollectionUtils.isNotEmpty(orderMaster.getCityIds())
                || CollectionUtils.isNotEmpty(orderMaster.getStreetIds())) {

            CustomerAddress customerAddress = new CustomerAddress();
            customerAddress.setDistrictIds(orderMaster.getDistrictIds());
            customerAddress.setCityIds(orderMaster.getCityIds());
            customerAddress.setStreetIds(orderMaster.getStreetIds());
            customerAddress.setNeedNameFlag(true);
            List<CustomerAddress> addressList = addressService.getCustomerAddressList(customerAddress);
            orderMaster.setAddressIds(
                    addressList.stream().map(CustomerAddress::getCustomerAddressId).collect(Collectors.toList()));
            if (CollectionUtils.isEmpty(orderMaster.getAddressIds())) {
                return voDataTable(orderListResponses, new ArrayList<>());
            }
        }
        
        // 移除startPage()调用，查询所有数据
        // startPage();
        // if (orderMaster.getOrderStatus()==OrderStatus.FINISH_CHECK.code()){
        // orderMaster.setOrderStatuses();
        // }
       if (orderMaster.getOrderType() != null && orderMaster.getOrderType() == 0&&orderMaster.getFrom().equals("customer")) {
          orderMaster.setExcludeGoodsOrder(true);
        }
        
        // 查询所有数据，不进行分页
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        orderMaster.setPageNum(null);
        orderMaster.setPageSize(null);
       List<OrderMaster> countList = orderMasterService.selectOrderMasterList(orderMaster);
        
        // 处理orderType为0的情况，额外查询原师傅ID相关的订单
        OrderMaster origiOrderMaster = new OrderMaster();
        if (orderMaster.getOrderType() == 0 && orderMaster.getWorkerId() != null
                && orderMaster.getWorkerId() != -1 && orderMaster.getIsMonitoredOrder() == true) {
            origiOrderMaster.setOriginalWorkerId(orderMaster.getWorkerId());
            origiOrderMaster.setOrderStatuses("0,1,2,3,4");
            List<OrderMaster> originalList = orderMasterService.selectOrderMasterList(origiOrderMaster);
            list.addAll(originalList);
            countList.addAll(originalList);
        }
        
        // 合并数据后去重（根据订单ID）
        Map<Long, OrderMaster> uniqueOrderMap = new LinkedHashMap<>();
        for (OrderMaster order : list) {
            uniqueOrderMap.put(order.getId(), order);
        }

        List<OrderMaster> uniqueList = new ArrayList<>(uniqueOrderMap.values());
        
        uniqueOrderMap = new LinkedHashMap<>();
        for (OrderMaster order : countList) {
            uniqueOrderMap.put(order.getId(), order);
        }
        countList = new ArrayList<>(uniqueOrderMap.values());

        List<Long> filterCityIds = orderMaster.getCityIds();
        Long filterCityId = orderMaster.getCityId();
        if ((filterCityIds != null && !filterCityIds.isEmpty()) || filterCityId != null) {
            Set<Long> citySet = new HashSet<>();
            if (filterCityIds != null) {
                citySet.addAll(filterCityIds);
            }
            if (filterCityId != null) {
                citySet.add(filterCityId);
            }
            uniqueList = uniqueList.stream()
                    .filter(o -> o.getCityId() != null && citySet.contains(o.getCityId()))
                    .collect(Collectors.toList());
            countList = countList.stream()
                    .filter(o -> o.getCityId() != null && citySet.contains(o.getCityId()))
                    .collect(Collectors.toList());
        }

        // 按创建时间排序
        uniqueList.sort((o1, o2) -> {
            if (o1.getUpdateTimeAlias() == null && o2.getUpdateTimeAlias() == null) return 0;
            if (o1.getUpdateTimeAlias() == null) return 1;
            if (o2.getUpdateTimeAlias() == null) return -1;
            return o2.getUpdateTimeAlias().compareTo(o1.getUpdateTimeAlias());
        });
        
        // 获取分页参数（从HTTP请求中获取）
        // 注意：这里不能使用startPage()，因为我们要查询所有数据进行手动分页
        // 获取分页参数（从PageDomain中获取）
        // PageDomain pageDomain = TableSupport.buildPageRequest();
        // Integer pageNum = pageDomain.getPageNum() != null ? pageDomain.getPageNum() : orderMaster.getPageNum();
        // Integer pageSize = pageDomain.getPageSize() != null ? pageDomain.getPageSize() : orderMaster.getPageSize();
        
        // // 手动分页
        // int totalCount = uniqueList.size();
        // int startIndex = (pageNum - 1) * pageSize;
        // int endIndex = Math.min(startIndex + pageSize, totalCount);
        
        // List<OrderMaster> pagedList;
        // if (startIndex >= totalCount) {
        //     pagedList = new ArrayList<>();
        // } else {
        //     pagedList = uniqueList.subList(startIndex, endIndex);
        // }

        if (CollectionUtils.isEmpty(uniqueList)) {
            return voDataTable(orderListResponses, new ArrayList<>());
        }

        // 优化1：收集所有需要查询的ID，避免重复查询
        Set<Long> workerIds = new HashSet<>();
        Set<Long> addressIds = new HashSet<>();
        Set<Long> goodsIds = new HashSet<>();

        uniqueList.forEach(master -> {
            if (master.getWorkerId() != null) {
                workerIds.add(master.getWorkerId());
            }
            if (master.getAddressId() != null) {
                addressIds.add(master.getAddressId());
            }
            if (master.getGoodsId() != null) {
                goodsIds.add(master.getGoodsId());
            }
        });

        // 优化2：批量查询常用数据，避免循环中的重复查询
        Map<Long, Worker> workerMap = new HashMap<>();
        Map<Long, CustomerAddress> addressMap = new HashMap<>();
        Map<Long, Goods> goodsMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(workerIds)) {
            List<Worker> workers = workerService.selectByIds(workerIds);
            workers.forEach(worker -> workerMap.put(worker.getWorkerId(), worker));
        }

        if (!CollectionUtils.isEmpty(addressIds)) {
            // 使用批量查询方法优化性能
            List<CustomerAddress> addresses = addressService.selectByIds(new ArrayList<>(addressIds));
            addresses.forEach(address -> addressMap.put(address.getCustomerAddressId(), address));
        }

        if (!CollectionUtils.isEmpty(goodsIds)) {
            List<Goods> goodsList = goodsService.selectByIds(goodsIds);
            goodsList.forEach(goods -> goodsMap.put(goods.getGoodsId(), goods));
        }
        
        uniqueList.forEach(master -> {
            // 子单
            List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(master.getId());

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

            // 优化3：使用预查询的师傅信息
            Worker worker = workerMap.get(master.getWorkerId());

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

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderMasterId(master.getId());
            Goods goods = new Goods();
//            if (orderStandardList.size() > 0) {
//                // 商品信息
//                GoodsStandard goodsStandard = goodsStandardService
//                        .selectById(orderStandardList.get(0).getGoodsStandardId());
//                if (goodsStandard != null) {
//                    goods = goodsService.selectById(goodsStandard.getGoodsId());
//                }
//            } else {
            // 优化4：使用预查询的商品信息
            goods = goodsMap.getOrDefault(master.getGoodsId(), new Goods());
//            }
            if(master.getGoodsOrderMasterId() != null){
                OrderMaster goodsOrderMaster = orderMasterService.selectById(master.getGoodsOrderMasterId());
                //goods = goodsService.selectById(goodsOrderMaster.getGoodsId());
                orderStandardList=orderGoodsService.selectByOrderMasterId(goodsOrderMaster.getId());
            }

            // 填充商品三级类目
            if (goods.getDeptGoodsCategoryId() != null) {
                Long categoryId = null;
                // 前端发单和后台派单
                if (com.ghy.common.utils.StringUtils.isEmpty(master.getOrderMode())) {
                    DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                            .selectOneByGoodsCategoryId(goods.getDeptGoodsCategoryId());
                    if (deptGoodsCategory != null) {
                        categoryId = deptGoodsCategory.getGoodsCategoryId();
                    } else {
                        categoryId = goods.getDeptGoodsCategoryId();
                    }
                } 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) {
                                master.setConsoleGoodsName(three.getGoodsCategoryName()
                                        + "-" + two.getGoodsCategoryName()
                                        + "-" + one.getGoodsCategoryName());
                            }
                        }
                    }
                }
            }

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(master.getId());
            BigDecimal totalPayMoney = financialMaster.getPayMoney();
            BigDecimal totalChangeMoney = new BigDecimal(0);
            BigDecimal paymentMoney = BigDecimal.ZERO;
            if (financialMaster.getPayStatus() == 1) {
                paymentMoney = paymentMoney.add(financialMaster.getPayMoney());
            }
            List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService
                    .selectByMasterId(master.getId());
            BigDecimal changePaymentMoney = financialChangeRecords.stream()
                    .filter(record -> record.getPayStatus() == 1)
                    .map(FinancialChangeRecord::getChangeMoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            paymentMoney = paymentMoney.add(changePaymentMoney);

            for (OrderDetail detail : detailList) {
                // 查询子单加价记录
                FinancialChangeRecord record = financialChangeRecordService
                        .selectNotPayRecordByDetailId(detail.getId());

                if (record != null) {
                    totalChangeMoney = totalChangeMoney.add(record.getChangeMoney());
                }
                OrderAttachmentRecord param = new OrderAttachmentRecord();
                param.setOrderDetailId(detail.getId());
                List<OrderAttachmentRecord> orderAttachmentRecordList = orderAttachmentRecordService
                        .selectOrderAttachmentRecordList(param);
                for (OrderAttachmentRecord orderAttachmentRecord : orderAttachmentRecordList) {
                    if (record != null && record.getPayStatus() == 0) {
                        totalChangeMoney = totalChangeMoney.add(orderAttachmentRecord.getAttachMoney());
                    } else {
                        paymentMoney = paymentMoney.add(orderAttachmentRecord.getAttachMoney());
                    }
                }
            }
            // 优化5：使用预查询的地址信息
            CustomerAddress customerAddress = addressMap.get(master.getAddressId());
            if (customerAddress == null) {
                customerAddress = new CustomerAddress();
            }
            SysArea sysArea;
            if (customerAddress.getStreetId() != null) {
                sysArea = sysAreaService.selectById(customerAddress.getStreetId());
            } else {
                sysArea = sysAreaService.selectById(customerAddress.getCountryId());
            }
            String completeAddress = "";
            if (sysArea != null) {
                completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();
            }

            // 优化6：避免重复查询订单详情
            List<AfterServiceRecord> afterServiceRecords = new ArrayList<>();
            // 直接使用已经查询的detailList，避免重复查询
            detailList.forEach(detail -> {
                AfterServiceRecord afterServiceRecordQry = new AfterServiceRecord();
                afterServiceRecordQry.setOrderDetailId(detail.getId());
                List<AfterServiceRecord> records = afterServiceRecordService
                        .selectAfterServiceRecordList(afterServiceRecordQry);
                afterServiceRecords.addAll(records);
            });

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

            // 获取商品主单信息
            if (master.getGoodsOrderMasterId() != null) {
                OrderMaster goodsOrderMaster = orderMasterService.selectById(master.getGoodsOrderMasterId());
                if (goodsOrderMaster != null && goodsOrderMaster.getWorkerId() != null) {
                    Worker goodsWorker = workerService.selectById(goodsOrderMaster.getWorkerId());
                    if (goodsWorker != null) {
                        // 获取师傅实名认证信息
                        WorkerCertification workerCertification = workerCertificationService.selectByWorkerId(goodsWorker.getWorkerId());
                        String masterCompanyName = workerCertification == null ? null : workerCertification.getCompanyName();
                        String masterWorkerPhone = goodsWorker.getPhone();
                        
                        orderListResponse.setMasterCompanyName(masterCompanyName);
                        orderListResponse.setMasterWorkerPhone(masterWorkerPhone);
                    }
                }
            }
             orderListResponse.setServiceCancelled(master.getServiceCancelled());
             orderListResponse.setServiceShopId(master.getServiceShopId());
             orderListResponse.setGoods(goods);
            // 编辑返回属性
            orderListResponse.setIsDeliveryToStore(master.getIsDeliveryToStore());
            orderListResponse.setGoodsOrderMasterId(master.getGoodsOrderMasterId());
            orderListResponse.setWorkerRemark(master.getWorkerRemark());
            orderListResponse.setIsNeedBill(master.getIsNeedBill());
            orderListResponse.setIsMonitoredOrder(master.getIsMonitoredOrder());
            orderListResponse.setOrderImages(master.getOrderImages());
            orderListResponse.setIsInvoiced(master.getIsInvoiced());
            orderListResponse.setOriginalWorkerId(master.getOriginalWorkerId());
            orderListResponse.setWorkerRemark(master.getWorkerRemark());
            orderListResponse.setOrderType(master.getOrderType());
            orderListResponse.setHasServiceOrder(master.getHasServiceOrder());
            orderListResponse.setPaymentMoney(paymentMoney);
            orderListResponse.setGoodsBrand(master.getGoodsBrand());
            orderListResponse.setGoodsSpecification(master.getGoodsSpecification());
            orderListResponse.setOrderMasterId(master.getId());
            orderListResponse.setGoodsName(master.getConsoleGoodsName());
            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(
                    org.apache.commons.lang3.StringUtils.isNotEmpty(master.getName()) ? master.getName()
                            : customerAddress.getName());
            orderListResponse.setCustomerPhone(
                    org.apache.commons.lang3.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(financialMaster.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.setServerMoney(master.getServerMoney());
            orderListResponse.setIsCall(master.getIsCall());
            if (StringUtils.isNotEmpty(master.getProvinceName())) {
                orderListResponse.setProvinceId(master.getProvinceId());
                orderListResponse.setCityId(master.getCityId());
                orderListResponse.setCountryId(master.getCountryId());
                orderListResponse.setPhone(master.getPhone());
                orderListResponse.setName(master.getName());
                orderListResponse.setProvinceName(master.getProvinceName());
                orderListResponse.setCityName(master.getCityName());
                orderListResponse.setCountryName(master.getCountryName());
                orderListResponse.setStreetId(master.getStreetId());
                orderListResponse.setStreetName(master.getStreetName());
                orderListResponse.setAddress(master.getAddress());
            } else {
                if (!StringUtils.isEmpty(customerAddress.getStreetId() + "")) {
                    String addressSysArea = sysArea != null ? sysArea.getMergerName() : "";
                    String[] array = addressSysArea.split(",");
                    if (array.length > 0) {
                        orderListResponse.setProvinceName(array[0]);
                    }
                    if (array.length > 1) {
                        orderListResponse.setCityName(array[1]);
                    }
                    if (array.length == 3) {
                        orderListResponse.setCountryName(array[2]);
                    }
                    if (array.length == 4) {
                        orderListResponse.setStreetName(array[3]);
                    }
                }
                orderListResponse.setProvinceId(customerAddress.getProvinceId());
                orderListResponse.setCityId(customerAddress.getCityId());
                orderListResponse.setCountryId(customerAddress.getCountryId());
                orderListResponse.setStreetId(orderMaster.getStreetId());
                orderListResponse.setAddress(customerAddress.getAddress());
                orderListResponse.setPhone(customerAddress.getPhone());
                orderListResponse.setName(customerAddress.getName());
            }
            orderListResponses.add(orderListResponse);
        });
        return voDataTable(orderListResponses, countList);
    }

    @PostMapping("/app/count")
    @ResponseBody
    public AjaxResult countAppList(@RequestBody OrderMaster orderMaster) {
        
        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }

    @PostMapping("/after/list")
    @ResponseBody
    public TableDataInfo afterList(@RequestBody 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");
        }

        startPage();
        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());

            // 财务信息
            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();

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

            // 编辑返回属性
            orderListResponse.setOrderMasterId(master.getId());
            orderListResponse.setGoods(goods);
            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(
                    org.apache.commons.lang3.StringUtils.isNotEmpty(master.getName()) ? master.getName()
                            : customerAddress.getName());
            orderListResponse.setCustomerPhone(
                    org.apache.commons.lang3.StringUtils.isNotEmpty(master.getPhone()) ? master.getPhone()
                            : customerAddress.getPhone());
            orderListResponse.setServerTime(master.getRevTime());
            orderListResponse.setExpectTimeStart(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(master.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(master.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(master.getExpectTimeEnd());
            orderListResponse.setOrderStatus(master.getOrderStatus());
            orderListResponse.setPayStatus(master.getPayStatus());
            orderListResponse.setPayType(master.getPayType());
            orderListResponse.setOrderMasterCode(master.getCode());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(master.getRemark());
            orderListResponse.setTimeout(master.getTimeout());
            orderListResponse.setTimeoutFineTimes(master.getTimeoutFineTimes());
            orderListResponses.add(orderListResponse);

        });

        // PageDomain pageDomain = TableSupport.buildPageRequest();
        // if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize()) {
        // rspData.setRows(orderListResponses);
        // rspData.setTotal(orderListResponses.size());
        // return rspData;
        // }
        // Integer pageSize = pageDomain.getPageNum();
        // if (pageSize > orderListResponses.size()) {
        // pageSize = orderListResponses.size();
        // }
        // rspData.setRows(orderListResponses.subList(0, pageSize));
        // rspData.setTotal(orderListResponses.size());
        return voDataTable(orderListResponses, list);
    }

    @PostMapping("/after/count")
    @ResponseBody
    public AjaxResult countAfterList(@RequestBody 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");
        }

        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }

    @PostMapping("/after/dispute/count")
    @ResponseBody
    public AjaxResult countAfterDisputeList(@RequestBody OrderMaster orderMaster) {
        // 查所有售后纠纷的单
        // AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
        // afterServiceRecord.setExcludeAfterServiceFinished(Boolean.TRUE);
        // // 只查询售后纠纷的记录（客户不同意的记录）
        // afterServiceRecord.setCustomerFinalCheck(0L); // 客户不同意
        // 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");
        // }
          orderMaster.setAfterServiceStatus(1);
        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }

    @PostMapping("/after/records/byMasterId")
    @ResponseBody
    public AjaxResult getAfterServiceRecordsByMasterId(@RequestBody OrderMaster orderMaster) {
        try {
            logger.info("查询主单[{}]的售后纠纷记录", orderMaster.getId());

            // 查询主单下的所有子单
            OrderDetail orderDetail = new OrderDetail();
            List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(orderMaster.getId());

            if (orderDetailList.isEmpty()) {
                logger.info("主单[{}]没有子单", orderMaster.getId());
                return AjaxResult.success(new ArrayList<>());
            }

            // 获取所有子单ID
            List<Long> orderDetailIds = orderDetailList.stream()
                    .map(OrderDetail::getId)
                    .collect(Collectors.toList());

            logger.info("主单[{}]的子单IDs: {}", orderMaster.getId(), orderDetailIds);

            // 使用IN查询一次性获取所有售后纠纷记录
            AfterServiceRecord queryRecord = new AfterServiceRecord();
            queryRecord.setCustomerFinalCheck(0L); // 客户不同意
            queryRecord.setExcludeAfterServiceFinished(Boolean.TRUE); // 排除已完成的售后

            // 构建子单ID的IN查询条件
            StringBuilder orderDetailIdsStr = new StringBuilder();
            for (int i = 0; i < orderDetailIds.size(); i++) {
                if (i > 0) {
                    orderDetailIdsStr.append(",");
                }
                orderDetailIdsStr.append(orderDetailIds.get(i));
            }

            // 设置子单ID列表用于IN查询
            queryRecord.setOrderDetailIds(orderDetailIdsStr.toString());

            List<AfterServiceRecord> disputeRecords = afterServiceRecordService
                    .selectAfterServiceRecordList(queryRecord);

            logger.info("主单[{}]的子单IDs: {}，找到{}条售后纠纷记录", orderMaster.getId(), orderDetailIds, disputeRecords.size());

            // 为每个售后记录添加子单信息
            Map<Long, OrderDetail> orderDetailMap = orderDetailList.stream()
                    .collect(Collectors.toMap(OrderDetail::getId, detail -> detail));

            disputeRecords.forEach(record -> {
                OrderDetail detail = orderDetailMap.get(record.getOrderDetailId());
                if (detail != null) {
                    record.setOrderDetailCode(detail.getCode());
                    logger.info("售后记录[{}]属于子单[{}]", record.getId(), detail.getCode());
                } else {
                    logger.warn("售后记录[{}]的子单ID[{}]在子单列表中未找到", record.getId(), record.getOrderDetailId());
                }
            });

            logger.info("主单[{}]总共找到{}条售后纠纷记录", orderMaster.getId(), disputeRecords.size());
            return AjaxResult.success(disputeRecords);

        } catch (Exception e) {
            logger.error("查询主单[{}]售后纠纷记录异常", orderMaster.getId(), e);
            return AjaxResult.error("查询售后纠纷记录失败：" + e.getMessage());
        }
    }

    @PostMapping("/after/records/byDetailId")
    @ResponseBody
    public AjaxResult getAfterServiceRecordsByDetailId(@RequestBody OrderDetail orderDetail) {
        try {
            logger.info("查询子单[{}]的售后纠纷记录", orderDetail.getId());

            // 直接查询该子单的售后纠纷记录
            AfterServiceRecord queryRecord = new AfterServiceRecord();
            queryRecord.setOrderDetailId(orderDetail.getId());
            queryRecord.setCustomerFinalCheck(0L); // 客户不同意
            queryRecord.setExcludeAfterServiceFinished(Boolean.TRUE); // 排除已完成的售后

            List<AfterServiceRecord> disputeRecords = afterServiceRecordService
                    .selectAfterServiceRecordList(queryRecord);

            logger.info("子单[{}]找到{}条售后纠纷记录", orderDetail.getId(), disputeRecords.size());

            // 为每个售后记录添加子单信息
            OrderDetail detail = orderDetailService.selectById(orderDetail.getId());
            if (detail != null) {
                disputeRecords.forEach(record -> {
                    record.setOrderDetailCode(detail.getCode());
                });
            }

            return AjaxResult.success(disputeRecords);

        } catch (Exception e) {
            logger.error("查询子单[{}]售后纠纷记录异常", orderDetail.getId(), e);
            return AjaxResult.error("查询售后纠纷记录失败：" + e.getMessage());
        }
    }

    @PostMapping("/after/dispute/handle")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult handleAfterServiceDispute(@RequestBody AfterServiceDisputeRequest request) {
        try {
            logger.info("处理售后纠纷退款，记录ID：{}，退款金额：{}", request.getRecordId(), request.getRefundAmount());

            // 查询售后记录
            AfterServiceRecord record = afterServiceRecordService.selectAfterServiceRecordById(request.getRecordId());
            if (record == null) {
                return AjaxResult.error("售后记录不存在");
            }

            // 验证是否为售后纠纷（客户不同意）
            if (record.getCustomerFinalCheck() == null || !record.getCustomerFinalCheck().equals(0L)) {
                return AjaxResult.error("该记录不是售后纠纷，无法处理");
            }

            // 设置退款金额和处理原因
            // record.setRefund(request.getRefundAmount());
            // record.setAgreedRefund(request.getRefundAmount());
            record.setPlatformRefund(request.getRefundAmount());
            record.setRefundApplyTime(new Date());
            record.setPlatformHandleReason(request.getPlatformHandleReason());

            // 更新售后记录
            afterServiceRecordService.updateAfterServiceRecord(record);

            // 执行退款逻辑
            try {
                afterServiceRecordService.executeRefundLogic(record);
                
                // 退款成功后，更新子单和主单的售后状态为已完成
                OrderDetail orderDetail = orderDetailService.selectById(record.getOrderDetailId());
                if (orderDetail != null) {
                    orderDetail.setAfterServiceStatus(2);
                    orderDetailService.updateOrderDetail(orderDetail);
                    logger.info("已将子单[{}]售后状态设置为已完成", orderDetail.getId());
                    
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    if (orderMaster != null) {
                        orderMaster.setAfterServiceStatus(2);
                        // 设置退款支付状态为已支付（因为执行了退款逻辑）
                        orderMaster.setRefundPayStatus(1);
                        orderMasterService.updateOrderMaster(orderMaster);
                        logger.info("已将主单[{}]售后状态设置为已完成，退款支付状态设置为已支付", orderMaster.getId());
                    }
                }
                
                // 退款成功后，更新售后记录状态为已完成
                record.setAfterServiceStatus(1);
                afterServiceRecordService.updateAfterServiceRecord(record);
                
                logger.info("售后纠纷退款处理成功，记录ID：{}，退款金额：{}，处理原因：{}", request.getRecordId(), request.getRefundAmount(), request.getPlatformHandleReason());
                return AjaxResult.success("退款处理成功");
            } catch (Exception e) {
                logger.error("售后纠纷退款执行失败，记录ID：{}，错误：{}", request.getRecordId(), e.getMessage());
                return AjaxResult.error("退款执行失败：" + e.getMessage());
            }

        } catch (Exception e) {
            logger.error("处理售后纠纷异常，记录ID：{}", request.getRecordId(), e);
            return AjaxResult.error("处理售后纠纷失败：" + e.getMessage());
        }
    }

    @PostMapping("/app/detail")
    @ResponseBody
    public AjaxResult appDetail(@RequestBody OrderMaster request) {
        try {
            // 主单信息
            OrderMaster orderMaster = orderMasterService.selectById(request.getId());

            List<OrderDetail> orderDetailList = orderDetailService.selectByOrderMasterId(orderMaster.getId());
            Collections.reverse(orderDetailList);
            List<OrderStandardDetail> orderStandardDetails = new ArrayList<>();

            // 财务信息
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMaster.getId());
            // 计算总额
            BigDecimal totalPayMoney = financialMaster.getPayMoney();
            
            // 扣减平台退款金额
            BigDecimal totalPlatformRefundMoney = BigDecimal.ZERO;
            for (OrderDetail orderDetail : orderDetailList) {
                AfterServiceRecord afterServiceRecordQuery = new AfterServiceRecord();
                afterServiceRecordQuery.setOrderDetailId(orderDetail.getId());
                List<AfterServiceRecord> afterServiceRecords = afterServiceRecordService
                        .selectAfterServiceRecordList(afterServiceRecordQuery);
                if (CollectionUtils.isNotEmpty(afterServiceRecords)) {
                    for (AfterServiceRecord record : afterServiceRecords) {
                        if (record.getPlatformRefund() != null && record.getPlatformRefund().compareTo(BigDecimal.ZERO) > 0) {
                            totalPlatformRefundMoney = totalPlatformRefundMoney.add(record.getPlatformRefund());
                        }
                    }
                }
            }
            // if (totalPlatformRefundMoney.compareTo(BigDecimal.ZERO) > 0) {
            //     totalPayMoney = totalPayMoney.subtract(totalPlatformRefundMoney);
            // }

            
            BigDecimal leaderMoney = BigDecimal.ZERO;
            for (OrderDetail orderDetail : orderDetailList) {
                List<OrderStandard> standardList = new ArrayList<>();
                // 子单施工师傅信息
                Worker detailWorker = workerService.selectById(orderDetail.getWorkerId());
                // 师傅实名信息
                WorkerCertification detailWorkerRealInfo = workerCertificationService
                        .selectByWorkerId(orderDetail.getWorkerId());

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

                for (OrderGoods orderGoods : orderStandardList) {
                    OrderStandard orderStandard = new OrderStandard();
                    orderStandard.setStandardName(orderGoods.getGoodsName());
                    orderStandard.setStandardNum(orderGoods.getGoodsNum());
                    orderStandard
                            .setServerNum(orderGoods.getServerGoodsNum() == null ? 0 : orderGoods.getServerGoodsNum());
                    orderStandard.setWaitServerNum(orderStandard.getStandardNum() - orderStandard.getServerNum());
                    standardList.add(orderStandard);
                }

                // 完工图片
                List<String> finishImgList = null;
                if (orderMaster.getOrderStatus() > 3) {
                    GoodsImgs qryImgsObj = new GoodsImgs();
                    qryImgsObj.setRemark(orderDetail.getId().toString());
                    qryImgsObj.setImgType(ImgType.FINISH_IMG.getId());
                    qryImgsObj.setGoodsId(0L);
                    List<GoodsImgs> goodsImgs = goodsImgsService.qryGoodsImgs(qryImgsObj);
                    finishImgList = goodsImgs.stream().map(GoodsImgs::getImgUrl).collect(Collectors.toList());
                }

                FinancialDetail financialDetail = financialDetailService.selectByOrderDetailId(orderDetail.getId());
                BigDecimal detailPayMoney = financialDetail.getPayMoney();
                // 查询子单加价记录
                FinancialChangeRecord changeRecordQry = new FinancialChangeRecord();
                changeRecordQry.setOrderDetailId(orderDetail.getId());
                List<FinancialChangeRecord> financialChangeRecords = financialChangeRecordService
                        .selectFinancialChangeRecordList(changeRecordQry);
                // if (CollectionUtils.isNotEmpty(financialChangeRecords)) {
                // financialChangeRecord = financialChangeRecords.get(0);
                // totalPayMoney = totalPayMoney.add(financialChangeRecord.getChangeMoney());
                // detailPayMoney = detailPayMoney.add(financialChangeRecord.getChangeMoney());
                // }

                OrderAttachmentRecord param = new OrderAttachmentRecord();
                param.setOrderDetailId(orderDetail.getId());
                List<OrderAttachmentRecord> orderAttachmentRecordList = orderAttachmentRecordService
                        .selectOrderAttachmentRecordList(param);
                BigDecimal addMoneyTotal = BigDecimal.ZERO;
                String remark = null;
                for (FinancialChangeRecord financialChangeRecord : financialChangeRecords) {
                    addMoneyTotal = addMoneyTotal.add(financialChangeRecord.getChangeMoney());
                    if (StringUtils.isNotEmpty(financialChangeRecord.getRemark())) {
                        remark = financialChangeRecord.getRemark();
                    }
                    OrderAttachmentRecord param1 = new OrderAttachmentRecord();
                    param1.setFinancialChangeRecordId(financialChangeRecord.getId());
                    BigDecimal attachmentMoney = BigDecimal.ZERO;
                    List<OrderAttachmentRecord> orderAttachmentRecords = orderAttachmentRecordService
                            .selectOrderAttachmentRecordList(param1);
                    if (orderAttachmentRecords != null && orderAttachmentRecords.size() > 0) {
                        attachmentMoney = attachmentMoney.add(orderAttachmentRecords.get(0).getAttachMoney());
                        financialChangeRecord.setAttachmentMoney(attachmentMoney);
                    }
                    if (financialChangeRecord.getPayStatus() == 1) {
                        if (financialChangeRecord.getLeaderMoney().compareTo(BigDecimal.ZERO) > 0) {
                            leaderMoney = leaderMoney.add(financialChangeRecord.getLeaderMoney());
                        }
                    }
                }
                for (OrderAttachmentRecord orderAttachmentRecord : orderAttachmentRecordList) {
                    addMoneyTotal = addMoneyTotal.add(orderAttachmentRecord.getAttachMoney());
                }

                OrderStandardDetail orderStandardDetail = new OrderStandardDetail();
                orderStandardDetail.setRefundPayStatus(orderMaster.getRefundPayStatus());
                orderStandardDetail.setPayStatus(orderMaster.getPayStatus());
                orderStandardDetail.setAfterPlatformServiceStatus(orderDetail.getAfterServiceStatus());
                orderStandardDetail.setOrderImages(orderDetail.getOrderImages());
                orderStandardDetail.setHandoverImages(orderDetail.getHandoverImages());
                orderStandardDetail.setHandoverRemark(orderDetail.getHandoverRemark());
                orderStandardDetail.setDeliveryType(orderDetail.getDeliveryType());
                orderStandardDetail.setDeliveryRemark(orderDetail.getDeliveryRemark());
                orderStandardDetail.setDeliveryImages(orderDetail.getDeliveryImages());
                orderStandardDetail.setTrackingNumber(orderDetail.getTrackingNumber());
                orderStandardDetail.setRemark(remark);
                orderStandardDetail.setAddMoney(addMoneyTotal);
                orderStandardDetail.setOrderDetailId(orderDetail.getId());
                orderStandardDetail.setOrderDetailCode(orderDetail.getCode());
                orderStandardDetail.setWorkBeginTime(orderDetail.getWorkBeginTime());
                orderStandardDetail.setWorkFinishTime(orderDetail.getWorkFinishTime());
                orderStandardDetail.setWorkerName(detailWorkerRealInfo != null
                        ? detailWorkerRealInfo.getSurname() + detailWorkerRealInfo.getName()
                        : detailWorker.getName());
                orderStandardDetail.setWorkerPhone(detailWorker.getPhone());
                orderStandardDetail.setRevTime(orderDetail.getRevTime());
                orderStandardDetail.setExpectTimeStart(orderDetail.getExpectTimeStart());
                orderStandardDetail.setExpectTimeEnd(orderDetail.getExpectTimeEnd());
                orderStandardDetail.setExpectTimeStartFront(orderDetail.getExpectTimeStart());
                orderStandardDetail.setExpectTimeEndFront(orderDetail.getExpectTimeEnd());
                orderStandardDetail.setOrderStandardList(standardList);
                orderStandardDetail.setFinishImgList(finishImgList);
                orderStandardDetail.setRemark(orderDetail.getRemark());
                orderStandardDetail.setPayMoney(detailPayMoney);
                orderStandardDetail.setFinancialChangeRecord(financialChangeRecords);
                orderStandardDetail.setOrderStatus(orderDetail.getOrderStatus());
                orderStandardDetail.setTimeout(orderDetail.getTimeout());
                orderStandardDetail.setTimeoutFineTimes(orderDetail.getTimeoutFineTimes());
                orderStandardDetail.setServerMoney(financialMaster.getServerMoney());
                AfterServiceRecord afterServiceRecord = new AfterServiceRecord();
                afterServiceRecord.setOrderDetailId(orderDetail.getId());
                List<AfterServiceRecord> records = afterServiceRecordService
                        .selectAfterServiceRecordList(afterServiceRecord);
                orderStandardDetail.setAfterServiceRecordList(records);

                orderStandardDetail.setIsOnlyServ(
                        this.checkIsOnlyServer(orderMaster.getId(), orderDetail.getWorkerId()) ? Boolean.TRUE
                                : Boolean.FALSE);

                orderStandardDetail.setDrawCashStatus(orderDetail.getDrawCashStatus());
                orderStandardDetail.setDrawCashTime(orderDetail.getDrawCashTime());

                orderStandardDetail.setAfterTimeout(orderDetail.getAfterTimeout());

                orderStandardDetail.setReturnReason(orderDetail.getReturnReason());
                orderStandardDetail.setReturnReasonDetail(orderDetail.getReturnReasonDetail());
                orderStandardDetail.setReturnImages(orderDetail.getReturnImages());

                orderStandardDetails.add(orderStandardDetail);
            }

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

            // 师傅信息
            Worker worker = workerService.selectById(orderMaster.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;
            Integer goodsPayStatus = null;
            
            // 消费者信息
            // Customer customer =
            // customerService.selectByCustomerId(orderMaster.getCustomerId());

            // 商品规格及信息
            List<OrderGoods> orderStandardList = orderGoodsService.selectByOrderMasterId(orderMaster.getId());
            if (orderMaster.getGoodsOrderMasterId() != null) {
                // 子单商品规格及信息
                goodsOrderMaster = orderMasterService.selectById(orderMaster.getGoodsOrderMasterId());
                goodsWorker = workerService.selectById(goodsOrderMaster.getWorkerId());
                goodsWorkerRealInfo = workerCertificationService.selectByWorkerId(goodsOrderMaster.getWorkerId());
                orderStandardList=orderGoodsService.selectByOrderMasterId(goodsOrderMaster.getId());
                orderListResponse.setOriginalOrderMasterCode(goodsOrderMaster.getCode());
                goodsPayStatus=goodsOrderMaster.getPayStatus();
            }
            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();
               
            }
            // 商品信息
            // GoodsStandard goodsStandard =
            // goodsStandardService.selectById(orderStandardList.get(0).getGoodsStandardId());

            Goods goods = goodsService.selectById(orderMaster.getGoodsId());
            if (goods != null) {
                // 填充商品三级类目
                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) {
                                    orderListResponse.setTotalName(three.getGoodsCategoryName()
                                            + "-" + two.getGoodsCategoryName()
                                            + "-" + one.getGoodsCategoryName());
                                }
                            }
                        }
                    }
                }
            }
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(goods.getGoodsId());
            goods.setGoodsAreaList(goodsAreas);

            // 地址信息
            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() == null ? 0 : orderGoods.getServerGoodsNum());
                orderStandard.setWaitServerNum(orderStandard.getStandardNum() - orderStandard.getServerNum());
                standardList.add(orderStandard);
            }

            // 查询主单师傅的最终收益
            FinancialDetail fdQry = new FinancialDetail();
            fdQry.setPayeeId(orderMaster.getWorkerId());
            fdQry.setFinancialMasterId(financialMaster.getId());
            List<FinancialDetail> financialDetailList = financialDetailService.selectFinancialDetailList(fdQry);
            BigDecimal finalRecvMoney = BigDecimal.ZERO;
            for (FinancialDetail financialDetail : financialDetailList) {
                finalRecvMoney = finalRecvMoney.add(financialDetail.getPayMoney());
            }
            BigDecimal serverMoney = BigDecimal.ZERO;
            serverMoney = serverMoney.add(financialMaster.getServerMoney());
            serverMoney = serverMoney.add(leaderMoney);
            logger.info("大师傅的服务金额{}大师傅的分成{}", serverMoney, leaderMoney);
            Shop shop = shopService.getShop(goods.getShopId());
            Shop serviceShop = shopService.getShop(orderMaster.getServiceShopId());
            shop = calculateShopDistance(orderMaster, shop);
            serviceShop = calculateShopDistance(orderMaster, serviceShop);
            // 编辑返回属性
            orderListResponse.setIsDeliveryToStore(orderMaster.getIsDeliveryToStore());
            orderListResponse.setDeliveryType(orderMaster.getDeliveryType());
            orderListResponse.setDeliveryRemark(orderMaster.getDeliveryRemark());
            orderListResponse.setDeliveryImages(orderMaster.getDeliveryImages());
            orderListResponse.setShop(shop);
            orderListResponse.setServiceShop(serviceShop);
            orderListResponse.setServiceCancelled(orderMaster.getServiceCancelled());

            orderListResponse.setMasterCompanyPhone(masterCompanyPhone);
            orderListResponse.setOriginalWorkerId(goodsOrderMaster != null ? goodsOrderMaster.getWorkerId() : null);
            orderListResponse.setGoodsOrderMasterId(orderMaster.getGoodsOrderMasterId());
            orderListResponse.setGoods(goods);
            orderListResponse.setTrackingNumber(orderMaster.getTrackingNumber());
            orderListResponse.setWorkerRemark(orderMaster.getWorkerRemark());
            orderListResponse.setOrderImages(orderMaster.getOrderImages());
            orderListResponse.setOrderMasterId(orderMaster.getId());
            orderListResponse.setOrderMasterCode(orderMaster.getCode());
            orderListResponse.setGoodsName(goods.getGoodsName());
            orderListResponse.setGoodsLogoUrl(goods.getGoodsImgUrl());
            orderListResponse.setDiscountMoney(financialMaster.getDiscountMoney());
            orderListResponse.setTotalMoney(financialMaster.getTotalMoney());
            orderListResponse.setPayMoney(totalPayMoney);
            orderListResponse.setWorkerId(worker == null ? null : worker.getWorkerId());
            orderListResponse.setWorkerName(workerName);
            orderListResponse.setWorkerPhone(worker == null ? "" : worker.getPhone());
            orderListResponse.setCustomerName(
                    org.apache.commons.lang3.StringUtils.isNotEmpty(orderMaster.getName()) ? orderMaster.getName()
                            : customerAddress.getName());
            orderListResponse.setCustomerPhone(
                    org.apache.commons.lang3.StringUtils.isNotEmpty(orderMaster.getPhone()) ? orderMaster.getPhone()
                            : customerAddress.getPhone());
            orderListResponse.setOrderStatus(orderMaster.getOrderStatus());
            orderListResponse.setPayStatus(goodsPayStatus!=null?goodsPayStatus:orderMaster.getPayStatus());
            orderListResponse.setRefundPayStatus(orderMaster.getRefundPayStatus());
            orderListResponse.setPayType(orderMaster.getPayType());
            orderListResponse.setStandardList(standardList);
            orderListResponse.setAddress(completeAddress);
            orderListResponse.setServerTime(orderMaster.getRevTime());
            orderListResponse.setServerMoney(serverMoney);
            orderListResponse.setExpectTimeStart(orderMaster.getExpectTimeStart());
            orderListResponse.setExpectTimeEnd(orderMaster.getExpectTimeEnd());
            orderListResponse.setExpectTimeStartFront(orderMaster.getExpectTimeStart());
            orderListResponse.setExpectTimeEndFront(orderMaster.getExpectTimeEnd());
            orderListResponse.setCreateTime(orderMaster.getCreateTime());
            orderListResponse.setRemark(goods.getRemark());
            orderListResponse.setCustomerRemark(orderMaster.getRemark());
            orderListResponse.setOrderStandardDetailList(orderStandardDetails);
            orderListResponse.setTimeout(orderMaster.getTimeout());
            orderListResponse.setTimeoutFineTimes(orderMaster.getTimeoutFineTimes());
            orderListResponse.setFinalRecvMoney(finalRecvMoney);
            orderListResponse.setGoodsAreaList(goods.getGoodsAreaList());
            orderListResponse.setOrderMode(orderMaster.getOrderMode());
            orderListResponse.setIsCall(orderMaster.getIsCall());
            orderListResponse.setMasterCompanyName(masterCompanyName);
            orderListResponse.setMasterWorkerPhone(masterWorker == null ? "" : masterWorker.getPhone());
            orderListResponse.setMasterWorkerName(masterWorkerName);
            if (StringUtils.isNotEmpty(orderMaster.getProvinceName())) {
                orderListResponse.setProvinceId(orderMaster.getProvinceId());
                orderListResponse.setCityId(orderMaster.getCityId());
                orderListResponse.setCountryId(orderMaster.getCountryId());
                orderListResponse.setPhone(orderMaster.getPhone());
                orderListResponse.setName(orderMaster.getName());
                orderListResponse.setProvinceName(orderMaster.getProvinceName());
                orderListResponse.setCityName(orderMaster.getCityName());
                orderListResponse.setCountryName(orderMaster.getCountryName());
                orderListResponse.setStreetId(orderMaster.getStreetId());
                orderListResponse.setStreetName(orderMaster.getStreetName());
                orderListResponse.setAddress(orderMaster.getAddress());
            } else {
                if (!StringUtils.isEmpty(customerAddress.getStreetId() + "")) {
                    String addressSysArea = sysArea.getMergerName();
                    String[] array = addressSysArea.split(",");
                    orderListResponse.setProvinceName(array[0]);
                    orderListResponse.setCityName(array[1]);
                    if (array.length == 3) {
                        orderListResponse.setCountryName(array[2]);
                    }
                    if (array.length == 4) {
                        orderListResponse.setStreetName(array[3]);
                    }

                }
                orderListResponse.setProvinceId(customerAddress.getProvinceId());
                orderListResponse.setCityId(customerAddress.getCityId());
                orderListResponse.setCountryId(customerAddress.getCountryId());
                orderListResponse.setStreetId(orderMaster.getStreetId());
                orderListResponse.setAddress(customerAddress.getAddress());
                orderListResponse.setPhone(customerAddress.getPhone());
                orderListResponse.setName(customerAddress.getName());

            }
            logger.info("主单id{}，主单数据1{}", request.getId(), orderListResponse);

            return AjaxResult.success(orderListResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    // @RequiresPermissions("order:master:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrderMaster orderMaster) {
        // 检查是否是售后纠纷查询
        if (orderMaster.getOrderStatusName() != null && "售后纠纷".equals(orderMaster.getOrderStatusName())) {
            // 通过查询AfterServiceRecord表中customerFinalCheck=0的记录获取售后纠纷的主单ID
            // List<Long> disputeOrderMasterIds = getDisputeOrderMasterIds();
            // if (disputeOrderMasterIds.isEmpty()) {
            //     // 如果没有售后纠纷记录，返回空结果
            //     return getDataTable(new ArrayList<>());
            // }
            // // 将售后纠纷的主单ID设置到查询条件中
            // String ids = disputeOrderMasterIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            // orderMaster.setOrderMasterIds(ids);
            orderMaster.setAfterServiceStatus(1);
            orderMaster.setOrderStatus(null); // 清除orderStatus条件，避免冲突
        } else if (orderMaster.getSearchAfterList() != null && orderMaster.getSearchAfterList()) {
            // 保持原有的售后查询逻辑
            List<?> rows = this.afterList(orderMaster).getRows();
            StringBuilder masterIds = new StringBuilder();
            if (CollectionUtils.isNotEmpty(rows)) {
                rows.forEach(model -> {
                    OrderListResponse response = (OrderListResponse) model;
                    masterIds.append(response.getOrderMasterId()).append(",");
                });
            }
            String ids = masterIds.toString();
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(ids)) {
                orderMaster.setOrderMasterIds(ids.substring(0, ids.length() - 1));
            }
        }

        // 非管理员
        if (this.getSysUser().getRoles().get(0).getRoleId() != 1) {
            orderMaster.setDeptId(this.getSysUser().getDeptId());
        }
        // PC师傅
        if (this.getSysUser().getRoles().get(0).getRoleId() == 101L) {
            orderMaster.setCreateBy(this.getSysUser().getUserId().toString());
        }
        
        // 先获取总数（防御性处理空值，避免分页时拆箱 NPE
        Integer pageSize= orderMaster.getPageSize();
        Integer pageNum =orderMaster.getPageNum();
        if (orderMaster.getProvince()==""){
            orderMaster.setProvince(null);
            orderMaster.setPageSize(10);
            orderMaster.setPageNum(1);
        }
        Long total = orderMasterService.selectOrderMasterCount(orderMaster);
        if (total == null) {
            total = 0L;
        }
        orderMaster.setPageSize(pageSize);
        orderMaster.setPageNum(pageNum);
        startPage();
        List<OrderMaster> orderMasterList = orderMasterService.selectOrderMasterList(orderMaster);
        Set<Long> orderMasterIds = orderMasterList.stream().map(OrderMaster::getId).collect(Collectors.toSet());

        Set<Long> customerIds = orderMasterList.stream().map(OrderMaster::getCustomerId).collect(Collectors.toSet());
        Map<Long, Customer> customerMap = customerService.selectByIds(customerIds)
                .stream().collect(Collectors.toMap(Customer::getCustomerId, x -> x, (x, y) -> y));

        List<FinancialMaster> financialMasters = financialMasterService.selectByOrderMasterIds(orderMasterIds);
        Map<Long, FinancialMaster> financialMasterMap = financialMasters
                .stream().collect(Collectors.toMap(FinancialMaster::getOrderMasterId, x -> x, (x, y) -> y));

        Set<Long> goodsIds = orderMasterList.stream().map(OrderMaster::getGoodsId).collect(Collectors.toSet());
        List<Goods> goods = goodsService.selectByIds(goodsIds);
        Map<Long, Goods> goodsMap = goods.stream().collect(Collectors.toMap(Goods::getGoodsId, x -> x, (x, y) -> y));

        Set<Long> workerIds = orderMasterList.stream().map(OrderMaster::getWorkerId).collect(Collectors.toSet());
        workerIds.addAll(goods.stream().map(Goods::getWorkerId).collect(Collectors.toSet()));
        Map<Long, Worker> workerMap = workerService.selectByIds(workerIds)
                .stream().collect(Collectors.toMap(Worker::getWorkerId, x -> x, (x, y) -> y));

        for (OrderMaster master : orderMasterList) {
            Customer customer = customerMap.get(master.getCustomerId());
            master.setWorker(workerMap.get(master.getWorkerId()));
            if (customer != null) {
                master.setCustomerName(customer.getName());
                master.setCustomerPhone(customer.getPhone());
            }
            if (StringUtils.isNotEmpty(orderMaster.getOrderStatusName())) {
                master.setOrderStatusName(orderMaster.getOrderStatusName());
            }

            // 如果数据库中的afterServiceStatus为null，则设置为0（无售后）
            if (master.getAfterServiceStatus() == null) {
                master.setAfterServiceStatus(0);
            }

            FinancialMaster fm = financialMasterMap.get(master.getId());
            if (fm != null) {
                master.setFinancialMasterMoney(fm.getPayMoney());
                master.setFinancialMasterPayMoney(fm.getServerMoney());
            }
            OrderCallRecord orderCallRecordParam = new OrderCallRecord();
            orderCallRecordParam.setOrderType("01");
            orderCallRecordParam.setOrderId(master.getId());
            List<OrderCallRecord> orderCallRecords = orderCallRecordService
                    .selectOrderCallRecordList(orderCallRecordParam);
            if (CollectionUtils.isNotEmpty(orderCallRecords)) {
                OrderCallRecord newOne = orderCallRecords.stream()
                        .sorted(Comparator.comparing(OrderCallRecord::getCallTime).reversed())
                        .collect(Collectors.toList()).get(0);
                master.setLastCallTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", newOne.getCallTime()) + " 拨号次数x"
                        + orderCallRecords.size());
            }
            Goods good = goodsMap.get(master.getGoodsId());
            if (good != null) {
                master.setGoods(good);
                // 填充商品三级类目
                if (good.getDeptGoodsCategoryId() != null) {
                    Long categoryId = null;
                    // 前端发单和后台派单
                    if (com.ghy.common.utils.StringUtils.isEmpty(master.getOrderMode())) {
                        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                                .selectOneByGoodsCategoryId(good.getDeptGoodsCategoryId());
                        if (deptGoodsCategory != null) {
                            categoryId = deptGoodsCategory.getGoodsCategoryId();
                        }
                    } else {
                        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService
                                .get(good.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) {
                                    int totalNum = orderGoodsService.selectByOrderMasterId(master.getId()).stream()
                                            .mapToInt(OrderGoods::getGoodsNum).sum();
                                    master.setConsoleGoodsName("【" + three.getGoodsCategoryName()
                                            + "-" + two.getGoodsCategoryName()
                                            + "-" + one.getGoodsCategoryName() + "】x" + totalNum);
                                }
                            }
                        }
                    }
                }
            }
            // 地址信息
            CustomerAddress customerAddress = addressService.selectByCustomerAddressId(master.getAddressId());
            if (customerAddress != null) {
                SysArea sysArea;
                if (customerAddress.getStreetId() != null) {
                    sysArea = sysAreaService.selectById(customerAddress.getStreetId());
                } else {
                    sysArea = sysAreaService.selectById(customerAddress.getCountryId());
                }

                String completeAddress = sysArea.getMergerName().replaceAll(",", "") + customerAddress.getAddress();
                master.setAddressName(customerAddress.getName());
                master.setAddressPhone(customerAddress.getPhone());
                master.setAddress(completeAddress);
            }
            if (master.getExpectTimeStart() != null && master.getExpectTimeEnd() != null) {
                master.setMixExpectTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", master.getExpectTimeStart()) + "-"
                        + DateUtils.parseDateToStr("HH:mm", master.getExpectTimeEnd()));
            }
            if ("01".equals(master.getConsultMode())) {
                master.setOrderMode("05");
            } else if (StringUtils.isEmpty(master.getOrderMode())) {
                master.setOrderMode("01");
            }
            List<OrderDetail> details = orderDetailService.selectByOrderMasterId(master.getId());
            StringBuilder stringBuilder = new StringBuilder();
            details.forEach(model -> {
                GoodsImgs param = new GoodsImgs();
                param.setRemark(String.valueOf(model.getId()));
                param.setImgType(ImgType.FINISH_IMG.getId());
                List<GoodsImgs> imgsList = goodsImgsService.qryGoodsImgs(param);
                imgsList.forEach(imgs -> {
                    stringBuilder.append("<a target='_blank' href='").append(imgs.getImgUrl()).append("' >查看图片<a/>");
                });
            });
            master.setOrderImgs(stringBuilder.toString());
        }
        TableDataInfo dataTable = getDataTable(orderMasterList);
        dataTable.setTotal(total);
        return dataTable;
    }

    @Log(title = "主订单管理", businessType = BusinessType.EXPORT)
    // @RequiresPermissions("order:master:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OrderMaster orderMaster) {
        List<OrderMaster> list = orderMasterService.selectOrderMasterList(orderMaster);
        ExcelUtil<OrderMaster> util = new ExcelUtil<>(OrderMaster.class);
        return util.exportExcel(list, "主订单数据");
    }

    // @RequiresPermissions("order:master:remove")
    @Log(title = "主订单管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(orderMasterService.deleteOrderMasterByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改主订单
     */
    // @RequiresPermissions("order:master:edit")
    @GetMapping("/edit/{orderMasterId}")
    public String edit(@PathVariable("orderMasterId") Long orderMasterId, ModelMap mmap) {
        mmap.put("orderMaster", orderMasterService.selectById(orderMasterId));
        return prefix + "/edit";
    }

    /**
     * 修改保存主订单
     */
    // @RequiresPermissions("order:master:edit")
    @Log(title = "主订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated OrderMaster orderMaster) throws BaseAdaPayException {
        try {
            if (UserConstants.ORDER_CODE_NOT_UNIQUE
                    .equals(orderMasterService.checkOrderMasterCodeUnique(orderMaster))) {
                return error("修改主订单'" + orderMaster.getCode() + "'失败，主订单编码已存在");
            }
            orderMaster.setUpdateBy(getLoginName());
            return toAjax(orderMasterService.updateOrderMaster(orderMaster));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改订单信息失败:" + e.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 修改保存主订单信息
     */
    @PostMapping("/editOrderMaster")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editOrderMaster(@RequestBody OrderMaster orderMaster) {
        try {
            int result = orderMasterService.updateOrderMaster(orderMaster);
            // 下单
            if (orderMaster.getOrderStatus() != null && OrderStatus.PLAIN.code() == orderMaster.getOrderStatus()) {
                OrderMaster model = orderMasterService.selectById(orderMaster.getId());
                // try {
                // if(model.getInsuranceId()!=null){
                // insuranceService.orderInsurance(model.getCode());
                // }
                // }catch (Exception e){
                // logger.error("下单报错:" + ExceptionUtils.getMessage(e));
                // return AjaxResult.error("保险正生成中，可能需几秒或几分钟，请稍等即可！若超半小时可联系发单方或平台!");
                // }
                // 判断是否是在线支付订单--如果是在线支付,且未付款,则需要提示支付后接单
                if (model.getPayMode().equals("02")){
                    if (PayTypeEnum.WX_LITE.getCode().equals(model.getPayType())) {
                        // 查询财务信息
                        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(model.getId());
                        if (!PayStatus.PAID.getCode().equals(financialMaster.getPayStatus())) {
                            return AjaxResult.error("客户支付中，请稍后！待支付完成可接单!");
                        }
                    }
                }

            }
            if (result > 0) {
                List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMaster.getId());
                orderDetails.forEach(orderDetail -> {
                    orderDetail.setOrderStatus(orderMaster.getOrderStatus());
                    orderDetailService.updateOrderDetail(orderDetail);
                });
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("派单失败:" + ExceptionUtils.getMessage(e));
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/editServingInfo")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editServingInfo(@RequestBody OrderMaster request) {
        logger.info("另一处修改地址库的方法{}", request);
        try {
            // 更新期望时间
            orderMasterService.updateOrderMaster(request);
            // 更新客户联系方式和地址
            OrderMaster order = orderMasterService.selectById(request.getId());
            CustomerAddress address2Update = new CustomerAddress();
            address2Update.setAddress(request.getAddress());
            address2Update.setPhone(request.getAddressPhone());
            address2Update.setCustomerAddressId(order.getAddressId());
            customerAddressService.updateCustomerAddress(address2Update);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改服务时间失败:" + ExceptionUtils.getStackTrace(e));
            return AjaxResult.error("修改失败");
        }
    }

    @PostMapping("/callCustomer")
    @ResponseBody
    public AjaxResult callCustomer(@RequestBody OrderMaster orderMaster) {
        try {
            OrderMaster result = orderMasterService.selectById(orderMaster.getId());
            if (result.getTimeout() == 1 && OrderStatus.PLAIN.code() == result.getOrderStatus()) {
                orderMaster.setTimeout(0);
            }
            int i = orderMasterService.updateOrderMaster(orderMaster);
            if (i > 0) {
                OrderCallRecord param = new OrderCallRecord();
                param.setOrderId(orderMaster.getId());
                param.setCallTime(new Date());
                param.setOrderType("01");
                orderCallRecordService.insertOrderCallRecord(param);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 校验主订单编码
     */
    @PostMapping("/checkOrderMasterCodeUnique")
    @ResponseBody
    public String checkOrderMasterCodeUnique(OrderMaster orderMaster) {
        return orderMasterService.checkOrderMasterCodeUnique(orderMaster);
    }

    /**
     * 消费者申请取消主订单
     *
     * @param orderMasterId 主订单ID
     */
    @PostMapping("/cancel")
    @ResponseBody
    public AjaxResult applyForCancel(Long orderMasterId) throws BaseAdaPayException {
        logger.info("消费者申请取消主订单，orderMasterId={}", orderMasterId);
        List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMasterId);
        for (OrderDetail detail : orderDetails) {
            if (detail.getOrderStatus() == 6 || detail.getOrderStatus() == 0 || detail.getOrderStatus() == 1) {

            } else {
                return AjaxResult.error("请详情内退单退款！");
            }
        }
        orderMasterService.applyForCancel(orderMasterId);
        return AjaxResult.success();
    }

    /*
     * 主单退单
     */
    @PostMapping("/console/cancel")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult consoleCancel(@RequestBody OrderMaster orderMaster) {
        if (orderMaster.getId() == null) {
            return AjaxResult.error("订单编码id不能为空!");
        }

        // 判断该主单状态
        OrderMaster orderMasterInfo = orderMasterService.selectById(orderMaster.getId());
        if (!orderMasterInfo.getOrderStatus().equals(OrderStatus.PLAIN.code())
                && !orderMasterInfo.getOrderStatus().equals(OrderStatus.RECEIVE.code())
                &&!orderMasterInfo.getOrderStatus().equals(OrderStatus.GOING.code())) {
            return AjaxResult.error("该订单处于无法退单状态!");
        }

        // 含有子单
        List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMaster.getId());
        if (CollectionUtils.isNotEmpty(orderDetails)) {
            return AjaxResult.error("该订单已经派发过子单,无法退单状态!");
        }

        try {
         //   判断是否为服务订单且需要退还服务金额
            if (isServiceOrder(orderMasterInfo) &&
                    orderMasterInfo.getGoodsOrderMasterId() != null ) {
               FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMasterInfo.getId());
                logger.info("检测到服务订单退单，开始退还服务金额：订单[{}]，金额[{}]，目标商品订单[{}]",
                        orderMasterInfo.getId(), financialMaster.getServerMoney(),
                        orderMasterInfo.getGoodsOrderMasterId());
                 orderMasterService.deleteOrderMasterByIds(orderMasterInfo.getId().toString());
                 // 删除对应的财务主单
                // 删除财务主单及其子单
            
                if (financialMaster != null) {
                    
                    // 再删除财务主单
                    financialMasterService.deleteFinancialMasterByIds(financialMaster.getId().toString());
                }
                // 退还服务金额到商品订单
                refundServerMoneyToGoodsOrder(orderMasterInfo.getGoodsOrderMasterId(),
                        financialMaster.getServerMoney());

                // 重置配件主单的服务订单派发状态
                OrderMaster goodsOrderUpdate = new OrderMaster();
                goodsOrderUpdate.setId(orderMasterInfo.getGoodsOrderMasterId());
                goodsOrderUpdate.setHasServiceOrder(0); // 重置为未派发状态
                // goodsOrderUpdate.setServiceShopId((long) -1);
                // 设置服务主单已撤销标识
                goodsOrderUpdate.setServiceCancelled(1);
                
                // 判断商品主单是否仍旧满足监控单条件
                OrderMaster goodsOrder = orderMasterService.selectById(orderMasterInfo.getGoodsOrderMasterId());
                boolean shouldShowInMonitor = false;
                
                if (goodsOrder != null) {
                    // 查询商品主单的所有派单详情
                    List<OrderDetail> orderDetails1 = orderDetailService.selectByOrderMasterId(goodsOrder.getId());
                    Set<Long> assignedWorkIds = orderDetails1.stream()
                            .map(OrderDetail::getWorkerId)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toSet());
                    
                    // 判断是否全部派完
                    if (orderMasterService.isAllAssign(goodsOrder.getId())) {
                        // 派完单的情况下：如果有其他师傅接单（包含其他人），则需要显示在监控单
                        if (assignedWorkIds.size() > 1 || !assignedWorkIds.contains(goodsOrder.getWorkerId())) {
                            shouldShowInMonitor = true;
                        }
                    } else {
                        // 未派完单的情况下：如果派给了非自己的师傅，则需要显示在监控单
                        if (assignedWorkIds.size() > 1 || (assignedWorkIds.size() == 1 && !assignedWorkIds.contains(goodsOrder.getWorkerId()))) {
                            shouldShowInMonitor = true;
                        }
                    }
                }
                
                // 只有在不满足监控单条件时才设置为0，否则保持原值
                if (!shouldShowInMonitor) {
                    goodsOrderUpdate.setShowInMonitor(0);
                }
                
                orderMasterService.updateOrderMaster(goodsOrderUpdate);
            }

            // 保存退单信息
            OrderMaster returnOrderUpdate = new OrderMaster();
            returnOrderUpdate.setId(orderMaster.getId());
            returnOrderUpdate.setReturnReason(orderMaster.getReturnReason());
            returnOrderUpdate.setReturnReasonDetail(orderMaster.getReturnReasonDetail());
            returnOrderUpdate.setReturnImages(orderMaster.getReturnImages());
            
            orderMasterService.updateOrderMaster(returnOrderUpdate);

            // 清空id
            orderMasterService.removeWorker(orderMaster.getId());
            // 更新状态待接单
            orderMasterService.updateStatus(orderMaster.getId(), OrderStatus.RECEIVE.code());

            return AjaxResult.success("退单成功");

        } catch (Exception e) {
            logger.error("退单失败：订单ID={}, 错误信息={}", orderMaster.getId(), e.getMessage(), e);
            return AjaxResult.error("退单失败：" + e.getMessage());
        }
    }

    /**
     * 判断是否为服务订单
     */
    private boolean isServiceOrder(OrderMaster orderMaster) {
        return orderMaster.getOrderType() != null && orderMaster.getOrderType() == 0;
    }

    /**
     * 服务订单退单时，退还服务金额给商品订单
     *
     * @param goodsOrderMasterId 商品订单主单ID
     * @param serverGoodsMoney   需要退还的服务金额
     */
    private void refundServerMoneyToGoodsOrder(Long goodsOrderMasterId, BigDecimal serverGoodsMoney) {
        try {
            // 1. 查询商品订单
            OrderMaster goodsOrder = orderMasterService.selectById(goodsOrderMasterId);
            if (goodsOrder == null) {
                logger.error("商品订单不存在，无法退还服务金额，goodsOrderMasterId={}", goodsOrderMasterId);
                throw new RuntimeException("商品订单不存在");
            }

            // 2. 查询商品订单的财务记录
            FinancialMaster goodsFinancial = financialMasterService.selectByOrderMasterId(goodsOrderMasterId);
            if (goodsFinancial == null) {
                logger.error("商品订单财务记录不存在，无法退还服务金额，goodsOrderMasterId={}", goodsOrderMasterId);
                throw new RuntimeException("商品订单财务记录不存在");
            }

            // 3. 更新商品订单的可用金额（增加退还的服务金额）
            BigDecimal currentPayMoney = goodsFinancial.getServerMoney();
            BigDecimal newPayMoney = currentPayMoney.add(serverGoodsMoney);

            goodsFinancial.setServerMoney(newPayMoney);
            financialMasterService.updateFinancialMaster(goodsFinancial);

            logger.info("服务订单退单成功，已退还{}元服务金额到商品订单[{}]", serverGoodsMoney, goodsOrderMasterId);

        } catch (Exception e) {
            logger.error("退还服务金额失败：goodsOrderMasterId={}, serverGoodsMoney={}, error={}",
                    goodsOrderMasterId, serverGoodsMoney, e.getMessage(), e);
            throw new RuntimeException("退还服务金额失败：" + e.getMessage());
        }
    }

    /**
     * 商品主单退单退款
     * 用于商品主单生成了服务主单后，先退服务主单然后再退商品主单
     * 前提是这两个主单状态都必须是没有进入确认中（状态不能是4-待确认）
     *
     * @param goodsOrderMasterId 商品主单ID
     */
    @PostMapping("/goodsOrderRefund")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult goodsOrderRefund(@RequestParam Long goodsOrderMasterId) {
        logger.info("商品主单退单退款开始，goodsOrderMasterId={}", goodsOrderMasterId);
        
        try {
            // 1. 检查商品主单是否存在
            OrderMaster goodsOrderMaster = orderMasterService.selectById(goodsOrderMasterId);
            if (goodsOrderMaster == null) {
                return AjaxResult.error("商品主单不存在!");
            }
            
            // 2. 检查商品主单状态，不能是待确认状态（4）
            if (goodsOrderMaster.getOrderStatus().equals(OrderStatus.FINISH_CHECK.code())) {
                return AjaxResult.error("商品主单已进入确认中状态，无法退单!");
            }
            
            // 3. 检查商品主单是否有子单
            List<OrderDetail> goodsOrderDetails = orderDetailService.selectByOrderMasterId(goodsOrderMasterId);
            if (goodsOrderDetails != null && !goodsOrderDetails.isEmpty()) {
                return AjaxResult.error("商品主单存在子单，无法退单！请先处理相关子单。");
            }
            
            // 4. 检查商品主单是否有关联的服务主单
            if (goodsOrderMaster.getHasServiceOrder() != null && goodsOrderMaster.getHasServiceOrder() == 1) {
                // 查找关联的服务主单
                OrderMaster serviceOrderMaster = orderMasterService.selectByGoodsOrderMasterId(goodsOrderMasterId);
                if (serviceOrderMaster != null) {
                    // 检查服务主单状态，不能是待确认状态（4）
                    if (serviceOrderMaster.getOrderStatus().equals(OrderStatus.FINISH_CHECK.code())) {
                        return AjaxResult.error("关联的服务主单已进入确认中状态，无法退单!");
                    }
                    
                    // 检查服务主单是否有子单
                    List<OrderDetail> serviceOrderDetails = orderDetailService.selectByOrderMasterId(serviceOrderMaster.getId());
                    if (serviceOrderDetails != null && !serviceOrderDetails.isEmpty()) {
                        return AjaxResult.error("关联的服务主单存在子单，无法退单！请先处理相关子单。");
                    }
                    
                    // 5. 先退服务主单
                    logger.info("开始退服务主单，serviceOrderMasterId={}", serviceOrderMaster.getId());
                    OrderMaster serviceOrderParam = new OrderMaster();
                    serviceOrderParam.setId(serviceOrderMaster.getId());
                    AjaxResult serviceResult = consoleCancel(serviceOrderParam);
                    if (!serviceResult.get("code").equals(0)) {
                        logger.error("退服务主单失败：{}", serviceResult.get("msg"));
                        throw new RuntimeException("退服务主单失败：" + serviceResult.get("msg"));
                    }
                    logger.info("退服务主单成功，serviceOrderMasterId={}", serviceOrderMaster.getId());
                }
            }
            
            // 6. 再退商品主单
            logger.info("开始退商品主单，goodsOrderMasterId={}", goodsOrderMasterId);
            OrderMaster goodsOrderParam = new OrderMaster();
            goodsOrderParam.setId(goodsOrderMasterId);
            AjaxResult goodsResult = consoleCancel(goodsOrderParam);
            if (!goodsResult.get("code").equals(0)) {
                logger.error("退商品主单失败：{}", goodsResult.get("msg"));
                throw new RuntimeException("退商品主单失败：" + goodsResult.get("msg"));
            }
            logger.info("退商品主单成功，goodsOrderMasterId={}", goodsOrderMasterId);
            
            // 7. 退单成功后进行退款操作
            try {
                // 获取商品主单的财务信息
                FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(goodsOrderMasterId);
                if (financialMaster == null) {
                    logger.warn("未找到商品主单的财务信息，goodsOrderMasterId={}", goodsOrderMasterId);
                    return AjaxResult.success("商品主单退单成功，但未找到财务信息，无法自动退款");
                }

                // 添加重复退款检查
                if (financialMaster.getPayStatus() != null && (financialMaster.getPayStatus() == 3 || financialMaster.getPayStatus() == 4)) {
                    logger.warn("财务主单已处于退款中或已退款状态，无法重复退款，goodsOrderMasterId={}, payStatus={}", goodsOrderMasterId, financialMaster.getPayStatus());
                    return AjaxResult.error("订单已处于退款中或已退款状态，无法重复退款");
                }

                // 计算退款金额（使用财务主单的payMoney）
                BigDecimal refundAmount = financialMaster.getPayMoney();
                if (refundAmount == null || refundAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    logger.info("商品主单退款金额为零，goodsOrderMasterId={}, refundAmount={}", goodsOrderMasterId, refundAmount);
                    return AjaxResult.success("商品主单退单成功，无需退款（金额为零）");
                }

                // 检查支付状态，只有已支付的订单才需要退款
                if (financialMaster.getPayStatus() == null || financialMaster.getPayStatus() != 1) {
                    logger.info("商品主单未支付，无需退款，goodsOrderMasterId={}, payStatus={}", goodsOrderMasterId, financialMaster.getPayStatus());
                    // 设置退款支付状态为未支付
                    OrderMaster orderMaster = orderMasterService.selectById(goodsOrderMasterId);
                    if (orderMaster != null) {
                        orderMaster.setRefundPayStatus(0);
                        orderMasterService.updateOrderMaster(orderMaster);
                        logger.info("商品主单无需退款，设置退款支付状态为未支付，goodsOrderMasterId={}", goodsOrderMasterId);
                    }
                    return AjaxResult.success("商品主单退单成功，无需退款（未支付）");
                }

                // 更新财务主单状态为退款中
                financialMaster.setPayStatus(3); // 3表示退款中
                financialMasterService.updateFinancialMaster(financialMaster);
                logger.info("更新财务主单状态为退款中，financialMasterId={}", financialMaster.getId());

                // 更新财务子单状态为退款中
                List<FinancialDetail> financialDetails = financialDetailService.selectByFinancialMasterId(financialMaster.getId());
                for (FinancialDetail detail : financialDetails) {
                    detail.setPayStatus(3); // 3表示退款中
                    financialDetailService.updateFinancialDetail(detail);
                }
                logger.info("更新财务子单状态为退款中，财务子单数量={}", financialDetails.size());

                // 调用支付撤销接口进行退款
                logger.info("开始调用支付撤销接口，paymentId={}, refundAmount={}", financialMaster.getPaymentId(), refundAmount);
                JSONObject reverseResult = adapayService.payReverse(goodsOrderMaster.getDeptId(), financialMaster.getPaymentId(), refundAmount.toPlainString(), RefundType.ROM);
                
                // 修复退款结果判断逻辑
                if (reverseResult != null && reverseResult.containsKey("reverseId") && reverseResult.getString("reverseId") != null) {
                    // 完善reverseId保存逻辑，添加空值检查
                    String reverseId = reverseResult.getString("reverseId");
                    if (reverseId != null && !reverseId.trim().isEmpty()) {
                        financialMaster.setReverseId(reverseId);
                        financialMaster.setPayStatus(4); // 更新为已退款状态
                        financialMasterService.updateFinancialMaster(financialMaster);
                        
                        // 更新财务子单状态为已退款
                        for (FinancialDetail detail : financialDetails) {
                            detail.setPayStatus(4); // 4表示已退款
                            financialDetailService.updateFinancialDetail(detail);
                        }
                        
                        // 设置退款支付状态为已支付
                        OrderMaster orderMaster = orderMasterService.selectById(goodsOrderMasterId);
                        if (orderMaster != null) {
                            orderMaster.setRefundPayStatus(1);
                            orderMasterService.updateOrderMaster(orderMaster);
                            logger.info("退款成功，设置退款支付状态为已支付，goodsOrderMasterId={}", goodsOrderMasterId);
                        }
                        
                        logger.info("退款成功，reverseId={}, goodsOrderMasterId={}", reverseId, goodsOrderMasterId);
                        return AjaxResult.success("商品主单退单退款成功，退款ID：" + reverseId);
                    } else {
                        logger.error("退款接口返回的reverseId为空，goodsOrderMasterId={}, reverseResult={}", goodsOrderMasterId, reverseResult);
                        throw new RuntimeException("退款失败：退款接口返回的reverseId为空");
                    }
                } else {
                    logger.error("退款接口返回异常结果，goodsOrderMasterId={}, reverseResult={}", goodsOrderMasterId, reverseResult);
                    throw new RuntimeException("退款失败：退款接口返回异常结果");
                }
            } catch (Exception refundException) {
                // 退款异常处理 - 抛出异常触发事务回滚
                logger.error("退款过程中发生异常，goodsOrderMasterId={}, 异常类型={}, 异常信息={}", 
                    goodsOrderMasterId, refundException.getClass().getSimpleName(), refundException.getMessage(), refundException);
                
                // 抛出RuntimeException触发事务回滚，确保退单和退款的原子性
                throw new RuntimeException("退款过程中发生异常：" + refundException.getMessage(), refundException);
            }
            
        } catch (Exception e) {
            logger.error("商品主单退单退款失败：goodsOrderMasterId={}, 错误信息={}", goodsOrderMasterId, e.getMessage(), e);
            return AjaxResult.error("商品主单退单退款失败：" + e.getMessage());
        }
    }

    /**
     * 师傅审核取消主订单申请
     *
     * @param orderMasterId 主订单ID
     * @param agree         0=不同意 1=同意
     */
    @PostMapping("/cancel/agree")
    @ResponseBody
    public AjaxResult cancelAgree(Long orderMasterId, Integer agree) {
        logger.info("师傅审核取消主订单申请，orderMasterId={}, agree={}", orderMasterId, agree);
        orderMasterService.cancelAgree(orderMasterId, agree);
        return AjaxResult.success();
    }

    @PostMapping("/app/getDetailListByMasterId")
    @ResponseBody
    public AjaxResult getDetailListByMasterId(@RequestBody Long orderMasterId) {
        try {
            List<OrderStandardDetail> orderStandardDetails = new ArrayList<>();
            List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(orderMasterId);
            // 查询主单金额
            FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderMasterId);
            BigDecimal totalMoney = financialMaster.getPayMoney();
            for (OrderDetail detail : detailList) {
                // 师傅信息
                Worker worker = workerService.selectById(detail.getWorkerId());

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

                // 查询子单加价记录
                // FinancialChangeRecord changeRecordQry = new FinancialChangeRecord();
                // changeRecordQry.setOrderDetailId(detail.getId());
                // List<FinancialChangeRecord> financialChangeRecords =
                // financialChangeRecordService.selectFinancialChangeRecordList(changeRecordQry);
                // if (CollectionUtils.isNotEmpty(financialChangeRecords)) {
                // totalMoney = totalMoney.add(financialChangeRecords.get(0).getChangeMoney());
                // }

                OrderStandardDetail detailRes = new OrderStandardDetail();
                detailRes.setOrderDetailId(detail.getId());
                detailRes.setOrderDetailCode(detail.getCode());
                detailRes.setWorkerName(workerName);
                detailRes.setRemark(workerName + "(" + detail.getCode() + ")");
                detailRes.setReturnReason(detail.getReturnReason());
                detailRes.setReturnReasonDetail(detail.getReturnReasonDetail());
                detailRes.setReturnImages(detail.getReturnImages());
                orderStandardDetails.add(detailRes);
            }

            for (OrderStandardDetail orderStandardDetail : orderStandardDetails) {
                orderStandardDetail.setPayMoney(totalMoney);
            }

            return AjaxResult.success(orderStandardDetails);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    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;
    }

    /**
     * 拒绝订单
     * 后台管理系统使用，可控制权限
     */
    @PostMapping("/reject")
    @ResponseBody
    public AjaxResult reject(OrderMaster orderMaster) {
        int i = orderMasterService.reject(orderMaster);
        return AjaxResult.success(i);
    }

    @GetMapping("/differentStatus/count")
    @ResponseBody
    public AjaxResult differentStatusOrderCount(OrderMaster orderMaster) {
        SysUser user = this.getSysUser();
        if (user != null && user.getRoles().get(0).getRoleId() == 101L) {
            orderMaster.setCreateBy(this.getSysUser().getUserId().toString());
        }
        return AjaxResult.success(orderMasterService.differentStatusOrderCount(orderMaster));
    }

    @GetMapping("/count")
    @ResponseBody
    public AjaxResult OrderMasterCount(OrderMaster orderMaster) {
        if (this.getSysUser() != null && this.getSysUser().getRoles().get(0).getRoleId() == 101L) {
            orderMaster.setCreateBy(this.getSysUser().getUserId().toString());
        }
        return AjaxResult.success(orderMasterService.countOrderMasterList(orderMaster));
    }

    @ResponseBody
    @Operation(summary = "获取当天订单统计数据", method = "GET")
    @GetMapping(path = "/statistics/now", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult statisticsNow() {
        return AjaxResult.success(orderMasterService.orderStatisticsReturnByNow());
    }

    @ResponseBody
    @Operation(summary = "获取全部订单统计数据", method = "GET")
    @GetMapping(path = "/statistics", produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult statistics() {
        return AjaxResult.success(orderMasterService.orderStatisticsReturn());
    }

    @PostMapping("/updateMasterAddress")
    @ResponseBody
    public AjaxResult updateMasterAddress(@RequestBody OrderMaster orderMaster) {

        return toAjax(orderMasterService.updateOrderMasterAddressById(orderMaster));
    }

    /**
     * 保存主单师傅备注
     */
    @PostMapping("/saveMasterWorkerRemark")
    @ResponseBody
    public AjaxResult saveMasterWorkerRemark(@RequestBody OrderMaster orderMaster) {
        try {
            if (orderMaster.getWorkerRemark() == null || orderMaster.getWorkerRemark().trim().isEmpty()) {
                return AjaxResult.error("师傅备注不能为空");
            }

            if (orderMaster.getId() == null) {
                return AjaxResult.error("主单ID不能为空");
            }

            int result = orderMasterService.saveMasterWorkerRemark(orderMaster.getId(), orderMaster.getWorkerRemark());
            if (result > 0) {
                return AjaxResult.success("主单师傅备注保存成功");
            } else {
                return AjaxResult.error("主单师傅备注保存失败");
            }
        } catch (Exception e) {
            logger.error("保存主单师傅备注失败", e);
            return AjaxResult.error("保存主单师傅备注失败：" + e.getMessage());
        }
    }

    /**
     * 计算商家与主单地址之间的距离
     *
     * @param orderMaster 主单信息
     * @param shop        商家信息
     * @return 带有距离信息的商家对象
     */
    private Shop calculateShopDistance(OrderMaster orderMaster, Shop shop) {
        try {
            // 直接使用主单地址获取经纬度
            logger.info("使用主单地址获取经纬度，主单id{}", orderMaster.getId());

            StringBuilder fullAddress = new StringBuilder();

            // 构建完整地址
            if (orderMaster.getProvinceId() != null) {
                SysArea province = sysAreaService.selectById(orderMaster.getProvinceId());
                if (province != null) {
                    fullAddress.append(province.getAreaName());
                }
            }

            if (orderMaster.getCityId() != null) {
                SysArea city = sysAreaService.selectById(orderMaster.getCityId());
                if (city != null) {
                    fullAddress.append(city.getAreaName());
                }
            }

            if (orderMaster.getCountryId() != null) {
                SysArea area = sysAreaService.selectById(orderMaster.getCountryId());
                if (area != null) {
                    fullAddress.append(area.getAreaName());
                }
            }

            if (orderMaster.getStreetId() != null) {
                SysArea street = sysAreaService.selectById(orderMaster.getStreetId());
                if (street != null) {
                    fullAddress.append(street.getAreaName());
                }
            }

            if (StringUtils.isNotEmpty(orderMaster.getAddress())) {
                fullAddress.append(orderMaster.getAddress());
            }

            String addressStr = fullAddress.toString();
            logger.info("构建的完整地址：{}", addressStr);

            if (StringUtils.isNotEmpty(addressStr)) {
                // 调用百度地图API获取经纬度
                Map<String, Double> coordinates = baiduMapUtils.getCoordinatesByAddress(shop.getProvinceName(),
                        shop.getCityName(), shop.getCountryName(), shop.getStreetName(), addressStr);

                if (coordinates != null && coordinates.containsKey("longitude")
                        && coordinates.containsKey("latitude")) {
                    BigDecimal lng = new BigDecimal(coordinates.get("longitude").toString());
                    BigDecimal lat = new BigDecimal(coordinates.get("latitude").toString());

                    logger.info("通过地址获取到经纬度：longitude={}, latitude={}", lng, lat);

                    // 计算距离
                    if (shop.getLongitude() != null && shop.getLatitude() != null) {

                        double distance = LocationUtils.getDistanceInMeters(
                                lat.doubleValue(),
                                lng.doubleValue(),
                                shop.getLatitude().doubleValue(),
                                shop.getLongitude().doubleValue());

                        String formattedDistance = LocationUtils.formatDistance(distance);
                        shop.setDistance(formattedDistance);
                        logger.info("通过地址获取经纬度后计算距离成功，商家[{}]与主单地址距离：{}", shop.getShopName(), formattedDistance);
                    }
                } else {
                    logger.warn("通过地址[{}]获取经纬度失败", addressStr);
                }
            } else {
                logger.warn("无法构建完整地址，跳过距离计算");
            }
        } catch (Exception e) {
            logger.error("计算商家与主单地址距离时发生异常", e);
        }

        return shop;
    }

    /**
     * 取消售后
     *
     * @param afterServiceRecordId 售后记录ID
     * @return 操作结果
     */
    @PostMapping("/after/cancel")
    @ResponseBody
    @Log(title = "取消售后管理", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelAfterService(@RequestParam("afterServiceRecordId") Long afterServiceRecordId,
                                       @RequestParam("platformHandleReason") String platformHandleReason) {
        try {
            // 参数校验
            if (afterServiceRecordId == null) {
                return AjaxResult.error("售后记录ID不能为空");
            }
            if (StringUtils.isEmpty(platformHandleReason)) {
                return AjaxResult.error("平台取消原因不能为空");
            }

            // 查询售后记录是否存在
            AfterServiceRecord afterServiceRecord = afterServiceRecordService.selectAfterServiceRecordById(String.valueOf(afterServiceRecordId));
            if (afterServiceRecord == null) {
                return AjaxResult.error("售后记录不存在");
            }

            // 检查售后记录状态是否允许取消
            if (afterServiceRecord.getAfterServiceStatus() != null && afterServiceRecord.getAfterServiceStatus() == 4) {
                return AjaxResult.error("售后记录已完成，无法取消");
            }

            // 更新售后记录状态
            AfterServiceRecord updateRecord = new AfterServiceRecord();
            updateRecord.setId(String.valueOf(afterServiceRecordId));
            // updateRecord.setAfterServiceStatus(3); // 3表示平台取消
            updateRecord.setPlatformRefund(BigDecimal.ZERO); // 平台退款金额设为0
            updateRecord.setAfterServiceStatus(2); // 售后状态改为已取消
            updateRecord.setPlatformHandleReason(platformHandleReason);
            updateRecord.setUpdateBy(getLoginName());
            updateRecord.setUpdateTime(new Date());

            afterServiceRecordService.updateAfterServiceRecord(updateRecord);

            // 同步更新子单和主单的售后纠纷状态
            // 1. 通过售后记录的orderDetailId查询对应的OrderDetail
            Long orderDetailId = afterServiceRecord.getOrderDetailId();
            if (orderDetailId != null) {
                OrderDetail orderDetail = orderDetailService.selectById(orderDetailId);
                if (orderDetail != null) {
                    // 2. 将OrderDetail的afterServiceStatus字段设为3（售后已取消）
                    OrderDetail updateOrderDetail = new OrderDetail();
                    updateOrderDetail.setId(orderDetailId);
                    updateOrderDetail.setAfterServiceStatus(3); // 0-无售后
                    updateOrderDetail.setUpdateBy(getLoginName());
                    updateOrderDetail.setUpdateTime(new Date());
            
                    orderDetailService.updateOrderDetail(updateOrderDetail);
                    
                    logger.info("更新子单售后状态成功：子单ID={}, 售后状态=0", orderDetailId);
                    
                    // 3. 通过OrderDetail的orderMasterId查询对应的OrderMaster
                    Long orderMasterId = orderDetail.getOrderMasterId();
                    if (orderMasterId != null) {
                        // 4. 检查该主单下是否还有其他售后纠纷记录
                        // 首先通过主单ID查询该主单下的所有子单
                        OrderDetail queryOrderDetail = new OrderDetail();
                        queryOrderDetail.setOrderMasterId(orderMasterId);
                        List<OrderDetail> orderDetails = orderDetailService.selectOrderDetailList(queryOrderDetail);
                        
                        // 获取所有子单ID列表
                        List<Long> orderDetailIds = orderDetails.stream()
                            .map(OrderDetail::getId)
                            .collect(Collectors.toList());
                        
                        // 通过子单ID列表查询对应的售后记录
                        List<AfterServiceRecord> masterAfterRecords = new ArrayList<>();
                        for (Long detailId : orderDetailIds) {
                            AfterServiceRecord queryParam = new AfterServiceRecord();
                            queryParam.setOrderDetailId(detailId);
                            List<AfterServiceRecord> detailAfterRecords = afterServiceRecordService.selectAfterServiceRecordList(queryParam);
                            masterAfterRecords.addAll(detailAfterRecords);
                        }
                        
                        // 过滤掉当前取消的售后记录，检查是否还有其他进行中的售后
                        boolean hasOtherAfterService = masterAfterRecords.stream()
                            .anyMatch(record -> !record.getId().equals(String.valueOf(afterServiceRecordId)) 
                                && record.getAfterServiceStatus() != null 
                                && record.getAfterServiceStatus() != 2); // 2表示已取消
                        
                        // 5. 如果没有其他售后纠纷则将OrderMaster的afterServiceStatus字段也设为0（无售后）
                        if (!hasOtherAfterService) {
                            OrderMaster updateOrderMaster = new OrderMaster();
                            updateOrderMaster.setId(orderMasterId);
                            updateOrderMaster.setAfterServiceStatus(0); // 0-无售后
                            updateOrderMaster.setUpdateBy(getLoginName());
                            updateOrderMaster.setUpdateTime(new Date());
                            orderMasterService.updateOrderMaster(updateOrderMaster);
                            
                            logger.info("更新主单售后状态成功：主单ID={}, 售后状态=0", orderMasterId);
                        } else {
                            logger.info("主单下还有其他售后记录，不更新主单售后状态：主单ID={}", orderMasterId);
                        }
                    }
                } else {
                    logger.warn("未找到对应的子单：子单ID={}", orderDetailId);
                }
            } else {
                logger.warn("售后记录中未找到对应的子单ID：售后记录ID={}", afterServiceRecordId);
            }

            logger.info("取消售后成功：售后记录ID={}, 操作人={}", 
                afterServiceRecordId, getLoginName());
            
            return AjaxResult.success("取消售后成功");
           
        } catch (Exception e) {
            logger.error("取消售后失败：售后记录ID={}, 错误信息={}", afterServiceRecordId, e.getMessage(), e);
            return AjaxResult.error("取消售后失败：" + e.getMessage());
        }
    }

    /**
     * 获取售后纠纷的主单ID列表
     * 通过查询AfterServiceRecord表中customerFinalCheck=0的记录
     * 
     * @return 售后纠纷的主单ID列表
     */
    private List<Long> getDisputeOrderMasterIds() {
        try {
            // 创建查询条件：customerFinalCheck = 0 表示售后纠纷
            AfterServiceRecord queryParam = new AfterServiceRecord();
            queryParam.setCustomerFinalCheck(0L);
            
            // 查询售后纠纷记录
            List<AfterServiceRecord> disputeRecords = afterServiceRecordService.selectAfterServiceRecordList(queryParam);
            
            if (disputeRecords.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 获取售后记录对应的订单详情ID
            List<Long> orderDetailIds = disputeRecords.stream()
                    .map(AfterServiceRecord::getOrderDetailId)
                    .distinct()
                    .collect(Collectors.toList());
            
            // 通过订单详情ID获取对应的主单ID
            Set<Long> orderMasterIds = new HashSet<>();
            for (Long orderDetailId : orderDetailIds) {
                OrderDetail orderDetail = orderDetailService.selectById(orderDetailId);
                if (orderDetail != null && orderDetail.getOrderMasterId() != null) {
                    orderMasterIds.add(orderDetail.getOrderMasterId());
                }
            }
            
            return new ArrayList<>(orderMasterIds);
                    
        } catch (Exception e) {
            logger.error("获取售后纠纷主单ID列表失败", e);
            return new ArrayList<>();
        }
    }
}
