package com.ghy.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ghy.common.adapay.model.AdapayStatusEnum;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.text.Convert;
import org.apache.commons.lang3.StringUtils;
import com.ghy.common.enums.OrderStatus;
import com.ghy.common.enums.PayStatus;
import com.ghy.common.enums.RefundType;
import com.ghy.common.enums.WxMsgEnum;
import com.ghy.common.exception.base.BaseException;
import com.ghy.common.utils.AdapayUtils;
import com.ghy.common.utils.ObjectUtils;
import com.ghy.common.utils.WechatMsgUtils;
import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.order.domain.AfterServiceImgs;
import com.ghy.order.domain.AfterServiceRecord;
import com.ghy.order.domain.OrderDetail;
import com.ghy.order.domain.OrderMaster;
import com.ghy.order.mapper.AfterServiceRecordMapper;
import com.ghy.order.mapper.OrderDetailMapper;
import com.ghy.order.service.IAfterServiceImgsService;
import com.ghy.order.service.IAfterServiceRecordService;
import com.ghy.order.service.OrderDetailService;
import com.ghy.order.service.OrderMasterService;
import com.ghy.payment.domain.FinancialDetail;
import com.ghy.payment.domain.FinancialMaster;
import com.ghy.payment.mapper.FinancialDetailMapper;
import com.ghy.payment.mapper.FinancialMasterMapper;
import com.ghy.payment.service.AdapayService;
import com.ghy.payment.service.FinancialDetailService;
import com.ghy.payment.service.FinancialMasterService;
import com.ghy.worker.domain.Worker;
import com.ghy.worker.service.WorkerService;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 售后记录Service业务层处理
 *
 * @author clunt
 * @date 2022-09-25
 */
@Slf4j
@Service
public class AfterServiceRecordServiceImpl implements IAfterServiceRecordService {
    @Resource
    private AfterServiceRecordMapper afterServiceRecordMapper;
    @Resource
    private IAfterServiceImgsService afterServiceImgsService;
    @Resource
    private FinancialDetailService financialDetailService;
    @Resource
    private OrderMasterService orderMasterService;
    @Resource
    private FinancialMasterService financialMasterService;
    @Resource
    private AdapayService adapayService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private WorkerService workerService;
    @Autowired
    private CustomerAddressService customerAddressService;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private FinancialDetailMapper financialDetailMapper;
    @Resource
    private FinancialMasterMapper financialMasterMapper;



    /**
     * 查询售后记录
     *
     * @param id 售后记录主键
     * @return 售后记录
     */
    @Override
    public AfterServiceRecord selectAfterServiceRecordById(String id) {
        return afterServiceRecordMapper.selectAfterServiceRecordById(id);
    }

    /**
     * 恢复财务金额
     * 当售后取消时，将之前扣减的金额恢复到原财务账单
     * @param afterServiceRecord 售后记录
     */
    public void restoreFinancialAmount(AfterServiceRecord afterServiceRecord) {
        try {
            log.info("开始恢复财务金额，售后记录ID：{}，原退款金额：{}", 
                    afterServiceRecord.getId(), afterServiceRecord.getOriginalRefund());
            
            // 检查是否有需要恢复的金额
            if (afterServiceRecord.getOriginalRefund() == null || 
                afterServiceRecord.getOriginalRefund().compareTo(BigDecimal.ZERO) <= 0) {
                log.info("无需恢复财务金额，售后记录ID：{}", afterServiceRecord.getId());
                return;
            }
            
            // 查询订单详情
            OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
            if (orderDetail == null) {
                log.error("订单详情不存在，无法恢复财务金额，订单详情ID：{}", afterServiceRecord.getOrderDetailId());
                return;
            }
            
            BigDecimal restoreAmount = afterServiceRecord.getOriginalRefund();
            
            // 判断是大师傅子单还是小师傅子单
            if (orderDetail.getOrderMasterId() != null && orderDetail.getOrderMasterId() > 0) {
                // 小师傅子单，恢复子财务单
                FinancialDetail financialDetail = financialDetailMapper.selectByOrderDetailId(orderDetail.getId());

                if (financialDetail != null) {
                    // 恢复支付金额和服务金额
                    BigDecimal newPayAmount = financialDetail.getPayMoney().add(restoreAmount);
                    
                    financialDetail.setPayMoney(newPayAmount);
                    financialDetail.setUpdateTime(new Date());
                    
                    financialDetailMapper.updateFinancialDetail(financialDetail);
                    
                    log.info("小师傅子单财务金额恢复成功，订单详情ID：{}，恢复金额：{}，新支付金额：{}", 
                            orderDetail.getId(), restoreAmount, newPayAmount);
                } else {
                    log.error("子财务单不存在，无法恢复财务金额，订单详情ID：{}", orderDetail.getId());
                }
            } else {
                // 大师傅子单，恢复主财务单
                FinancialMaster financialMaster = financialMasterMapper.selectByOrderMasterId(orderDetail.getOrderMasterId());
                if (financialMaster != null) {
                    // 恢复支付金额和服务金额
                    BigDecimal newPayAmount = financialMaster.getPayMoney().add(restoreAmount);
                    BigDecimal newServiceAmount = financialMaster.getServerMoney().add(restoreAmount);
                    
                    financialMaster.setPayMoney(newPayAmount);
                    financialMaster.setServerMoney(newServiceAmount);
                    financialMaster.setUpdateTime(new Date());
                    
                    financialMasterMapper.updateFinancialMaster(financialMaster);
                    
                    log.info("大师傅子单财务金额恢复成功，主订单ID：{}，恢复金额：{}，新支付金额：{}，新服务金额：{}", 
                            orderDetail.getOrderMasterId(), restoreAmount, newPayAmount, newServiceAmount);
                } else {
                    log.error("主财务单不存在，无法恢复财务金额，主订单ID：{}", orderDetail.getOrderMasterId());
                }
            }
            
            log.info("财务金额恢复完成，售后记录ID：{}，恢复金额：{}", 
                    afterServiceRecord.getId(), restoreAmount);
                    
        } catch (Exception e) {
            log.error("恢复财务金额异常，售后记录ID：{}，错误：{}", 
                    afterServiceRecord.getId(), e.getMessage(), e);
        }
    }

    /**
     * 查询售后记录列表
     *
     * @param afterServiceRecord 售后记录
     * @return 售后记录
     */
    @Override
    public List<AfterServiceRecord> selectAfterServiceRecordList(AfterServiceRecord afterServiceRecord) {
        if(afterServiceRecord == null){
            afterServiceRecord = new AfterServiceRecord();
            afterServiceRecord.setNeedImgs(false);
        }
        List<AfterServiceRecord> list = afterServiceRecordMapper.selectAfterServiceRecordList(afterServiceRecord);
        if(afterServiceRecord.getNeedImgs() != null && !afterServiceRecord.getNeedImgs()){
            return list;
        }
        list.forEach(record -> {
            AfterServiceImgs param = new AfterServiceImgs();
            param.setAfterServiceRecordId(Long.valueOf(record.getId()));
            record.setImgsList(afterServiceImgsService.selectAfterServiceImgsList(param));
        });
        return list;
    }

    /**
     * 新增售后记录
     *
     * @param afterServiceRecord 售后记录
     * @return 结果
     */
    @Override
    public int insertAfterServiceRecord(AfterServiceRecord afterServiceRecord) {
        AfterServiceRecord unfinished = unfinished(afterServiceRecord.getOrderDetailId());
        if (unfinished != null) {
            log.warn("订单[{}]存在未完成的售后记录", afterServiceRecord.getOrderDetailId());
            throw new BaseException("存在未完成的售后记录，请勿重复申请！");
        }
        // 根据订单类型自动设置售后大类
        setAfterServiceCategory(afterServiceRecord);
        

        
        int result = afterServiceRecordMapper.insertAfterServiceRecord(afterServiceRecord);
        
        // 暂停确认中倒计时
        pauseConfirmTimeout(afterServiceRecord.getOrderDetailId());
        // 发一起一次售后发起通知
        // 通知师傅新订单
        try {
            OrderDetail orderDetail =  orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
            OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
            Worker worker = workerService.selectById(orderDetail.getWorkerId());
            // 推送公众号通知数据。
            // 消息组装。
            Map<String, Object> paramsNew = new HashMap<>();
            // 订单编号
            paramsNew.put("thing9", "您收到1条售后/投诉单");
            // 名称
            paramsNew.put("thing11", "请进入【我的订单--售后中】操作处理");
            CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
            paramsNew.put("thing10", address.getName());
            // 预约时间
            paramsNew.put("time13", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
            WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.AFTER_SALES_ORDER, paramsNew);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (afterServiceRecord.getImgsList() != null && afterServiceRecord.getImgsList().size() > 0) {
            afterServiceRecord.getImgsList().forEach(imgUrl -> {
                imgUrl.setAfterServiceRecordId(Long.valueOf(afterServiceRecord.getId()));
                afterServiceImgsService.insertAfterServiceImgs(imgUrl);
            });
        }
        return result;
    }

    /**
     * 查询未完成的售后记录 用于判断是否可以申请售后
     *
     * @return 未完成的售后记录
     */
    public AfterServiceRecord unfinished(Long orderDetailId) {
        return afterServiceRecordMapper.unfinished(orderDetailId);
    }

    public AfterServiceRecord getUnfinishedByOrderDetailId(Long orderDetailId) {
        return afterServiceRecordMapper.unfinished(orderDetailId);
    }

    /**
     * 修改售后记录
     *
     * @param param 售后记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateAfterServiceRecord(AfterServiceRecord param) throws BaseAdaPayException {
        Long one = 1L;
        Long two = 2L;
        AfterServiceRecord afterServiceRecord = this.selectAfterServiceRecordById(param.getId());
        if (param.getIsAutoProcessed() != null) {
            afterServiceRecord.setIsAutoProcessed(param.getIsAutoProcessed());
        }
        if (param.getAfterServiceStatus() != null) {
            afterServiceRecord.setAfterServiceStatus(param.getAfterServiceStatus());
        }
        if (param.getCustomerFinalCheck() != null) {
            afterServiceRecord.setCustomerFinalCheck(param.getCustomerFinalCheck());
        }
        if (param.getWorkerReceiveConfirm() != null) {
            afterServiceRecord.setWorkerReceiveConfirm(param.getWorkerReceiveConfirm());
        }
        Assert.notNull(afterServiceRecord, "售后记录不存在！");
        OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
        afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
        // 检查orderDetail是否为null，避免NullPointerException
        if (orderDetail == null) {
            log.error("订单详情不存在，售后记录ID：{}，订单详情ID：{}", afterServiceRecord.getId(), afterServiceRecord.getOrderDetailId());
            return AjaxResult.error("订单详情不存在，无法处理售后记录");
        }
        
        boolean drawCash = orderDetail.getDrawCashTime() != null;
        // 更新为售后未超时
        orderDetailService.updateAfterTimeout(afterServiceRecord.getOrderDetailId(), 0, 0);
        log.info("客户是否同意{}，客户操作{}",one.equals(param.getCustomerFinalCheck()),param);
        log.info("修改后的售后订单{}",orderDetail);
        
        Boolean isCustomerFinalCheck = param.getCustomerFinalCheck()==null;

        // 新增：处理客户同意上门重做方案
        if (param.getCustomerAgreeRedo() != null&&isCustomerFinalCheck) {
            afterServiceRecord.setCustomerAgreeRedo(param.getCustomerAgreeRedo());
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            afterServiceRecord.setRedoCompleteTime(null);
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            log.info("客户同意上门重做方案状态已更新：{}", param.getCustomerAgreeRedo());
            return AjaxResult.success("客户同意方案状态已更新");
        }
        
        // 新增：处理师傅重做/补做完成
        if (isCustomerFinalCheck&&param.getWorkerFeedbackResult() != null && param.getWorkerFeedbackResult().equals(3L)) {
            afterServiceRecord.setWorkerFeedbackResult(3L);
            afterServiceRecord.setRedoCompleteTime(new Date());
            if (param.getRedoCompleteRemark() != null) {
                afterServiceRecord.setRedoCompleteRemark(param.getRedoCompleteRemark());
            }
            if (param.getRedoCompleteImages() != null) {
                afterServiceRecord.setRedoCompleteImages(param.getRedoCompleteImages());
            }
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            log.info("师傅重做/补做完成，记录ID：{}，完成时间：{}", param.getId(), afterServiceRecord.getRedoCompleteTime());
            return AjaxResult.success("重做/补做完成状态已更新");
        }
        
        // 新增：处理师傅反馈结果为0或1时，设置redoCompleteTime为当前时间+36小时
        if (isCustomerFinalCheck&&param.getWorkerFeedbackResult() != null && (param.getWorkerFeedbackResult().equals(0L) || param.getWorkerFeedbackResult().equals(1L))) {
            afterServiceRecord.setWorkerFeedbackResult(param.getWorkerFeedbackResult());
            // 设置当前时间推后36小时
            // Calendar calendar = Calendar.getInstance();
            // calendar.setTime(new Date());
            // // calendar.add(Calendar.HOUR_OF_DAY, 36);
            afterServiceRecord.setRedoCompleteTime(new Date());
            
            // 处理师傅反馈相关字段
            if (param.getWorkerFeedbackReasonType() != null) {
                afterServiceRecord.setWorkerFeedbackReasonType(param.getWorkerFeedbackReasonType());
            }
            if (param.getWorkerFeedbackReason() != null) {
                afterServiceRecord.setWorkerFeedbackReason(param.getWorkerFeedbackReason());
            }
            if (param.getWorkerFeedbackImages() != null) {
                afterServiceRecord.setWorkerFeedbackImages(param.getWorkerFeedbackImages());
            }
            if (param.getAgreedRefund() != null) {
                afterServiceRecord.setAgreedRefund(param.getAgreedRefund());
            }
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            log.info("师傅反馈结果为{}，记录ID：{}，redoCompleteTime设置为：{}", param.getWorkerFeedbackResult(), param.getId(), afterServiceRecord.getRedoCompleteTime());
            return AjaxResult.success("师傅反馈结果已更新");
        }
        
        if (param.getCustomerFinalCheck()!=null ) {
             afterServiceRecord.setRedoCompleteTime(null);
            // 检查是否已经被自动处理过，防止重复退款
            if (afterServiceRecord.getIsAutoProcessed() != null && afterServiceRecord.getIsAutoProcessed() == 1) {
                log.warn("售后记录[{}]已被自动处理，不允许手动重复操作", afterServiceRecord.getId());
                return AjaxResult.error("该售后记录已被系统自动处理，无法重复操作");
            }
            
            // 检查师傅是否已经重做完成
            if (afterServiceRecord.getWorkerFeedbackResult() != null && afterServiceRecord.getWorkerFeedbackResult().equals(3L)) {
                // 师傅已重做完成
                if (one.equals(param.getCustomerFinalCheck())) {
                    // 客户同意重做结果，订单完成结束，不执行退款
                    afterServiceRecord.setCustomerFinalCheck(1L);

                    // 如果redoCompleteTime字段有值，且师傅操作为0或1，且客户同意，则将其设置为null
                    if (afterServiceRecord.getRedoCompleteTime() != null && 
                        (afterServiceRecord.getWorkerFeedbackResult() != null && 
                         (afterServiceRecord.getWorkerFeedbackResult().equals(0L) || afterServiceRecord.getWorkerFeedbackResult().equals(1L)))) {
                        afterServiceRecord.setRedoCompleteTime(null);
                    }
                    afterServiceRecord.setRefundApplyTime(new Date());
                    log.info("师傅重做完成后，客户同意重做结果，订单完成结束，不执行退款");
                    
                    // // 售后客户回复通知
                    // try {
                    //     Worker worker = workerService.selectById(orderDetail.getWorkerId());
                    //     OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    //     // 推送公众号通知数据。
                    //     Map<String, Object> paramsNew = new HashMap<>();
                    //     paramsNew.put("thing9", "您有1条售后/投诉单，客户已回复");
                    //     paramsNew.put("thing11", "请进入【我的订单--售后中】查看处理");
                    //     CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                    //     paramsNew.put("thing10", address.getName());
                    //     paramsNew.put("time13", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                    //     WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.AFTER_SALES_ORDER, paramsNew);
                    // } catch (Exception e) {
                    //     log.error(e.getMessage(), e);
                    // }
                    
                    afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                    
                    // 恢复确认中倒计时
                    resumeConfirmTimeout(afterServiceRecord.getOrderDetailId());
                    
                    return AjaxResult.success("订单完成结束");
                } else {
                    // 客户不同意重做结果，按之前的逻辑走（可能需要退款）
                    log.info("师傅重做完成后，客户不同意重做结果，按原逻辑处理");
                    // 如果redoCompleteTime字段有值，且师傅操作为0或1，且客户不同意，则将其设置为null
                    if (afterServiceRecord.getRedoCompleteTime() != null && 
                        (afterServiceRecord.getWorkerFeedbackResult() != null && 
                         (afterServiceRecord.getWorkerFeedbackResult().equals(0L) || afterServiceRecord.getWorkerFeedbackResult().equals(1L)))) {
                        afterServiceRecord.setRedoCompleteTime(null);
                    }
                    // 客户不同意时，保存不同意图片和理由
                    if (param.getCustomerDisagreeImages() != null) {
                        afterServiceRecord.setCustomerDisagreeImages(param.getCustomerDisagreeImages());
                    }
                    if (param.getCustomerDisagreeReason() != null) {
                        afterServiceRecord.setCustomerDisagreeReason(param.getCustomerDisagreeReason());
                    }

                    // 继续执行下面的退款逻辑
                }
            }
            
            // 师傅未重做完成，按原逻辑处理退款
            if (one.equals(param.getCustomerFinalCheck())) {
                afterServiceRecord.setCustomerFinalCheck(1L);

                // 如果redoCompleteTime字段有值，且师傅操作为0或1，且客户同意，则将其设置为null
                if (afterServiceRecord.getRedoCompleteTime() != null && 
                    (afterServiceRecord.getWorkerFeedbackResult() != null && 
                     (afterServiceRecord.getWorkerFeedbackResult().equals(0L) || afterServiceRecord.getWorkerFeedbackResult().equals(1L)))) {
                    afterServiceRecord.setRedoCompleteTime(null);
                }
                

            }else{
                afterServiceRecord.setCustomerFinalCheck(0L);

                // 如果redoCompleteTime字段有值，且师傅操作为0或1，且客户不同意，则将其设置为null
                if (afterServiceRecord.getRedoCompleteTime() != null && 
                    (afterServiceRecord.getWorkerFeedbackResult() != null && 
                     (afterServiceRecord.getWorkerFeedbackResult().equals(0L) || afterServiceRecord.getWorkerFeedbackResult().equals(1L)))) {
                    afterServiceRecord.setRedoCompleteTime(null);
                }
                // 客户不同意时，保存不同意图片和理由
                if (param.getCustomerDisagreeImages() != null) {
                    afterServiceRecord.setCustomerDisagreeImages(param.getCustomerDisagreeImages());
                }
                if (param.getCustomerDisagreeReason() != null) {
                    afterServiceRecord.setCustomerDisagreeReason(param.getCustomerDisagreeReason());
                }
                  try {
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    if (orderMaster != null) {
                        orderMaster.setAfterServiceStatus(1);
                        orderMasterService.updateOrderMaster(orderMaster);
                        log.info("客户不同意处理方案，已将主单[{}]标记为售后纠纷状态", orderMaster.getId());
                        
                        // 同时更新子单的售后纠纷状态
                        orderDetail.setAfterServiceStatus(1);
                        orderDetailService.updateOrderDetail(orderDetail);
                        log.info("客户不同意处理方案，已将子单[{}]标记为售后纠纷状态", orderDetail.getId());
                    }
                } catch (Exception e) {
                    log.error("更新主单和子单售后纠纷状态失败，主单ID：{}，子单ID：{}", orderDetail.getOrderMasterId(), orderDetail.getId(), e);
                }

            }
            afterServiceRecord.setRefundApplyTime(new Date());
            
            // 售后客户回复通知
            // 通知师傅新订单
            try {
                Worker worker = workerService.selectById(orderDetail.getWorkerId());
                OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                // 推送公众号通知数据。
                // 消息组装。
                Map<String, Object> paramsNew = new HashMap<>();
                // 订单编号
                paramsNew.put("thing9", "您有1条售后/投诉单，客户已回复");
                // 名称
                paramsNew.put("thing11", "请进入【我的订单--售后中】查看处理");
                CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                paramsNew.put("thing10", address.getName());
                // 预约时间
                paramsNew.put("time13", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.AFTER_SALES_ORDER, paramsNew);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
             if (afterServiceRecord.getCustomerFinalCheck().equals(0L)) {
                afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                return AjaxResult.success("客户不同意师傅方案，进入售后纠纷处理。");
            }
            // 新增：如果师傅拒绝（workerFeedbackResult=2）且客户同意，则不执行退款流程
            if (afterServiceRecord.getWorkerFeedbackResult() != null && afterServiceRecord.getWorkerFeedbackResult().equals(0L) && one.equals(param.getCustomerFinalCheck())) {
                log.info("师傅拒绝且客户同意，不执行退款流程，售后记录ID：{}", afterServiceRecord.getId());
                afterServiceRecord.setRefundApplyTime(new Date());
                afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                return AjaxResult.success("客户同意师傅拒绝方案，售后流程结束，不执行退款");
            }
            
            // DrawCashTime不为空说明已经发起过分账
            if (drawCash) {
                log.warn("子单[{}]已发起分账，不能退款", afterServiceRecord.getOrderDetailId());
                afterServiceRecord.setOriginalRefund(BigDecimal.ZERO);
                afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                return AjaxResult.error("本单已划款，师傅/服务人员已到帐或即将到帐，双方达成退款的，请对方线下支付后点对方已退款");
            } else {
                // 执行退款逻辑
                int refundResult = agreeRefund(afterServiceRecord);
                
                // 退款成功后，将售后状态设置为已完成
                if (refundResult > 0) {
                    try {
                        // 设置售后记录状态为已完成（2表示已完成）
                        afterServiceRecord.setAfterServiceStatus(2);
                        afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                        log.info("客户同意处理方案且退款成功，已将售后记录[{}]状态设置为已完成", afterServiceRecord.getId());
                        
                        // 更新对应主单和子单的售后状态为已完成
                        OrderDetail orderDetail1 = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
                        if (orderDetail1 != null) {
                            // 只有当子单的售后状态为售后纠纷（1）时，才修改为已完成（2）
                            if (orderDetail1.getAfterServiceStatus() != null && orderDetail1.getAfterServiceStatus() == 1) {
                                orderDetail1.setAfterServiceStatus(2);
                                orderDetailService.updateOrderDetail(orderDetail1);
                                log.info("已将子单[{}]售后状态从售后纠纷设置为已完成", orderDetail1.getId());
                            }
                            
                            OrderMaster orderMaster = orderMasterService.selectById(orderDetail1.getOrderMasterId());
                            if (orderMaster != null) {
                                // 只有当主单的售后状态为售后纠纷（1）时，才修改为已完成（2）
                                if (orderMaster.getAfterServiceStatus() != null && orderMaster.getAfterServiceStatus() == 1) {
                                    orderMaster.setAfterServiceStatus(2);
                                    orderMasterService.updateOrderMaster(orderMaster);
                                    log.info("已将主单[{}]售后状态从售后纠纷设置为已完成", orderMaster.getId());
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("更新售后完成状态失败，售后记录ID：{}", afterServiceRecord.getId(), e);
                    }
                }
            }
//            orderDetailService.updateAfterTimeout(afterServiceRecord.getOrderDetailId(), 0, 0);
        } else if (one.equals(afterServiceRecord.getWorkerFeedbackResult()) && param.getCustomerFinalCheck() == null) {
            // 师傅同意 且 客户未处理
            afterServiceRecordMapper.updateAfterServiceRecord(param);
            return drawCash ? AjaxResult.error("本单银联已确认货款结算完毕(订单支付完成)，款项已到达或即将到达您所绑定帐户，需同意退款的同意后您线下与客户另行操作，系统无法提供原路返回退款!") : AjaxResult.success();
        } else {
            if(two.equals(param.getCustomerFinalCheck())){
                // 客户不同意师傅的意见,如果订单是确认中,则需要将订单改为服务中
                if(orderDetail.getOrderStatus() == OrderStatus.FINISH_CHECK.code() && orderDetail.getDrawCashTime()!= null ){
                    orderDetail.setOrderStatus(OrderStatus.SERVER.code());
                    orderDetailService.updateOrderDetail(orderDetail);
                    // 如果发现是唯一子单,则需要将主单也更新为服务中
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    if(orderMaster.getOrderStatus() == OrderStatus.FINISH_CHECK.code()){
                        orderMaster.setOrderStatus(OrderStatus.SERVER.code());
                        orderMasterService.updateOrderMaster(orderMaster);
                    }
                }
            }
            afterServiceRecordMapper.updateAfterServiceRecord(param);
        }
        return AjaxResult.success();
    }

    /**
     * 修改商品售后记录
     *
     * @param param 售后记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateGoodsAfterServiceRecord(AfterServiceRecord param) throws BaseAdaPayException {
        Long one = 1L;
        Long two = 2L;
        AfterServiceRecord afterServiceRecord = this.selectAfterServiceRecordById(param.getId());
          if (param.getIsAutoProcessed() != null) {
            afterServiceRecord.setIsAutoProcessed(param.getIsAutoProcessed());
        }
        if (param.getAfterServiceStatus() != null) {
            afterServiceRecord.setAfterServiceStatus(param.getAfterServiceStatus());
        }
        if (param.getCustomerFinalCheck() != null) {
            afterServiceRecord.setCustomerFinalCheck(param.getCustomerFinalCheck());
        }
        if (param.getWorkerReceiveConfirm() != null) {
            afterServiceRecord.setWorkerReceiveConfirm(param.getWorkerReceiveConfirm());
        }
        afterServiceRecord.setUpdateTime(new Date());
        afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
        Assert.notNull(afterServiceRecord, "售后记录不存在！");
        OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
        boolean drawCash = orderDetail.getDrawCashTime() != null;
        // 更新为售后未超时
        orderDetailService.updateAfterTimeout(afterServiceRecord.getOrderDetailId(), 0, 0);
        log.info("商品售后-客户是否同意{}，客户操作{}",one.equals(param.getCustomerFinalCheck()),param);
        log.info("商品售后-修改后的售后订单{}",orderDetail);
        
        // 新增：处理客户同意上门重做方案
        if (param.getCustomerAgreeRedo() != null) {
            afterServiceRecord.setCustomerAgreeRedo(param.getCustomerAgreeRedo());
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            afterServiceRecord.setRedoCompleteTime(null);
            afterServiceRecord.setWorkerResendPlanTime(null);
              // 设置客户操作时间
            afterServiceRecord.setCustomerOperationTime(new Date());
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            log.info("商品售后-客户同意上门重做方案状态已更新：{}", param.getCustomerAgreeRedo());
            return AjaxResult.success("客户同意方案状态已更新");
        }
        
        // 新增：处理师傅重做/补做完成
        if (param.getWorkerFeedbackResult() != null && param.getWorkerFeedbackResult().equals(3L)) {
            afterServiceRecord.setWorkerFeedbackResult(3L);
            afterServiceRecord.setRedoCompleteTime(new Date());
            if (param.getRedoCompleteRemark() != null) {
                afterServiceRecord.setRedoCompleteRemark(param.getRedoCompleteRemark());
            }
            if (param.getRedoCompleteImages() != null) {
                afterServiceRecord.setRedoCompleteImages(param.getRedoCompleteImages());
            }
            // 新增：处理重发/补发相关字段
            afterServiceRecord.setWorkerResendTime(new Date());
            if (param.getWorkerResendType() != null) {
                afterServiceRecord.setWorkerResendType(param.getWorkerResendType());
            }
            if (param.getWorkerResendTrackingNumber() != null) {
                afterServiceRecord.setWorkerResendTrackingNumber(param.getWorkerResendTrackingNumber());
            }
            if (param.getWorkerResendRemark() != null) {
                afterServiceRecord.setWorkerResendRemark(param.getWorkerResendRemark());
            }
            if (param.getWorkerResendImages() != null) {
                afterServiceRecord.setWorkerResendImages(param.getWorkerResendImages());
            }
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            afterServiceRecord.setRedoCompleteTime(null);
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            log.info("商品售后-师傅重做/补做完成，记录ID：{}，完成时间：{}", param.getId(), afterServiceRecord.getRedoCompleteTime());
            return AjaxResult.success("重做/补做完成状态已更新");
        }
        
        // 新增：处理师傅重发/补发方案
        if (param.getWorkerResendPlan() != null) {
            // 验证快递/物流方式必须提供单号
            if (param.getWorkerResendType() != null && param.getWorkerResendType() == 1) {
                if (param.getWorkerResendTrackingNumber() == null || param.getWorkerResendTrackingNumber().trim().isEmpty()) {
                    return AjaxResult.error("快递/物流方式必须提供物流单号");
                }
            }
            
            afterServiceRecord.setWorkerResendPlan(param.getWorkerResendPlan());
            afterServiceRecord.setWorkerResendTime(new Date());
            if (param.getWorkerFeedbackResult() != null && param.getWorkerFeedbackResult().equals(2L)) {
                // afterServiceRecord.setWorkerFeedbackResult(2L);
                afterServiceRecord.setWorkerResendPlanTime(new Date());
            }
            afterServiceRecord.setWorkerResendType(param.getWorkerResendType()); // 1-快递/物流，2-送货上门，3-自提
            afterServiceRecord.setWorkerResendTrackingNumber(param.getWorkerResendTrackingNumber()); // 物流单号
            // 新增：设置师傅重发/补发备注和图片
            if (param.getWorkerResendRemark() != null) {
                afterServiceRecord.setWorkerResendRemark(param.getWorkerResendRemark());
            }
            if (param.getWorkerResendImages() != null) {
                afterServiceRecord.setWorkerResendImages(param.getWorkerResendImages());
            }
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            
            // 发送重发补发通知给客户
            // sendWorkerResendNotification(orderDetail, afterServiceRecord);
            
            log.info("商品售后-师傅重发/补发方案已提交，记录ID：{}，方案：{}，方式：{}，单号：{}", 
                    param.getId(), param.getWorkerResendPlan(), param.getWorkerResendType(), param.getWorkerResendTrackingNumber());
            return AjaxResult.success("重发/补发方案已提交，等待客户确认");
        }
        
        // 新增：处理师傅操作处理按键（收货状态和同意处理方式）
        if (param.getWorkerReceiveStatus() != null && param.getWorkerAgreeType() != null) {
            afterServiceRecord.setWorkerReceiveStatus(param.getWorkerReceiveStatus());
            afterServiceRecord.setWorkerAgreeType(param.getWorkerAgreeType());
            //  Calendar calendar = Calendar.getInstance();
            // calendar.setTime(new Date());
            // calendar.add(Calendar.HOUR_OF_DAY, 36);
            afterServiceRecord.setRedoCompleteTime(new Date());
            // 处理师傅反馈相关字段
            if (param.getWorkerFeedbackReasonType() != null) {
                afterServiceRecord.setWorkerFeedbackReasonType(param.getWorkerFeedbackReasonType());
            }
            if (param.getWorkerFeedbackReason() != null) {
                afterServiceRecord.setWorkerFeedbackReason(param.getWorkerFeedbackReason());
            }
            if (param.getWorkerFeedbackResult() != null) {
                afterServiceRecord.setWorkerFeedbackResult(param.getWorkerFeedbackResult());
            }
            if (param.getAgreedRefund() != null) {
                afterServiceRecord.setAgreedRefund(param.getAgreedRefund());
            }
            if (param.getUpdateBy() != null) {
                afterServiceRecord.setUpdateBy(param.getUpdateBy());
            }
            if (param.getRefund() != null) {
                afterServiceRecord.setRefund(param.getRefund());
            }

            // 根据不同的状态和方式执行不同的业务逻辑
           // handleWorkerProcessLogic(afterServiceRecord, orderDetail);
            
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            
            log.info("商品售后-师傅处理操作已提交，记录ID：{}，收货状态：{}，同意方式：{}", 
                    param.getId(), param.getWorkerReceiveStatus(), param.getWorkerAgreeType());
            return AjaxResult.success("师傅处理操作已提交");
        }
        
        if (param.getCustomerFinalCheck()!=null ) {
             afterServiceRecord.setRedoCompleteTime(null);
            // 检查是否已经被自动处理过，防止重复退款
            if (afterServiceRecord.getIsAutoProcessed() != null && afterServiceRecord.getIsAutoProcessed() == 1) {
                log.warn("商品售后记录[{}]已被自动处理，不允许手动重复操作", afterServiceRecord.getId());
                return AjaxResult.error("该售后记录已被系统自动处理，无法重复操作");
            }
            
            // 商品售后的处理逻辑
            if (one.equals(param.getCustomerFinalCheck())) {
                afterServiceRecord.setCustomerFinalCheck(1L);
                // 如果redoCompleteTime字段有值，且师傅操作为0或1，且客户同意，则将其设置为null
                if (afterServiceRecord.getRedoCompleteTime() != null && 
                    (afterServiceRecord.getWorkerFeedbackResult() != null && 
                     (afterServiceRecord.getWorkerFeedbackResult().equals(0L) || afterServiceRecord.getWorkerFeedbackResult().equals(1L)))) {
                    afterServiceRecord.setRedoCompleteTime(null);
                }
                // 保存操作者和退款金额
                if (param.getUpdateBy() != null) {
                    afterServiceRecord.setUpdateBy(param.getUpdateBy());
                }
                if (param.getRefund() != null) {
                    afterServiceRecord.setRefund(param.getRefund());
                }
                log.info("商品售后-客户同意处理方案");
              
                
                // 商品售后特殊处理：客户同意且师傅选择即时退单退款时立即执行退款
                if (afterServiceRecord.getWorkerAgreeType() != null && afterServiceRecord.getWorkerAgreeType() == 1) {
                    log.info("商品售后-客户同意且师傅选择即时退单退款，立即执行退款，记录ID：{}", param.getId());
                    afterServiceRecord.setRefundApplyTime(new Date());
                    
                    // 执行退款逻辑
                    try {
                        executeRefundLogic(afterServiceRecord);
                        log.info("商品售后-即时退单退款执行成功，记录ID：{}", param.getId());
                    } catch (Exception e) {
                        log.error("商品售后-即时退单退款执行失败，记录ID：{}，错误：{}", param.getId(), e.getMessage());
                    }
                } else if(afterServiceRecord.getIsAutoProcessed() != null && afterServiceRecord.getIsAutoProcessed() == 1){
                   log.info("商品售后-定时器自动处理，立即执行退款，记录ID：{}", param.getId());
                    afterServiceRecord.setRefundApplyTime(new Date());
                    // orderDetail.setAfterServiceStatus(2);
                    // 执行退款逻辑
                    try {
                        executeRefundLogic(afterServiceRecord);
                        log.info("商品售后-即时退单退款执行成功，记录ID：{}", param.getId());
                    } catch (Exception e) {
                        log.error("商品售后-即时退单退款执行失败，记录ID：{}，错误：{}", param.getId(), e.getMessage());
                    }
                }
                else{
                    // 注意：客户同意重发补发方案后，不立即结束售后流程
                    // 而是等待倒计时结束，由定时器自动处理
                    // 这样可以给师傅时间完成重发补发操作
                    log.info("商品售后-非即时退款方式，等待师傅确认收货后执行退款，记录ID：{}，同意方式：{}", 
                            param.getId(), afterServiceRecord.getWorkerAgreeType());
                }
                
            } else if (afterServiceRecord.getCustomerFinalCheck() == null) {
                afterServiceRecord.setCustomerFinalCheck(0L);
                // 如果redoCompleteTime字段有值，且师傅操作为0或1，且客户不同意，则将其设置为null
                if (afterServiceRecord.getRedoCompleteTime() != null && 
                    (afterServiceRecord.getWorkerFeedbackResult() != null && 
                     (afterServiceRecord.getWorkerFeedbackResult().equals(0L) || afterServiceRecord.getWorkerFeedbackResult().equals(1L)))) {
                    afterServiceRecord.setRedoCompleteTime(null);
                }
                // 客户不同意时，保存不同意图片和理由
                if (param.getCustomerDisagreeImages() != null) {
                    afterServiceRecord.setCustomerDisagreeImages(param.getCustomerDisagreeImages());
                }
                if (param.getCustomerDisagreeReason() != null) {
                    afterServiceRecord.setCustomerDisagreeReason(param.getCustomerDisagreeReason());
                }
                // 保存操作者和退款金额
                if (param.getUpdateBy() != null) {
                    afterServiceRecord.setUpdateBy(param.getUpdateBy());
                }
                if (param.getRefund() != null) {
                    afterServiceRecord.setRefund(param.getRefund());
                }

                // 客户不同意时，将对应主单的afterServiceStatus字段设置为1（售后纠纷状态）
                try {
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    if (orderMaster != null) {
                        orderMaster.setAfterServiceStatus(1);
                        orderMasterService.updateOrderMaster(orderMaster);
                        log.info("客户不同意处理方案，已将主单[{}]标记为售后纠纷状态", orderMaster.getId());
                    }
                    
                    // 同时更新子单的售后纠纷状态
                    orderDetail.setAfterServiceStatus(1);
                    orderDetailService.updateOrderDetail(orderDetail);
                    log.info("客户不同意处理方案，已将子单[{}]标记为售后纠纷状态", orderDetail.getId());
                } catch (Exception e) {
                    log.error("更新主单/子单售后纠纷状态失败，主单ID：{}，子单ID：{}", orderDetail.getOrderMasterId(), orderDetail.getId(), e);
                }

                log.info("商品售后-客户不同意处理方案");
            }
            
            afterServiceRecord.setRefundApplyTime(new Date());
            
            // 商品售后客户回复通知
            // 通知师傅新订单
            try {
                Worker worker = workerService.selectById(orderDetail.getWorkerId());
                OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                // 推送公众号通知数据。
                // 消息组装。
                Map<String, Object> paramsNew = new HashMap<>();
                // 订单编号
                paramsNew.put("thing9", "您有1条售后/投诉单，客户已回复");
                // 名称
                paramsNew.put("thing11", "请进入【我的订单--售后中】查看处理");
                CustomerAddress address = customerAddressService.selectByCustomerAddressId(orderMaster.getAddressId());
                paramsNew.put("thing10", address.getName());
                // 预约时间
                paramsNew.put("time13", com.ghy.common.utils.DateUtils.parseDateToStr("yyyy年MM月dd日 HH:mm", new Date()));
                WechatMsgUtils.sendWeChatMsg(WechatMsgUtils.getToken(), worker.getWxOpenId(), WxMsgEnum.AFTER_SALES_ORDER, paramsNew);
            } catch (Exception e) {
                log.error("商品售后通知发送失败", e);
            }
            if (afterServiceRecord.getCustomerFinalCheck().equals(0L)) {
                afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                return AjaxResult.success("客户不同意师傅方案，进入售后纠纷处理。");
            }
            // 新增：如果师傅拒绝（workerFeedbackResult=2）且客户同意，则不执行退款流程
            if (afterServiceRecord.getWorkerFeedbackResult() != null && afterServiceRecord.getWorkerFeedbackResult().equals(0L) && one.equals(param.getCustomerFinalCheck())) {
                log.info("商品售后-师傅拒绝且客户同意，不执行退款流程，售后记录ID：{}", afterServiceRecord.getId());
                afterServiceRecord.setRefundApplyTime(new Date());
                
                // 师傅拒绝且客户同意，售后流程结束，设置状态为已完成
                try {
                    afterServiceRecord.setAfterServiceStatus(2);
                    afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                    log.info("师傅拒绝且客户同意，已将售后记录[{}]状态设置为已完成", afterServiceRecord.getId());
                    
                    // 更新对应主单和子单的售后状态为已完成
                    OrderDetail orderDetail1 = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
                    if (orderDetail1 != null) {
                        orderDetail.setAfterServiceStatus(2);
                        orderDetailService.updateOrderDetail(orderDetail1);
                        log.info("已将子单[{}]售后状态设置为已完成", orderDetail1.getId());
                        
                        OrderMaster orderMaster = orderMasterService.selectById(orderDetail1.getOrderMasterId());
                        if (orderMaster != null) {
                            orderMaster.setAfterServiceStatus(2);
                            orderMasterService.updateOrderMaster(orderMaster);
                            log.info("已将主单[{}]售后状态设置为已完成", orderMaster.getId());
                        }
                    }
                } catch (Exception e) {
                    log.error("更新售后完成状态失败，售后记录ID：{}", afterServiceRecord.getId(), e);
                }
                
                return AjaxResult.success("客户同意师傅拒绝方案，售后流程结束，不执行退款");
            }
            
            // DrawCashTime不为空说明已经发起过分账
            if (drawCash) {
                log.warn("商品售后-子单[{}]已发起分账，不能退款", afterServiceRecord.getOrderDetailId());
                afterServiceRecord.setOriginalRefund(BigDecimal.ZERO);
                afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                return AjaxResult.error("本单已划款，师傅/服务人员已到帐或即将到帐，双方达成退款的，请对方线下支付后点对方已退款");
            } else {
                agreeRefund(afterServiceRecord);
            }
//            orderDetailService.updateAfterTimeout(afterServiceRecord.getOrderDetailId(), 0, 0);
        } else if (one.equals(afterServiceRecord.getWorkerFeedbackResult()) && param.getCustomerFinalCheck() == null) {
            // 师傅同意 且 客户未处理
            afterServiceRecordMapper.updateAfterServiceRecord(param);
            return drawCash ? AjaxResult.error("本单银联已确认货款结算完毕(订单支付完成)，款项已到达或即将到达您所绑定帐户，需同意退款的同意后您线下与客户另行操作，系统无法提供原路返回退款!") : AjaxResult.success();
        } else {
            if(two.equals(afterServiceRecord.getCustomerFinalCheck())){
                // 客户不同意师傅的意见,如果订单是确认中,则需要将订单改为服务中
                if(orderDetail.getOrderStatus() == OrderStatus.FINISH_CHECK.code() && orderDetail.getDrawCashTime()!= null ){
                    orderDetail.setOrderStatus(OrderStatus.SERVER.code());
                    orderDetailService.updateOrderDetail(orderDetail);
                    // 如果发现是唯一子单,则需要将主单也更新为服务中
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    if(orderMaster.getOrderStatus() == OrderStatus.FINISH_CHECK.code()){
                        orderMaster.setOrderStatus(OrderStatus.SERVER.code());
                        orderMasterService.updateOrderMaster(orderMaster);
                    }
                }
            }
            afterServiceRecordMapper.updateAfterServiceRecord(param);
        }
        return AjaxResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    private int agreeRefund(AfterServiceRecord afterServiceRecord) throws BaseAdaPayException {
        OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
        Assert.notNull(orderDetail, "子单不存在！");
        FinancialDetail financialDetail = financialDetailService.selectByOrderDetailId(afterServiceRecord.getOrderDetailId());
        Assert.notNull(financialDetail, "财务子单不存在！");
        OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
        Assert.notNull(orderMaster, "找不到对应的订单");
        FinancialMaster financialMaster = financialMasterService.selectByOrderMasterId(orderDetail.getOrderMasterId());
        Assert.notNull(financialMaster, "找不到支付记录");
        // 是否已付款,用于判断是否需要退款
        boolean payReverse = PayStatus.PAID.getCode().equals(financialMaster.getPayStatus());
        log.info("当前订单是否已支付: {}", payReverse);
        
        // 设置退款时支付状态：已支付=1，未支付=0
        if (payReverse) {
            orderMaster.setRefundPayStatus(1);
        } else {
            orderMaster.setRefundPayStatus(0);
        }
        orderMasterService.updateOrderMaster(orderMaster);
        // 申请退款金额
        BigDecimal refundMoney=BigDecimal.ZERO;
        if (ObjectUtils.isNotEmpty(afterServiceRecord.getPlatformRefund())) {
            refundMoney = afterServiceRecord.getPlatformRefund();
        }else if (ObjectUtils.isNotEmpty(afterServiceRecord.getAgreedRefund())) {
            refundMoney = afterServiceRecord.getAgreedRefund();
        } else {
            refundMoney = afterServiceRecord.getRefund();
        }
        log.info("AfterServiceRecord[{}].refundMoney: {},操作数据{}", afterServiceRecord.getId(), refundMoney,afterServiceRecord);
        // 是不是大师傅的子单
        boolean isMaster = orderMaster.getWorkerId().equals(orderDetail.getWorkerId());
        log.info("isMaster: {}", isMaster);
        if (isMaster) {
            // 如果这是大师傅的子单 退款金额最大可以等于主单服务金额
            // 判断退款金额 >= 主单服务金额
            if (refundMoney==null){
                refundMoney=BigDecimal.ZERO;
            }
            boolean refundAll = refundMoney.compareTo(financialMaster.getServerMoney()) > -1;
            log.info("refundAll: {}", refundAll);
            List<OrderDetail> orderDetails = orderDetailService.selectByOrderMasterId(orderMaster.getId());
            // 判断是否有派单给子师傅
            boolean noneSubWorker = true;
            for (OrderDetail od : orderDetails) {
                if (!orderMaster.getWorkerId().equals(od.getWorkerId())) {
                    noneSubWorker = false;
                    break;
                }
            }
            log.info("noneSubWorker: {}", noneSubWorker);
            if (refundAll && noneSubWorker) {
                // 如果退款金额 >= 主单服务金额 并且 没有派单给子师傅 则退整个主单
                orderMasterService.cancelAgree(orderMaster.getId(), 1);
                afterServiceRecord.setOriginalRefund(financialMaster.getPayMoney());
            } else if (refundAll) {
                // 如果退款金额 >= 主单服务金额 但是有派单给子师傅
                afterServiceRecord.setOriginalRefund(financialMaster.getServerMoney());
                // 退款金额就是主单服务金额
                String reverseAmt = AdapayUtils.bigDecimalToString(financialMaster.getServerMoney());
                log.info("大师傅子单[{}]退款 refundMoney: {}", orderDetail.getId(), reverseAmt);
                // 更新主财务单 PayMoney=PayMoney-ServerMoney ，ServerMoney=0
                financialMaster.setPayMoney(financialMaster.getPayMoney().subtract(financialMaster.getServerMoney()));
                financialMaster.setServerMoney(BigDecimal.ZERO);
                financialMasterService.updateFinancialMaster(financialMaster);

                // 发起支付撤销
                if (payReverse) {
                    payReverse(orderMaster.getDeptId(), financialMaster.getPaymentId(), reverseAmt);
                }else{
                    BigDecimal  newRefundMoney=BigDecimal.ZERO;
                    afterServiceRecord.setOriginalRefund(newRefundMoney);
                }
            } else {
                // 如果退款金额 < 主单服务金额
                log.info("大师傅子单[{}]退款 refundMoney: {}", orderDetail.getId(), refundMoney);
                afterServiceRecord.setOriginalRefund(refundMoney);
                financialMaster.setPayMoney(financialMaster.getPayMoney().subtract(refundMoney));
                financialMaster.setServerMoney(financialMaster.getServerMoney().subtract(refundMoney));
//                financialMaster.setDiscountMoney(financialMaster.getDiscountMoney().add(refundMoney));
                financialMasterService.updateFinancialMaster(financialMaster);
                String reverseAmt = AdapayUtils.bigDecimalToString(refundMoney);
                // 发起支付撤销
                if (payReverse) {
                    log.info("已支付[{}]退款 refundMoney: {}", orderDetail.getId(), reverseAmt);
                    payReverse(orderMaster.getDeptId(), financialMaster.getPaymentId(), reverseAmt);
                }else{
                    BigDecimal  newRefundMoney=BigDecimal.ZERO;
                    afterServiceRecord.setOriginalRefund(newRefundMoney);
                }
            }
        } else {
            // 是子师傅的子单 退款金额最大可以等于子单的派单金额
            log.info("financialDetail.getPayMoney()[{}].refundMoney: {}", financialDetail.getPayMoney(), refundMoney);
            if (refundMoney.compareTo(financialDetail.getPayMoney()) > -1) {
                // 子单全额退款 直接走取消流程
                orderDetailService.cancelAgree(orderDetail.getId(), 1);
                afterServiceRecord.setOriginalRefund(financialDetail.getPayMoney());
            } else {
                log.info("小师傅子单[{}]退款 refundMoney = {}", orderDetail.getId(), refundMoney);
                afterServiceRecord.setOriginalRefund(refundMoney);
                financialDetail.setPayMoney(financialDetail.getPayMoney().subtract(refundMoney));
                financialMaster.setPayMoney(financialMaster.getPayMoney().subtract(refundMoney));
                // 更新主/子财务单金额
                financialMasterService.updateFinancialMaster(financialMaster);
                financialDetailService.updateFinancialDetail(financialDetail);

                // 发起支付撤销
                if (payReverse) {
                    String reverseAmt = AdapayUtils.bigDecimalToString(refundMoney);
                    payReverse(orderMaster.getDeptId(), financialMaster.getPaymentId(), reverseAmt);
                }else{
                    BigDecimal  newRefundMoney=BigDecimal.ZERO;
                    afterServiceRecord.setOriginalRefund(newRefundMoney);
                }

            }
        }
        afterServiceRecord.setRefundApplyTime(new Date());
        // 退款成功后，更新售后状态为已完成
        afterServiceRecord.setAfterServiceStatus(1);
        return afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
    }

    private void payReverse(Long deptId, String paymentId, String reverseAmt) throws BaseAdaPayException {
        JSONObject response = adapayService.payReverse(deptId, paymentId, reverseAmt, RefundType.RAS);
        if (!AdapayStatusEnum.pending.code.equals(response.getString("status"))) {
            log.error("发起退款异常，异常信息：{}", response);
            if ("reverse_amt_over".equals(response.getString("error_code"))) {
                throw new BaseException("退款金额超出订单金额");
            } else {
                throw new BaseException("发起退款失败");
            }
        }
    }

    /**
     * 批量删除售后记录
     *
     * @param ids 需要删除的售后记录主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAfterServiceRecordByIds(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        
        // 1. 查询要删除的售后记录信息
        for (String id : idArray) {

            AfterServiceRecord afterServiceRecord = afterServiceRecordMapper.selectAfterServiceRecordById(id);
            if (afterServiceRecord == null) {
                continue;
            }
            
            // 2. 检查对应子单是否处于售后纠纷状态
            OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
            if (orderDetail != null && orderDetail.getAfterServiceStatus() != null && orderDetail.getAfterServiceStatus() == 1) {
                // 3. 如果子单处于售后纠纷状态，将其更新为无售后
                orderDetail.setAfterServiceStatus(0);
                orderDetailService.updateOrderDetail(orderDetail);
                log.info("删除售后记录时更新子单售后状态为无售后，子单ID：{}", orderDetail.getId());
            }
            
            // 4. 检查对应的主单是否还有其他进行中的售后记录
            if (orderDetail != null && orderDetail.getOrderMasterId() != null) {
                // 查询主单下所有子单
                List<OrderDetail> detailList = orderDetailService.selectByOrderMasterId(orderDetail.getOrderMasterId());
                if (detailList != null && !detailList.isEmpty()) {
                    // 获取所有子单的orderDetailId
                    List<Long> detailIds = detailList.stream().map(OrderDetail::getId).collect(java.util.stream.Collectors.toList());
                    
                    // 查询这些子单下的所有售后记录（不包括当前要删除的记录）
                    AfterServiceRecord searchRecord = new AfterServiceRecord();
                    searchRecord.setOrderDetailIds(StringUtils.join(detailIds, ","));
                    List<AfterServiceRecord> activeRecords = afterServiceRecordMapper.selectAfterServiceRecordList(searchRecord);
                
                // 过滤掉要删除的记录和已取消/已超时的记录
                boolean hasOtherActiveRecords = activeRecords.stream()
                    .filter(record -> !record.getId().toString().equals(id))
                    .filter(record -> record.getAfterServiceStatus() != null)
                    .filter(record -> record.getAfterServiceStatus() != 2 && record.getAfterServiceStatus() != 3)
                    .findAny()
                    .isPresent();
                
                // 5. 如果主单没有其他进行中的售后记录，且主单的售后状态为售后纠纷，则将其更新为无售后
                if (!hasOtherActiveRecords) {
                    OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                    if (orderMaster != null && orderMaster.getAfterServiceStatus() != null && orderMaster.getAfterServiceStatus() == 1) {
                        orderMaster.setAfterServiceStatus(0);
                        orderMasterService.updateOrderMaster(orderMaster);
                        log.info("删除售后记录时更新主单售后状态为无售后，主单ID：{}，售后记录ID：{}", orderMaster.getId(), id);
                    }
                }
            }
        }
    }
        // 6. 执行原始的删除操作
        return afterServiceRecordMapper.deleteAfterServiceRecordByIds(idArray);
    }

    /**
     * 删除售后记录信息
     *
     * @param id 售后记录主键
     * @return 结果
     */
    @Override
    public int deleteAfterServiceRecordById(String id) {
        return afterServiceRecordMapper.deleteAfterServiceRecordById(id);
    }

    /**
     * 查询师傅反馈超时的售后记录
     * 倒计时1：客户发起后，师傅24小时不操作任何反馈
     *
     * @return 超时的售后记录列表
     */
    @Override
    public List<AfterServiceRecord> selectWorkerFeedbackTimeoutRecords() {
        return afterServiceRecordMapper.selectWorkerFeedbackTimeoutRecords();
    }

    /**
     * 查询客户确认超时的售后记录
     * 倒计时2：师傅重做完成后客户36小时不操作
     * 倒计时3：师傅拒绝后客户36小时不操作
     *
     * @return 超时的售后记录列表
     */
    @Override
    public List<AfterServiceRecord> selectCustomerConfirmTimeoutRecords() {
        return afterServiceRecordMapper.selectCustomerConfirmTimeoutRecords();
    }

    /**
     * 执行退款逻辑
     * 用于定时器自动处理退款
     *
     * @param afterServiceRecord 售后记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeRefundLogic(AfterServiceRecord afterServiceRecord) {
        try {
            // 检查是否已分账，如果已分账则不能退款
            OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
            if (orderDetail != null && orderDetail.getDrawCashTime() != null) {
                log.warn("子单[{}]已发起分账，不能自动退款", afterServiceRecord.getOrderDetailId());
                afterServiceRecord.setOriginalRefund(BigDecimal.ZERO);
                afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
                
                // 设置主单退款支付状态为未支付（因为无需退款）
                OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                if (orderMaster != null) {
                    orderMaster.setRefundPayStatus(0);
                    orderMasterService.updateOrderMaster(orderMaster);
                    log.info("子单已分账无法退款，设置主单退款支付状态为未支付，orderMasterId={}", orderMaster.getId());
                }
                return;
            }
            
            // 商品售后需要检查师傅收货确认状态
            if (afterServiceRecord.getAfterServiceCategory() != null && afterServiceRecord.getAfterServiceCategory().equals(2)) {
                // 商品售后
                if (afterServiceRecord.getWorkerAgreeType() != null && afterServiceRecord.getWorkerAgreeType() != 1) {
                    // 非即时退单退款，需要师傅确认收货
                    if (afterServiceRecord.getWorkerReceiveConfirm() == null || afterServiceRecord.getWorkerReceiveConfirm() != 1) {
                        log.info("商品售后非即时退款，师傅未确认收货，暂不执行退款，售后记录ID：{}，同意方式：{}，收货确认：{}", 
                                afterServiceRecord.getId(), afterServiceRecord.getWorkerAgreeType(), afterServiceRecord.getWorkerReceiveConfirm());
                        
                        // 设置主单退款支付状态为未支付（因为暂不执行退款）
                        OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                        if (orderMaster != null) {
                            orderMaster.setRefundPayStatus(0);
                            orderMasterService.updateOrderMaster(orderMaster);
                            log.info("商品售后师傅未确认收货暂不执行退款，设置主单退款支付状态为未支付，orderMasterId={}", orderMaster.getId());
                        }
                        return;
                    }
                } else if (afterServiceRecord.getWorkerAgreeType() != null && afterServiceRecord.getWorkerAgreeType() == 1) {
                    // 即时退单退款，需要客户同意
                    if (afterServiceRecord.getCustomerFinalCheck() == null || afterServiceRecord.getCustomerFinalCheck() != 1) {
                        log.info("商品售后即时退款，客户未同意，暂不执行退款，售后记录ID：{}，客户确认：{}", 
                                afterServiceRecord.getId(), afterServiceRecord.getCustomerFinalCheck());
                        
                        // 设置主单退款支付状态为未支付（因为暂不执行退款）
                        OrderMaster orderMaster = orderMasterService.selectById(orderDetail.getOrderMasterId());
                        if (orderMaster != null) {
                            orderMaster.setRefundPayStatus(0);
                            orderMasterService.updateOrderMaster(orderMaster);
                            log.info("商品售后客户未同意暂不执行退款，设置主单退款支付状态为未支付，orderMasterId={}", orderMaster.getId());
                        }
                        return;
                    }
                }
            }
            
            // 执行退款逻辑
            agreeRefund(afterServiceRecord);
            log.info("定时器自动执行退款逻辑完成，售后记录ID：{}", afterServiceRecord.getId());
        } catch (Exception e) {
            log.error("定时器自动执行退款逻辑异常，售后记录ID：{}", afterServiceRecord.getId(), e);
        }
    }

    /**
     * 师傅重发/补发操作
     * 师傅端点击重发补发按钮，保存重发/补发方案
     *
     * @param param 售后记录
     * @return 操作结果
     */
    @Override
    public AjaxResult workerResendPlan(AfterServiceRecord param) {
        try {
            // 参数校验
            if (param.getId() == null) {
                return AjaxResult.error("售后记录ID不能为空");
            }
            if (param.getWorkerResendPlan() == null) {
                return AjaxResult.error("重发/补发方案不能为空");
            }
            
            // 查询售后记录
            AfterServiceRecord afterServiceRecord = afterServiceRecordMapper.selectAfterServiceRecordById(param.getId());
            if (afterServiceRecord == null) {
                return AjaxResult.error("售后记录不存在");
            }
            
            // 检查售后记录状态
            if (afterServiceRecord.getCustomerFinalCheck() != null) {
                return AjaxResult.error("售后记录已处理完成，无法修改");
            }
            
            // 更新重发/补发方案
            afterServiceRecord.setWorkerFeedbackResult(param.getWorkerFeedbackResult());
            afterServiceRecord.setWorkerResendPlanTime(new Date());
            afterServiceRecord.setWorkerResendPlan(param.getWorkerResendPlan());
            afterServiceRecord.setUpdateBy(param.getUpdateBy());
            
            // 新增：设置师傅重发/补发备注和图片
            if (param.getWorkerResendRemark() != null) {
                afterServiceRecord.setWorkerResendRemark(param.getWorkerResendRemark());
            }
            if (param.getWorkerResendImages() != null) {
                afterServiceRecord.setWorkerResendImages(param.getWorkerResendImages());
            }
            
            // 新增：设置师傅反馈结果
            if (param.getWorkerFeedbackResult() != null) {
                afterServiceRecord.setWorkerFeedbackResult(param.getWorkerFeedbackResult());
            }
            
            // 更新数据库
            int result = afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            if (result > 0) {
                log.info("师傅重发/补发方案更新成功，售后记录ID：{}，方案：{}", param.getId(), param.getWorkerResendPlan());
                return AjaxResult.success("重发/补发方案保存成功",afterServiceRecord);
            } else {
                return AjaxResult.error("重发/补发方案保存失败");
            }
        } catch (Exception e) {
            log.error("师傅重发/补发操作异常，售后记录ID：{}", param.getId(), e);
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 退货操作
     * 客户或师傅端进行退货操作，保存退货信息
     *
     * @param param 售后记录
     * @return 操作结果
     */
    @Override
    public AjaxResult returnGoods(AfterServiceRecord param) {
        try {
            // 参数校验
            if (param.getId() == null) {
                return AjaxResult.error("售后记录ID不能为空");
            }
            
            // 查询售后记录
            AfterServiceRecord afterServiceRecord = afterServiceRecordMapper.selectAfterServiceRecordById(param.getId());
            if (afterServiceRecord == null) {
                return AjaxResult.error("售后记录不存在");
            }
            
            // 检查售后记录状态
            if (afterServiceRecord.getCustomerFinalCheck() != null) {
                return AjaxResult.error("售后记录已处理完成，无法修改");
            }
            
            // 更新退货信息
            if (param.getReturnAddress() != null) {
                afterServiceRecord.setReturnAddress(param.getReturnAddress());
            }
            if (param.getReturnContact() != null) {
                afterServiceRecord.setReturnContact(param.getReturnContact());
            }
            if (param.getReturnPhone() != null) {
                afterServiceRecord.setReturnPhone(param.getReturnPhone());
            }
            if (param.getReturnType() != null) {
                afterServiceRecord.setReturnType(param.getReturnType());
            }
            if (param.getReturnRemark() != null) {
                afterServiceRecord.setReturnRemark(param.getReturnRemark());
            }
            if (param.getReturnImages() != null) {
                afterServiceRecord.setReturnImages(param.getReturnImages());
            }
            if (param.getReturnTrackingNumber() != null) {
                afterServiceRecord.setReturnTrackingNumber(param.getReturnTrackingNumber());
            }
            if (param.getReturnShipTime() != null) {
                afterServiceRecord.setReturnShipTime(param.getReturnShipTime());
            }
            if (param.getReturnStatus() != null) {
                afterServiceRecord.setReturnStatus(param.getReturnStatus());
            }
            
            // 如果选择物流/快递退货且提供了物流单号，自动设置发货时间和状态
            if (param.getReturnType() != null && param.getReturnType() == 1 && 
                param.getReturnTrackingNumber() != null && !param.getReturnTrackingNumber().trim().isEmpty()) {
                
                // 如果提供了物流单号但没有设置发货时间，自动设置为当前时间
                if (param.getReturnShipTime() == null) {
                    afterServiceRecord.setReturnShipTime(new Date());
                }
                
                // 如果提供了物流单号但没有设置状态，自动设置为"客户已发货"
                if (param.getReturnStatus() == null) {
                    afterServiceRecord.setReturnStatus(3); // 3-客户已发货
                }
                
                log.info("检测到物流/快递退货且提供物流单号，自动设置发货时间和状态，售后记录ID：{}，物流单号：{}", 
                        param.getId(), param.getReturnTrackingNumber());
            }
            
            afterServiceRecord.setWorkerResendPlanTime(null);
            afterServiceRecord.setUpdateBy(param.getUpdateBy());
            afterServiceRecord.setRedoCompleteTime(null);
            // 设置客户操作时间
            afterServiceRecord.setCustomerOperationTime(new Date());
            
            // 更新数据库
            int result = afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            if (result > 0) {
                log.info("退货信息更新成功，售后记录ID：{}，退货状态：{}", param.getId(), param.getReturnStatus());
                return AjaxResult.success("退货信息保存成功", afterServiceRecord);
            } else {
                return AjaxResult.error("退货信息保存失败");
            }
        } catch (Exception e) {
            log.error("退货操作异常，售后记录ID：{}", param.getId(), e);
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 更新子单和主单的售后状态
     * @param orderDetailId 子单ID
     * @param afterServiceStatus 售后状态：0-无售后，1-售后纠纷
     */


    /**
     * 暂停确认中倒计时
     * @param orderDetailId 子单ID
     */
    private void pauseConfirmTimeout(Long orderDetailId) {
        try {
            OrderDetail orderDetail = orderDetailService.selectById(orderDetailId);
            if (orderDetail != null && orderDetail.getOrderStatus() == OrderStatus.FINISH_CHECK.code()) {
                // 计算剩余倒计时时间
                long remainingTime = calculateConfirmTimeoutRemainingTime(orderDetail);
                
                // 记录剩余时间
                OrderDetail updateDetail = new OrderDetail();
                updateDetail.setId(orderDetailId);
                updateDetail.setConfirmTimeoutRemainingTime(remainingTime);
                orderDetailService.updateOrderDetail(updateDetail);
                
                log.info("暂停确认中倒计时，子单ID：{}，剩余时间：{}毫秒", orderDetailId, remainingTime);
            }
        } catch (Exception e) {
            log.error("暂停确认中倒计时失败，子单ID：{}", orderDetailId, e);
        }
    }

    /**
     * 恢复确认中倒计时
     * @param orderDetailId 子单ID
     */
    @Override
    public void resumeConfirmTimeout(Long orderDetailId) {
        try {
            OrderDetail orderDetail = orderDetailService.selectById(orderDetailId);
            if (orderDetail != null && orderDetail.getOrderStatus() == OrderStatus.FINISH_CHECK.code()) {
                Long remainingTime = orderDetail.getConfirmTimeoutRemainingTime();
                if (remainingTime != null && remainingTime > 0) {
                    // 设置新的确认中开始时间 = 当前时间 - 剩余时间
                    Date newConfirmStartTime = new Date(System.currentTimeMillis() + remainingTime);
                    
                    OrderDetail updateDetail = new OrderDetail();
                    updateDetail.setId(orderDetailId);
                    updateDetail.setConfirmStartTime(newConfirmStartTime);
                    updateDetail.setConfirmTimeoutRemainingTime(null); // 清空剩余时间
                    orderDetailService.updateOrderDetail(updateDetail);
                    
                    log.info("恢复确认中倒计时，子单ID：{}，新确认开始时间：{}，剩余时间：{}毫秒", 
                            orderDetailId, newConfirmStartTime, remainingTime);
                }
            }
        } catch (Exception e) {
            log.error("恢复确认中倒计时失败，子单ID：{}", orderDetailId, e);
        }
    }

    /**
     * 根据订单类型设置售后大类
     * @param afterServiceRecord 售后记录
     */
    private void setAfterServiceCategory(AfterServiceRecord afterServiceRecord) {
        try {
            OrderDetail orderDetail = orderDetailService.selectById(afterServiceRecord.getOrderDetailId());
            if (orderDetail != null && orderDetail.getOrderType() != null) {
                // 根据订单类型设置售后大类
                if (orderDetail.getOrderType() == 0) {
                    // 服务订单
                    afterServiceRecord.setAfterServiceCategory(1);
                } else if (orderDetail.getOrderType() == 1) {
                    // 商品订单
                    afterServiceRecord.setAfterServiceCategory(2);
                }
                log.info("根据订单类型设置售后大类，子单ID：{}，订单类型：{}，售后大类：{}", 
                        orderDetail.getId(), orderDetail.getOrderType(), afterServiceRecord.getAfterServiceCategory());
            }
        } catch (Exception e) {
            log.error("设置售后大类失败，子单ID：{}", afterServiceRecord.getOrderDetailId(), e);
        }
    }

    /**
     * 计算确认中倒计时的剩余时间
     * @param orderDetail 子单信息
     * @return 剩余时间（毫秒）
     */
    private long calculateConfirmTimeoutRemainingTime(OrderDetail orderDetail) {
        if (orderDetail.getConfirmStartTime() == null) {
            return 0;
        }
        
        long confirmStartTime = orderDetail.getConfirmStartTime().getTime();
        long currentTime = System.currentTimeMillis();
       // long timeoutDuration = 60 * 60 * 1000L; // 10分钟（测试环境），生产环境应该是60分钟
        
        long elapsedTime = confirmStartTime-currentTime;
        // long remainingTime = timeoutDuration - elapsedTime;
        
        return Math.max(0, elapsedTime); // 确保不为负数
    }

    /**
     * 发送师傅重发补发通知给客户
     * @param orderDetail 订单详情
     * @param afterServiceRecord 售后记录
     */
    private void sendWorkerResendNotification(OrderDetail orderDetail, AfterServiceRecord afterServiceRecord) {
        try {
            // 这里可以发送微信通知、短信通知等给客户
            // 通知客户师傅已提交重发补发方案，需要客户确认
            log.info("发送师傅重发补发通知给客户，子单ID：{}，方案：{}，方式：{}", 
                    orderDetail.getId(), afterServiceRecord.getWorkerResendPlan(), afterServiceRecord.getWorkerResendType());
            
            // TODO: 实现具体的通知逻辑，比如微信模板消息、短信等
            // 可以根据workerResendType判断倒计时时间：
            // 1-快递/物流：6天倒计时
            // 2-送货上门，3-自提：24小时倒计时
            
        } catch (Exception e) {
            log.error("发送师傅重发补发通知失败，子单ID：{}", orderDetail.getId(), e);
        }
    }

    /**
     * 查询师傅重发补发超时的售后记录
     * 快递/物流：6天倒计时
     * 非快递：24小时倒计时
     * @return 超时的售后记录列表
     */
    @Override
    public List<AfterServiceRecord> selectWorkerResendTimeoutRecords() {
        return afterServiceRecordMapper.selectWorkerResendTimeoutRecords();
    }

    /**
     * 处理师傅操作处理逻辑
     * 根据不同的收货状态和同意处理方式执行不同的业务逻辑
     */
    private void handleWorkerProcessLogic(AfterServiceRecord record, OrderDetail orderDetail) {
        int receiveStatus = record.getWorkerReceiveStatus();
        int agreeType = record.getWorkerAgreeType();
        
        log.info("处理师傅操作逻辑，收货状态：{}，同意方式：{}，订单详情ID：{}", 
                receiveStatus, agreeType, orderDetail.getId());
        
        switch (agreeType) {
            case 1: // 即时退单退款
                handleImmediateRefund(record, orderDetail);
                break;
            case 2: // 货物拦截后退单退款
                handleInterceptAndRefund(record, orderDetail);
                break;
            case 3: // 快递返回货物后退单退款
                handleReturnAndRefund(record, orderDetail);
                break;
            case 4: // 退回货物后退单退款
                handleCustomerReturnAndRefund(record, orderDetail);
                break;
            default:
                log.warn("未知的师傅同意处理方式：{}", agreeType);
                break;
        }
    }

    /**
     * 处理即时退单退款
     */
    private void handleImmediateRefund(AfterServiceRecord record, OrderDetail orderDetail) {
        log.info("执行即时退单退款，记录ID：{}，订单详情ID：{}", record.getId(), orderDetail.getId());
        
        // 设置退款申请时间
        record.setRefundApplyTime(new Date());
        
        // 执行退款逻辑
        try {
            executeRefundLogic(record);
            log.info("即时退单退款执行成功，记录ID：{}", record.getId());
        } catch (Exception e) {
            log.error("即时退单退款执行失败，记录ID：{}，错误：{}", record.getId(), e.getMessage());
        }
    }

    /**
     * 处理货物拦截后退单退款
     */
    private void handleInterceptAndRefund(AfterServiceRecord record, OrderDetail orderDetail) {
        log.info("执行货物拦截后退单退款，记录ID：{}，订单详情ID：{}", record.getId(), orderDetail.getId());
        
        // TODO: 联系物流公司进行货物拦截
        // 1. 获取物流单号
        // 2. 调用物流API进行拦截
        // 3. 拦截成功后执行退款
        
        // 暂时先设置退款申请时间，实际拦截逻辑需要根据具体物流公司API实现
        record.setRefundApplyTime(new Date());
        
        log.info("货物拦截处理已启动，记录ID：{}", record.getId());
    }

    /**
     * 处理快递返回货物后退单退款
     */
    private void handleReturnAndRefund(AfterServiceRecord record, OrderDetail orderDetail) {
        log.info("执行快递返回货物后退单退款，记录ID：{}，订单详情ID：{}", record.getId(), orderDetail.getId());
        
        // TODO: 等待货物返回确认
        // 1. 监控物流状态
        // 2. 确认货物已返回
        // 3. 执行退款
        
        // 暂时不设置退款申请时间，等待货物返回确认
        log.info("等待快递返回货物确认，记录ID：{}", record.getId());
    }

    /**
     * 处理客户退回货物后退单退款
     */
    private void handleCustomerReturnAndRefund(AfterServiceRecord record, OrderDetail orderDetail) {
        log.info("执行客户退回货物后退单退款，记录ID：{}，订单详情ID：{}", record.getId(), orderDetail.getId());
        
        // TODO: 等待客户退回货物确认
        // 1. 通知客户退回货物
        // 2. 确认货物已退回
        // 3. 执行退款
        
        // 暂时不设置退款申请时间，等待客户退回货物确认
        log.info("等待客户退回货物确认，记录ID：{}", record.getId());
    }

    /**
     * 师傅确认收货
     * 师傅确认收到货物后，根据同意处理方式决定是否执行退款
     */
    @Override
    public AjaxResult workerConfirmReceive(AfterServiceRecord param) {
        try {
            log.info("师傅确认收货，售后记录ID：{}", param.getId());
            
            // 查询售后记录
            AfterServiceRecord afterServiceRecord = afterServiceRecordMapper.selectAfterServiceRecordById(param.getId());
            if (afterServiceRecord == null) {
                return AjaxResult.error("售后记录不存在");
            }
            
            // 验证是否为商品售后
            if (afterServiceRecord.getAfterServiceCategory() == null || !afterServiceRecord.getAfterServiceCategory().equals(2)) {
                return AjaxResult.error("只有商品售后才能进行收货确认");
            }
            
            // 验证师傅同意处理方式
            if (afterServiceRecord.getWorkerAgreeType() == null) {
                return AjaxResult.error("请先选择师傅同意处理方式");
            }
            
            // 设置师傅收货确认
            afterServiceRecord.setWorkerReceiveConfirm(1); // 1-已收货
            afterServiceRecord.setWorkerReceiveStatus(3); // 3-已确认收货
            afterServiceRecord.setUpdateTime(new Date());
            
            // 根据师傅同意处理方式决定是否执行退款
            int agreeType = afterServiceRecord.getWorkerAgreeType();
            if (agreeType == 1) {
                // 1-即时退单退款：客户同意时已经执行退款，师傅确认收货不需要再退款
                log.info("即时退单退款，客户同意时已执行退款，师傅确认收货无需重复退款，记录ID：{}", param.getId());
            } else if (agreeType == 2) {
                // 2-货物拦截后退单退款：需要等货物拦截成功
                log.info("货物拦截后退单退款，师傅确认收货后执行退款，记录ID：{}", param.getId());
                afterServiceRecord.setRefundApplyTime(new Date());
                
                // 执行退款逻辑
                try {
                    executeRefundLogic(afterServiceRecord);
                    log.info("货物拦截后退单退款执行成功，记录ID：{}", param.getId());
                } catch (Exception e) {
                    log.error("货物拦截后退单退款执行失败，记录ID：{}，错误：{}", param.getId(), e.getMessage());
                }
            } else if (agreeType == 3) {
                // 3-快递返回货物后退单退款：需要等快递返回
                log.info("快递返回货物后退单退款，师傅确认收货后执行退款，记录ID：{}", param.getId());
                afterServiceRecord.setRefundApplyTime(new Date());
                
                // 执行退款逻辑
                try {
                    executeRefundLogic(afterServiceRecord);
                    log.info("快递返回货物后退单退款执行成功，记录ID：{}", param.getId());
                } catch (Exception e) {
                    log.error("快递返回货物后退单退款执行失败，记录ID：{}，错误：{}", param.getId(), e.getMessage());
                }
            } else if (agreeType == 4) {
                // 4-退回货物后退单退款：需要等客户退回货物
                log.info("退回货物后退单退款，师傅确认收货后执行退款，记录ID：{}", param.getId());
                afterServiceRecord.setRefundApplyTime(new Date());
                
                // 执行退款逻辑
                try {
                    executeRefundLogic(afterServiceRecord);
                    log.info("退回货物后退单退款执行成功，记录ID：{}", param.getId());
                } catch (Exception e) {
                    log.error("退回货物后退单退款执行失败，记录ID：{}，错误：{}", param.getId(), e.getMessage());
                }
            }
            afterServiceRecord.setCustomerFinalCheck(1L);
            afterServiceRecord.setCustomerOperationTime(null);
            // 更新售后记录
            afterServiceRecordMapper.updateAfterServiceRecord(afterServiceRecord);
            
            log.info("师傅确认收货操作完成，记录ID：{}，同意方式：{}", param.getId(), agreeType);
            return AjaxResult.success("师傅确认收货成功");
            
        } catch (Exception e) {
            log.error("师傅确认收货操作异常，记录ID：{}", param.getId(), e);
            return AjaxResult.error("师傅确认收货操作失败：" + e.getMessage());
        }
    }

    /**
     * 查询退货发货超时的售后记录
     * 退货发货时间超过6天，师傅未确认收货的记录
     * @return 超时的售后记录列表
     */
    @Override
    public List<AfterServiceRecord> selectReturnShipTimeoutRecords() {
        log.debug("查询退货发货超时的售后记录");
        return afterServiceRecordMapper.selectReturnShipTimeoutRecords();
    }



}
