package com.yiqi.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yiqi.common.constant.CacheConstants;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.app.domain.AppUser;
import com.yiqi.app.domain.dto.AppDeliveryManListQueryDTO;
import com.yiqi.app.domain.vo.AppUserVO;
import com.yiqi.app.service.IAppCouponItemService;
import com.yiqi.app.service.IAppUserBillMstrService;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.PageVO;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.*;
import com.yiqi.common.utils.*;
import com.yiqi.common.utils.pay.PayCodeUtils;
import com.yiqi.core.domain.*;
import com.yiqi.core.domain.vo.ClothHangerOrderRelationVO;
import com.yiqi.core.service.*;
import com.yiqi.delay.DelayQueueCache;
import com.yiqi.order.domain.*;
import com.yiqi.order.domain.dto.*;
import com.yiqi.order.domain.dto.weapp.OrderClothAppQueryDTO;
import com.yiqi.order.domain.vo.*;
import com.yiqi.order.service.*;
import com.yiqi.recharge.service.IRechargePasswordCardService;
import com.yiqi.system.domain.SysOrg;
import com.yiqi.system.domain.SysSettlementRate;
import com.yiqi.system.domain.SysStore;
import com.yiqi.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiqi.order.mapper.OrderClothMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 洗衣订单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-06
 */
@Service
public class OrderClothServiceImpl extends ServiceImpl<OrderClothMapper, OrderCloth> implements IOrderClothService {

    @Autowired
    private IClothSpeedService clothSpeedService;
    @Autowired
    private IClothWashModeService clothWashModeService;
    @Autowired
    private IClothFlawService clothFlawService;
    @Autowired
    private IClothFlawTypeService clothFlawTypeService;
    @Autowired
    private IClothColorService clothColorService;
    @Autowired
    private IClothCraftService clothCraftService;
    @Autowired
    private IClothTypeService clothTypeService;
    @Autowired
    private IOrderClothRefundService orderClothRefundService;
    @Autowired
    private ISysStoreService sysStoreService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IOrderClothItemService orderClothItemService;
    @Autowired
    private IOrderClothFlawService orderClothFlawService;
    @Autowired
    private IOrderClothColorService orderClothColorService;
    @Autowired
    private IOrderClothCraftService orderClothCraftService;
    @Autowired
    private IOrderClothTypeService orderClothTypeService;
    @Autowired
    private IOrderClothAdjunctService orderClothAdjunctService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private ISysConfigRecordService sysConfigRecordService;
    @Autowired
    private IOrderClothItemCouponRelationService orderClothItemCouponRelationService;
    @Autowired
    private IAppCouponItemService appCouponItemService;
    @Autowired
    private IRechargePasswordCardService rechargePasswordCardService;
    @Autowired
    private IAppUserBillMstrService appUserBillMstrService;
    @Autowired
    private OrderNoUtils orderNoUtils;
    @Autowired
    private ISysOrgService sysOrgService;
    @Autowired
    private IPayService payService;
    @Autowired
    private IOrderClothItemFlowRecordService orderClothItemFlowRecordService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IOrderRechargeService orderRechargeService;
    @Autowired
    private ISysSettlementRateService sysSettlementRateService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IOrderDeliveryService orderDeliveryService;
    @Autowired
    private IOrderClothAddressService orderClothAddressService;
    @Autowired
    private IOrderPayInfoService orderPayInfoService;
    @Autowired
    private DelayQueueCache delayQueueCache;

    @Override
    public void handleDeliverySuccessUpdateOrderStatus(String orderNo) {
        OrderDelivery orderDelivery = orderDeliveryService.getOne(
                new QueryWrapper<OrderDelivery>().lambda()
                        .eq(OrderDelivery::getTransOrderId, orderNo));
        if (orderDelivery == null) {
            throw new ServiceException("未查询到配送信息");
        }
        OrderCloth orderCloth = getOne(
                new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderDelivery.getOrderSn()));
        if (orderCloth == null) {
            throw new ServiceException("未查询到洗衣订单");
        }
        if (orderDelivery.getClothOrderType().equals(ClothOrderDeliveryType.collectCloth.getCode())
                && (orderCloth.getOrderStatus().equals(ClothOrderStatusType.WAITING_TO_DOOR.getCode())
                || orderCloth.getOrderStatus().equals(ClothOrderStatusType.HAS_TO_DOOR.getCode()))) {
            update(new UpdateWrapper<OrderCloth>().lambda()
                    .set(OrderCloth::getOrderStatus, ClothOrderStatusType.HAS_TAKING.getCode())
                    .eq(OrderCloth::getId, orderCloth.getId()));
        }
        if (orderDelivery.getClothOrderType().equals(ClothOrderDeliveryType.takeCloth.getCode())
                && (orderCloth.getOrderStatus().equals(ClothOrderStatusType.WAITING_TO_SEND.getCode())
                || orderCloth.getOrderStatus().equals(ClothOrderStatusType.SENDING.getCode()))) {
            update(new UpdateWrapper<OrderCloth>().lambda()
                    .set(OrderCloth::getOrderStatus, ClothOrderStatusType.FINISH.getCode())
                    .eq(OrderCloth::getId, orderCloth.getId()));
        }
    }

    @Override
    public R paySuccess(String orderNo, String outTradeNo) {
        //查询订单
        OrderCloth orderCloth = getOne(new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderNo));
        if (orderCloth.getPayStatus().equals(PayStatus.HAS_PAY.getCode())) {
            return R.ok();
        }
        return paySuccess(orderCloth);
    }

    @Transactional(rollbackFor = Exception.class)
    public R paySuccess(OrderCloth orderCloth) {
        //查询订单
        if (ClothOrderPayTimeType.take_cloth_pay.getCode().equals(orderCloth.getPayTimeType())) {//收衣付款
            orderCloth.setOrderStatus(ClothOrderStatusType.WAIT_FACTORY.getCode());
        } else {
            //取衣付款，不影响订单状态
//            orderCloth.setOrderStatus(ClothOrderStatusType.WAITING_FOR_HANG.getCode());
        }
        orderCloth.setRefundAmount(BigDecimal.ZERO);
        orderCloth.setPayStatus(PayStatus.HAS_PAY.getCode());
        orderCloth.setPayTime(DateUtils.getNowDate());
        orderCloth.buildUpdateData();
        if (orderCloth.getPayType().equals(PayType.CASH.getCode())) {
            orderCloth.setCashPayAmount(orderCloth.getPayAmount());
        } else if (orderCloth.getPayType().equals(PayType.BALANCE.getCode())) {
            orderCloth.setMemberPayAmount(orderCloth.getPayAmount());
        } else if (orderCloth.getPayType().equals(PayType.WECHAT.getCode())) {
            orderCloth.setWxPayAmount(orderCloth.getPayAmount());
        } else if (orderCloth.getPayType().equals(PayType.ALIPAY.getCode())) {
            orderCloth.setAliPayAmount(orderCloth.getPayAmount());
        }
        updateById(orderCloth);
        //如果是组合支付，则扣除会员余额
        if (orderCloth.getPayType().equals(PayType.COMBINE.getCode())) {
            if (orderCloth.getMemberPayAmount().compareTo(BigDecimal.ZERO) > 0) {
                //如果支付金额大于0，则扣除会员余额
                RechargeCardPayDTO rechargeCardPayDTO = new RechargeCardPayDTO(orderCloth.getAppUserId(), orderCloth.getId(), orderCloth.getSourceType(), orderCloth.getOrgId(), orderCloth.getOrderNo(), orderCloth.getMemberPayAmount(), OrderType.cloth.getCode());
                rechargePasswordCardService.orderPayByBalance(rechargeCardPayDTO);
            }
        }
        //更新衣服状态
        if (ClothOrderPayTimeType.take_cloth_pay.getCode().equals(orderCloth.getPayTimeType())) {
            //收衣付款,更新衣服状态为待入厂
            orderClothItemService.updateAllClothItemStatusByOrderId(orderCloth.getId(), ClothOrderFlowStatus.waitingForWash.getCode());
        } else {
            //取衣付款
        }
        return R.ok();
    }

    @Override
    public R payExpireOrCancelNotify(String orderNo) {
        OrderPayInfo orderPayInfo = orderPayInfoService.getOrderPayInfoByRequestNo(orderNo);
        if (orderPayInfo == null) {
            return R.fail("未查询到订单");
        }
        OrderCloth orderCloth = getOne(new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderPayInfo.getOrderNo()));
        if (!ClothOrderStatusType.WAITING_FOR_PAY.getCode().equals(orderCloth.getOrderStatus())) {
            return R.fail("订单状态不正确，无法支付执行支付取消操作");
        }
        orderCloth.setOrderStatus(ClothOrderStatusType.CANCEL.getCode());
        updateById(orderCloth);
        return R.ok();
    }

    @Override
    public R refundSuccess(String refundNo, String orderNo) {
        OrderClothRefund orderClothRefund = orderClothRefundService.getOrderClothRefundByRefundNo(refundNo);
        orderClothRefund.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
        orderClothRefund.setRefundTime(DateUtils.getNowDate());

        if (orderClothRefund.getPayType().equals(PayType.CASH.getCode())) {
            orderClothRefund.setCashRefundAmount(orderClothRefund.getRefundAmount());
        } else if (orderClothRefund.getPayType().equals(PayType.BALANCE.getCode())) {
            orderClothRefund.setMemberRefundAmount(orderClothRefund.getRefundAmount());
        } else if (orderClothRefund.getPayType().equals(PayType.WECHAT.getCode())) {
            orderClothRefund.setWxRefundAmount(orderClothRefund.getRefundAmount());
        } else if (orderClothRefund.getPayType().equals(PayType.ALIPAY.getCode())) {
            orderClothRefund.setAliRefundAmount(orderClothRefund.getRefundAmount());
        }
        orderClothRefundService.updateById(orderClothRefund);

        if (orderNo == null) {
            orderNo = orderClothRefund.getOrderNo();
        }

        OrderCloth orderCloth = getOne(new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderNo));
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }
        if (orderCloth.getRefundStatus().equals(OrderRefundStatus.REFUND_SUCCESS.getCode())) {//退款状态不正确，直接跳过
            return R.ok();
        }
        orderCloth.setOrderStatus(ClothOrderStatusType.REFUND_SUCCESS.getCode());
        orderCloth.setRefundTime(DateUtils.getNowDate());
        orderCloth.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
        updateById(orderCloth);

        //如果是组合支付，退会员余额
        if (orderCloth.getPayType().equals(PayType.COMBINE.getCode())) {
            if (orderClothRefund.getMemberRefundAmount().compareTo(BigDecimal.ZERO) > 0) {
                //如果支付金额大于0，则扣除会员余额
                Boolean res = rechargePasswordCardService.orderRefundByBalance(orderClothRefund.getOrderNo(), orderClothRefund.getMemberRefundAmount());
                if (res) {
                    throw new ServiceException("会员余额退款失败");
                }
            }
        }

        orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                .set(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.refund.getCode())
                .eq(OrderClothItem::getOrderId, orderCloth.getId()));

        List<OrderClothItem> orderClothItems = orderClothItemService.list(new QueryWrapper<OrderClothItem>().lambda()
                .eq(OrderClothItem::getOrderId, orderCloth.getId()));
        orderClothItemFlowRecordService.addRecordBatch(orderClothItems, ClothOrderFlowStatus.refund.getCode());
        return R.ok();
    }

    @Override
    public R refundClosed(String orderNo) {
        OrderCloth orderCloth = getOne(new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderNo));
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }

        orderCloth.setRefundStatus(OrderRefundStatus.REFUND_SUCCESS.getCode());
        updateById(orderCloth);
        return R.ok();
    }

    @Override
    public R refundError(String orderNo) {
        OrderCloth orderCloth = getOne(new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderNo));
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }
        orderCloth.setRefundStatus(OrderRefundStatus.ERROR.getCode());
        updateById(orderCloth);
        return R.ok();
    }

    @Override
    public R<Page<OrderClothQueryVO>> findPage(LambdaQueryWrapper<OrderCloth> queryWrapper, PageVO pageVO) {
        Page<OrderCloth> page = page(new Page<OrderCloth>(pageVO.getPageNum(), pageVO.getPageSize())
                , queryWrapper);
        if (page.getRecords().size() == 0) {
            Page<OrderClothQueryVO> orderClothQueryVOPage = new Page<>();
            orderClothQueryVOPage.setTotal(page.getTotal());
            return R.ok(orderClothQueryVOPage);
        }
        Map<Long, AppUser> appUserMap = appUserService.list(new QueryWrapper<AppUser>().lambda()
                .in(AppUser::getId, page.getRecords().stream().map(OrderCloth::getAppUserId)
                        .collect(Collectors.toSet()))).stream().collect(Collectors.toMap(AppUser::getId, AppUser -> AppUser));

        Map<Long, AppUser> sendClothUserMap = new HashMap<>();
        if (page.getRecords().stream().filter(orderCloth -> orderCloth.getSendClothAppUserId() != null).map(OrderCloth::getAppUserId).collect(Collectors.toSet()).size() > 0) {
            sendClothUserMap = appUserService.list(new QueryWrapper<AppUser>().lambda()
                            .in(AppUser::getId, page.getRecords().stream().filter(orderCloth -> orderCloth.getSendClothAppUserId() != null)
                                    .map(OrderCloth::getAppUserId).collect(Collectors.toSet())))
                    .stream().collect(Collectors.toMap(AppUser::getId, AppUser -> AppUser));
        }

        List<OrderClothQueryVO> orderClothQueryVOS = new ArrayList<>();
        for (OrderCloth record : page.getRecords()) {
            OrderClothQueryVO orderClothQueryVO = new OrderClothQueryVO();
            BeanUtils.copyProperties(record, orderClothQueryVO);
            if (appUserMap.containsKey(record.getAppUserId())) {
                orderClothQueryVO.setAppUserName(appUserMap.get(record.getAppUserId()).getRealName());
                orderClothQueryVO.setAppUserPhoneNumber(appUserMap.get(record.getAppUserId()).getPhoneNumber());
            }
            if (record.getSendClothAppUserId() != null && sendClothUserMap.containsKey(record.getSendClothAppUserId())) {
                AppUserVO appUserVO = new AppUserVO();
                BeanUtils.copyProperties(sendClothUserMap.get(record.getSendClothAppUserId()), appUserVO);
                orderClothQueryVO.setSendClothUserVO(appUserVO);
            }
            orderClothQueryVOS.add(orderClothQueryVO);
        }

        //如果为总部查询，需要带上组织信息返回
        Map<Long, SysOrg> storeOrgMap = new HashMap<>();
        Map<Long, SysOrg> factoryOrgMap = new HashMap<>();
        if (page.getRecords().stream().filter(orderCloth -> SourceType.STORE.getCode()
                .equals(orderCloth.getSourceType())).collect(Collectors.toList()).size() > 0) {
            storeOrgMap = sysOrgService.list(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getSourceType
                            , SourceType.STORE.getCode()).in(SysOrg::getId, page.getRecords().stream()
                            .map(OrderCloth::getOrgId).collect(Collectors.toSet()))).stream()
                    .collect(Collectors.toMap(SysOrg::getId, SysOrg -> SysOrg));
        }
        for (OrderClothQueryVO orderClothQueryVO : orderClothQueryVOS) {
            orderClothQueryVO.setSysOrg(storeOrgMap.get(orderClothQueryVO.getOrgId()));
        }
        Page<OrderClothQueryVO> orderClothQueryVOPage = new Page<>();
        orderClothQueryVOPage.setRecords(orderClothQueryVOS);
        orderClothQueryVOPage.setTotal(page.getTotal());
        return R.ok(orderClothQueryVOPage);
    }

    @Override
    public List<OrderClothVO> findPage(OrderClothAppQueryDTO orderClothAppQueryDTO) {
        return baseMapper.findPage(orderClothAppQueryDTO, AuthHolder.userId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderCloth collectCloth(OrderClothDTO orderClothDTO) {
        OrderCloth orderCloth = null;
        if (SysBoolType.YES.getCode().equals(orderClothDTO.getIsAppointment())) {//匹配预约单号
            if (StringUtils.isEmpty(orderClothDTO.getOrderNo())) {
                throw new ServiceException("预约单号不能为空");
            }
            orderCloth = getOne(new QueryWrapper<OrderCloth>().lambda()
                    .eq(OrderCloth::getOrderNo, orderClothDTO.getOrderNo())
                    .eq(OrderCloth::getAppUserId, orderClothDTO.getAppUserId())
                    .eq(OrderCloth::getDelFlag, DeleteStatus.OK.getCode()), false);
            if (orderCloth == null) {
                throw new ServiceException("未查询到预约订单");
            }
        } else {//新建订单
            orderCloth = new OrderCloth();
            orderCloth.setCreateBy(SecurityUtils.getUsername());
            orderCloth.setCreateById(SecurityUtils.getUserId());
            orderCloth.setCreateTime(DateUtils.getNowDate());
            orderCloth.setAppUserId(orderClothDTO.getAppUserId());
            //新建为到店收衣方式
            orderCloth.setTakeClothWay(TakeOrSendClothWay.TOSTORE.getCode());
            orderCloth.setSendClothWay(TakeOrSendClothWay.TOSTORE.getCode());
            //门店新建的订单
            orderCloth.setOrderType(ClothOrderType.normal.getCode());
            buildAppUserInfoOrder(orderCloth);
        }
        //配置订单基本数据
        buildClothOrderInfo(orderCloth, orderClothDTO);
        //配置订单洗衣速度
        buildClothSpeedIntoOrder(orderCloth);
        //配置组织信息
        buildOrgIntoOrder(orderCloth);
        orderCloth.setPayType(PayType.WAITPAY.getCode());
        saveOrUpdate(orderCloth);

        List<OrderClothItem> orderClothItems = buildOrderClothItemData(orderClothDTO.getOrderClothItemDTOS(), orderCloth);

        //所有的数据处理完后，将订单的总金额进行更新
        buildOrderTotalPrice(orderCloth, orderClothItems);

        //取衣时再付款，直接配置订单状态为清洗中
        if (ClothOrderPayTimeType.send_cloth_pay.getCode().equals(orderClothDTO.getPayTimeType())) {
            orderCloth.setOrderStatus(ClothOrderStatusType.WAIT_FACTORY.getCode());
        } else {
            orderCloth.setOrderStatus(ClothOrderStatusType.WAITING_FOR_PAY.getCode());
        }
        buildOrderCoupon(orderCloth, orderClothItems, orderClothDTO.getOrderCouponDTOS());

        //计算总支付金额
        orderCloth.setPayAmount(orderCloth.getOrderAmount().subtract(orderCloth.getCouponDeductAmount())
                        .subtract(orderCloth.getDeliveryDeductAmount())
                .subtract(orderCloth.getCashDeductAmount()).subtract(orderCloth.getActivityDiscountAmount()));
        orderClothItemService.updateBatchById(orderClothItems);
        updateById(orderCloth);
        return orderCloth;
    }

    @Override
    public Map<String, Object> calculateDeliveryFee(Long orderId, String sendWay) {
        OrderCloth orderCloth = selectOrderClothById(orderId);
        String deliveryAmountStr = sysConfigRecordService.getCacheConfigRecordByKey(CacheConstants.WASH_DELIVERY_AMOUNT_KEY);
        BigDecimal deliveryAmount = StringUtils.isEmpty(deliveryAmountStr) ? BigDecimal.ZERO : new BigDecimal(deliveryAmountStr);
        BigDecimal freeAmount = BigDecimal.ZERO;
        BigDecimal totalPrice = orderCloth.getOrderClothPrice();
        //配送费减免规则 价格1-价格2:减免费用; 多个阶梯之间用英文分号隔开
        String deliveryFreezeStr = sysConfigRecordService.getCacheConfigRecordByKey(CacheConstants.WASH_DELIVERY_FREE_KEY);
        if (StringUtils.isNotEmpty(deliveryFreezeStr)) {
            String[] deliveryFreezes = deliveryFreezeStr.split(";");
            for (String deliveryFreeze : deliveryFreezes) {
                String[] deliveryFreezeArr = deliveryFreeze.split(":");
                String[] amountArr = deliveryFreezeArr[0].split("-");
                if (totalPrice.doubleValue() >= Double.parseDouble(amountArr[0]) && totalPrice.doubleValue() <= Double.parseDouble(amountArr[1])) {
                    freeAmount = new BigDecimal(deliveryFreezeArr[1]);
                }
            }
        }
        BigDecimal totalDeliveryAmount = BigDecimal.ZERO;
        // 上门收衣-计算收衣配送费
        if (orderCloth.getTakeClothWay().equals(TakeOrSendClothWay.DELIVERY.getCode())) {
            totalDeliveryAmount = deliveryAmount;
        }
        // 上门取衣（配送上门）-计算取衣配送费
        if (sendWay.equals(TakeOrSendClothWay.DELIVERY.getCode())) {
            totalDeliveryAmount = CurrencyUtil.add(totalDeliveryAmount, deliveryAmount);
        }
        orderCloth.setDeliveryAmount(totalDeliveryAmount);
        orderCloth.setOrderAmount(CurrencyUtil.add(totalPrice, totalDeliveryAmount));
        orderCloth.setDeliveryDeductAmount(freeAmount.compareTo(totalDeliveryAmount) > 0 ? totalDeliveryAmount : freeAmount);
        //计算总支付金额
        orderCloth.setPayAmount(orderCloth.getOrderClothPrice().add(orderCloth.getDeliveryAmount()).subtract(orderCloth.getCouponDeductAmount())
                .subtract(orderCloth.getDeliveryDeductAmount())
                .subtract(orderCloth.getCashDeductAmount()).subtract(orderCloth.getActivityDiscountAmount()));
        Map<String, Object> map = new HashMap<>();
        map.put("deliveryAmount", orderCloth.getDeliveryAmount());
        map.put("deliveryDeductAmount", orderCloth.getDeliveryDeductAmount());
        return map;
    }

    /**
     * 退款
     *
     * @param orderId
     * @param remark
     */
    @Override
    public void refundOrderApply(Long orderId, String remark) {
        LambdaQueryWrapper<OrderCloth> queryWrapper = new QueryWrapper<OrderCloth>().lambda()
                .eq(OrderCloth::getId, orderId);
        if (SourceType.FACTORY.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            queryWrapper.eq(OrderCloth::getFactoryId, SecurityUtils.getLoginUser().getOrgId());
        }
        if (SourceType.STORE.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            queryWrapper.eq(OrderCloth::getOrgId, SecurityUtils.getLoginUser().getOrgId());
        }
        OrderCloth orderCloth = getOne(queryWrapper);
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }
        if (Integer.parseInt(orderCloth.getRefundStatus()) > 0) {
            throw new ServiceException("请勿重复申请");
        }
        if (Integer.parseInt(orderCloth.getOrderStatus()) >= Integer.parseInt(ClothOrderStatusType.WASHING.getCode())) {
            throw new ServiceException("订单已入厂，不允许退款");
        }
        //如果有某个衣服已经是已入厂的情况，也不允许退款
        //todo
        //如果用户是且未支付情况下，则直接撤销成功，不生成退款订单，否则要生成退款单
        if (orderCloth.getPayStatus().equals(PayStatus.WAITING_TO_PAY.getCode())) {
            orderCloth.setOrderStatus(ClothOrderStatusType.CANCEL.getCode());
            orderCloth.buildUpdateData();
            updateById(orderCloth);
            return;
        }
        OrderClothRefund orderClothRefund = new OrderClothRefund();
        BeanUtils.copyProperties(orderCloth, orderClothRefund);
        orderClothRefund.setId(null);
        orderClothRefund.setRefundNo(orderNoUtils.getClothOrderNo());
        orderClothRefund.setRefundAmount(orderCloth.getPayAmount());
        orderClothRefund.setRefundApplyTime(DateUtils.getNowDate());
        orderClothRefund.setRefundReason(remark);
        orderClothRefund.setRefundStatus(OrderRefundStatus.REFUND_APPLYING.getCode());
        orderClothRefund.setAliRefundAmount(orderCloth.getAliPayAmount());
        orderClothRefund.setCashRefundAmount(orderCloth.getCashPayAmount());
        orderClothRefund.setWxRefundAmount(orderCloth.getWxPayAmount());
        orderClothRefund.setMemberRefundAmount(orderCloth.getMemberPayAmount());
        orderClothRefundService.save(orderClothRefund);

        orderCloth.setRefundStatus(OrderRefundStatus.REFUNDING.getCode());
        orderCloth.setRefundAmount(orderCloth.getPayAmount());
        baseMapper.updateById(orderCloth);

        //更新衣服标记，将衣服标记为撤单
        List<OrderClothItem> orderClothItems = orderClothItemService.list(new QueryWrapper<OrderClothItem>().lambda()
                .eq(OrderClothItem::getOrderId, orderId));
        orderClothItems.forEach(orderClothItem -> {
            orderClothItem.setFlowStatus(ClothOrderFlowStatus.refund.getCode());
            orderClothItem.setRefundId(orderClothRefund.getId());
            orderClothItem.setRefundTime(DateUtils.getNowDate());
            orderClothItem.buildUpdateData();
            orderClothItemService.updateById(orderClothItem);
        });

        //如果是现金支付，执行退款逻辑
        if (orderCloth.getPayType().equals(PayType.CASH.getCode())) {
            refundSuccess(orderClothRefund.getRefundNo(), orderCloth.getOrderNo());
            return;
        }

        if (orderCloth.getPayType().equals(PayType.BALANCE.getCode())) {
            //充值卡支付退单
            Boolean res = rechargePasswordCardService.orderRefundByBalance(orderClothRefund.getOrderNo(), orderClothRefund.getRefundAmount());
            if (res) {
                refundSuccess(orderClothRefund.getRefundNo(), orderCloth.getOrderNo());
            }
        }
        if (orderCloth.getPayType().equals(PayType.WECHAT.getCode()) || orderCloth.getPayType().equals(PayType.ALIPAY.getCode())) {
            PayRefundDTO payRefundDTO = new PayRefundDTO(orderCloth.getPayType(), orderCloth.getOrderNo(), orderClothRefund.getRefundAmount(), orderClothRefund.getRefundNo(), orderCloth.getOutTradeOrderNo(), remark);
            //执行微信退款逻辑
            payRefundDTO.setTotalAmount(orderCloth.getPayAmount());
            payRefundDTO.setStoreId(orderCloth.getOrgId());
            RefundResponseDTO refundResponse = payService.refundApply(payRefundDTO);
            if (refundResponse.getRefundResult().equals(PayResult.fail.getCode())) {
                orderClothRefund.setRefundStatus(OrderRefundStatus.ERROR.getCode());
                orderClothRefund.setRemark(refundResponse.getPayMsg());
                orderClothRefundService.updateById(orderClothRefund);
                orderCloth.setRefundStatus(OrderRefundStatus.ERROR.getCode());
                baseMapper.updateById(orderCloth);
            }
        }
        if (orderCloth.getPayType().equals(PayType.COMBINE.getCode())) {
            if (orderClothRefund.getCashRefundAmount().compareTo(BigDecimal.ZERO) > 0) {
                //退款成功
                refundSuccess(orderClothRefund.getRefundNo(), orderCloth.getOrderNo());
            }
            if (orderClothRefund.getWxRefundAmount().compareTo(BigDecimal.ZERO) > 0 || orderClothRefund.getAliRefundAmount().compareTo(BigDecimal.ZERO) > 0) {
                //执行微信退款逻辑
                BigDecimal refundAmount = orderClothRefund.getWxRefundAmount().add(orderClothRefund.getAliRefundAmount());
                String payType = orderClothRefund.getWxRefundAmount().compareTo(BigDecimal.ZERO) > 0 ? PayType.WECHAT.getCode() : PayType.ALIPAY.getCode();
                PayRefundDTO payRefundDTO = new PayRefundDTO(payType, orderCloth.getOrderNo(), refundAmount, orderClothRefund.getRefundNo(), orderCloth.getOutTradeOrderNo(), remark);
                payRefundDTO.setTotalAmount(refundAmount);
                payRefundDTO.setStoreId(orderCloth.getOrgId());
                RefundResponseDTO refundResponse = payService.refundApply(payRefundDTO);
                if (refundResponse.getRefundResult().equals(PayResult.fail.getCode())) {
                    orderClothRefund.setRefundStatus(OrderRefundStatus.ERROR.getCode());
                    orderClothRefund.setRemark(refundResponse.getPayMsg());
                    orderClothRefundService.updateById(orderClothRefund);
                    orderCloth.setRefundStatus(OrderRefundStatus.ERROR.getCode());
                    baseMapper.updateById(orderCloth);
                }
            }
        }
    }

    @Override
    public void refundOrderItemApply(OrderClothItem orderClothItem, String remark) {
        OrderCloth orderCloth = getById(orderClothItem.getOrderId());
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }
        OrderClothRefund orderClothRefund = new OrderClothRefund();
        BeanUtils.copyProperties(orderCloth, orderClothRefund);
        orderClothRefund.setId(null);
        orderClothRefund.setRefundNo(orderNoUtils.getClothOrderNo());
        orderClothRefund.setRefundAmount(orderClothItem.getPayPrice());
        orderClothRefund.setRefundApplyTime(DateUtils.getNowDate());
        orderClothRefund.setRefundReason(remark);
        orderClothRefund.setRefundStatus(OrderRefundStatus.REFUND_APPLYING.getCode());
        orderClothRefund.setAliRefundAmount(BigDecimal.ZERO);
        orderClothRefund.setCashRefundAmount(BigDecimal.ZERO);
        orderClothRefund.setWxRefundAmount(BigDecimal.ZERO);
        orderClothRefund.setMemberRefundAmount(BigDecimal.ZERO);
        orderClothRefundService.save(orderClothRefund);

        orderCloth.setRefundStatus(OrderRefundStatus.REFUNDING.getCode());
        if (orderCloth.getRefundAmount() == null) {
            orderCloth.setRefundAmount(orderClothItem.getPayPrice());
        } else {
            orderCloth.setRefundAmount(CurrencyUtil.add(orderCloth.getRefundAmount(), orderClothItem.getPayPrice()));
        }
        if (orderCloth.getPayType().equals(PayType.COMBINE.getCode())) {

        }
        baseMapper.updateById(orderCloth);
        //更新衣服退款标记
        orderClothItem.setFlowStatus(ClothOrderFlowStatus.refund.getCode());
        orderClothItem.setRefundId(orderClothRefund.getId());
        orderClothItem.setRefundTime(DateUtils.getNowDate());
        orderClothItemService.updateById(orderClothItem);
        //对当前衣服的所有附件进行标记退单，但是不改变洗衣状态
//        List<OrderClothAdjunct> orderClothAdjuncts = orderClothAdjunctService.list(new QueryWrapper<OrderClothAdjunct>().lambda()
//                .eq(OrderClothAdjunct::getOrderClothId, orderClothItem.getId()));
//        orderClothAdjuncts.forEach(orderClothAdjunct -> {
//            orderClothAdjunct.setRefundId(orderClothRefund.getId());
//            orderClothAdjunct.setFlowStatus(ClothOrderFlowStatus.checkCloth.getCode());
//            orderClothAdjunct.buildUpdateData();
//            orderClothAdjunctService.updateById(orderClothAdjunct);
//        });
    }


    @Override
    public OrderCloth getOrderClothByOrderNo(String orderNo) {
        return getOne(new QueryWrapper<OrderCloth>().lambda().eq(OrderCloth::getOrderNo, orderNo));
    }

    @Override
    public OrderPayResultVO clothOrderAppPay(OrderClothAppPayDTO orderClothPayDTO) {
        OrderCloth orderCloth = getOrderClothByOrderNo(orderClothPayDTO.getOrderNo());
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }
        if (orderCloth.getPayStatus().equals(PayStatus.HAS_PAY.getCode())) {
            throw new ServiceException("订单已支付");
        }
        orderCloth.setDiscountActivityId(orderClothPayDTO.getActivityId());
        orderCloth.setActivityDiscountAmount(orderClothPayDTO.getActivityDiscountAmount());
        orderCloth.setCouponDeductAmount(orderClothPayDTO.getCouponDeductAmount());
        orderCloth.setPayType(orderClothPayDTO.getPayType());
        orderCloth.setDeliveryAmount(orderClothPayDTO.getDeliveryAmount());
        orderCloth.setRemark(orderClothPayDTO.getRemark());
        orderCloth.setDeliveryAmount(orderClothPayDTO.getDeliveryAmount());
        orderCloth.setDeliveryDeductAmount(orderClothPayDTO.getDeliveryDeductAmount());
        orderCloth.setOrderAmount(CurrencyUtil.add(orderCloth.getOrderClothPrice(), orderCloth.getDeliveryAmount()));
        BigDecimal payAmount = CurrencyUtil.sub(orderCloth.getOrderAmount(), orderClothPayDTO.getCouponDeductAmount(), orderClothPayDTO.getActivityDiscountAmount(), orderClothPayDTO.getDeliveryDeductAmount()).add(orderClothPayDTO.getDeliveryAmount());
        if (payAmount.compareTo(orderClothPayDTO.getPayAmount()) != 0) {
            throw new ServiceException("支付金额有误");
        }
        orderCloth.setPayAmount(payAmount);
        orderCloth.setSendClothWay(orderClothPayDTO.getSendClothWay());
        if (orderClothPayDTO.getPayType().equals(PayType.COMBINE.getCode())) {
            //组合支付
            orderCloth.setMemberPayAmount(orderClothPayDTO.getMemberPayAmount());
            if (orderClothPayDTO.getOtherPayType().equals(PayType.WECHAT.getCode())) {
                orderCloth.setWxPayAmount(CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()));
            }
            if (orderClothPayDTO.getOtherPayType().equals(PayType.ALIPAY.getCode())) {
                orderCloth.setAliPayAmount(CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()));
            }
        }
        updateOrderCloth(orderCloth);
        //更新优惠券
//        QueryWrapper<OrderClothCouponRelation> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(OrderClothCouponRelation::getOrderId, orderCloth.getId());
//        orderClothCouponRelationService.remove(queryWrapper);

        QueryWrapper<OrderClothItemCouponRelation> itemWrapper = new QueryWrapper<>();
        itemWrapper.lambda().eq(OrderClothItemCouponRelation::getOrderId, orderCloth.getId());
        orderClothItemCouponRelationService.remove(itemWrapper);

        if (orderClothPayDTO.getOrderCouponDTOS() != null) {
//            List<OrderClothCouponRelation> orderClothCouponRelations = new ArrayList<>();
            List<OrderClothItemCouponRelation> orderClothItemCouponRelations = new ArrayList<>();
            List<OrderCouponDTO> orderCouponDTOS = orderClothPayDTO.getOrderCouponDTOS();
            for (OrderCouponDTO orderCouponDTO : orderCouponDTOS) {
//                OrderClothCouponRelation orderClothCouponRelation = new OrderClothCouponRelation();
//                orderClothCouponRelation.setOrderId(orderCloth.getId());
//                orderClothCouponRelation.setOrderNo(orderCloth.getOrderNo());
//                orderClothCouponRelation.setCouponItemId(orderCouponDTO.getId());
//                orderClothCouponRelation.buildCreateData();
//                orderClothCouponRelations.add(orderClothCouponRelation);
                for (OrderCouponClothDTO orderCouponClothDTO : orderCouponDTO.getOrderCouponClothDTOS()) {
                    OrderClothItemCouponRelation orderClothItemCouponRelation = new OrderClothItemCouponRelation();
                    orderClothItemCouponRelation.setClothId(orderCouponClothDTO.getId());
                    orderClothItemCouponRelation.setOrderClothItemId(orderCouponClothDTO.getOrderClothItemId());
                    orderClothItemCouponRelation.setCouponItemId(orderCouponDTO.getId());
                    orderClothItemCouponRelation.setOrderId(orderCloth.getId());
                    orderClothItemCouponRelation.setOrderNo(orderCloth.getOrderNo());
                    orderClothItemCouponRelation.setDiscountPrice(orderCouponClothDTO.getDeductAmount());
                    orderClothItemCouponRelation.buildCreateData();
                    orderClothItemCouponRelations.add(orderClothItemCouponRelation);
                    OrderClothItem orderClothItem = orderClothItemService.getById(orderCouponClothDTO.getOrderClothItemId());
                    orderClothItem.setPayPrice(orderClothItem.getPayPrice().subtract(orderCouponClothDTO.getDeductAmount()));
                    orderClothItemService.updateById(orderClothItem);
                }
            }
//            orderClothCouponRelationService.saveBatch(orderClothCouponRelations);
            orderClothItemCouponRelationService.saveBatch(orderClothItemCouponRelations);
        }

        //会员余额支付
        if (orderClothPayDTO.getPayType().equals(PayType.BALANCE.getCode())) {
            orderCloth.setPayType(PayType.BALANCE.getCode());
            RechargeCardPayDTO rechargeCardPayDTO = new RechargeCardPayDTO(orderCloth.getAppUserId(), orderCloth.getId(), orderCloth.getSourceType(), orderCloth.getOrgId(), orderCloth.getOrderNo(), orderCloth.getPayAmount(), OrderType.cloth.getCode());
            rechargePasswordCardService.orderPayByBalance(rechargeCardPayDTO);
            paySuccess(orderCloth);
            return OrderPayResultVO.paySuccess(orderCloth.getOrderNo());
        } else if (orderClothPayDTO.getPayType().equals(PayType.WECHAT.getCode()) || orderClothPayDTO.getPayType().equals(PayType.ALIPAY.getCode())) {
            OrderPayResultVO orderPayResultVO = new OrderPayResultVO();
            orderPayResultVO.setAppPayRespVO(payService.appPay(PayOrderAppDTO.buildClothOrderPayData(orderCloth, orderClothPayDTO.getPlatform())));
            orderPayResultVO.setPayResult(100);
            return orderPayResultVO;
        } else if (orderClothPayDTO.getPayType().equals(PayType.COMBINE.getCode())) {
            //组合支付
            OrderPayResultVO orderPayResultVO = new OrderPayResultVO();
            orderPayResultVO.setAppPayRespVO(payService.appPay(PayOrderAppDTO.buildClothOrderPayDataByCombine(orderCloth, CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()), orderClothPayDTO.getOtherPayType(), orderClothPayDTO.getPlatform())));
            orderPayResultVO.setPayResult(100);
            return orderPayResultVO;
        } else {
            return OrderPayResultVO.payError("请重新支付");
        }
    }


    @Override
    public OrderPayResultVO clothOrderPay(OrderClothPayDTO orderClothPayDTO) {
        OrderCloth orderCloth = getOrderClothByOrderNo(orderClothPayDTO.getOrderNo());
        if (orderCloth == null) {
            throw new ServiceException("未查询到订单");
        }
        if (orderCloth.getPayStatus().equals(PayStatus.HAS_PAY.getCode())) {
            throw new ServiceException("订单已支付");
        }
        if (!orderCloth.getPayAmount().equals(orderCloth.getPayAmount())) {
            throw new ServiceException("订单金额有误");
        }
        if (orderClothPayDTO.getPayType().equals(PayType.CASH.getCode())) {
            orderCloth.setPayType(PayType.CASH.getCode());
            paySuccess(orderCloth);
            return OrderPayResultVO.paySuccess(orderCloth.getOrderNo());
        }
        if (orderClothPayDTO.getPayType().equals(PayType.WECHAT.getCode())) {
            String payType = null;
            try {
                payType = PayCodeUtils.getPayTypeByCode(orderClothPayDTO.getAuthCode());
            } catch (ServiceException e) {
                return OrderPayResultVO.payError(e.getMessage());
            }
            orderCloth.setPayType(payType);
            this.updateById(orderCloth);
            try {
                return payService.faceToFacePay(PayOrderFaceToFaceDTO.createRechargeOrderPayData(orderCloth.getOrderNo(), orderCloth.getPayAmount(), orderCloth.getPayType(), orderClothPayDTO.getAuthCode()));
            } catch (Exception e) {
                e.printStackTrace();
                return OrderPayResultVO.payError("扫收款码支付失败");
            }
        }
        //组合支付
        if (orderClothPayDTO.getPayType().equals(PayType.COMBINE.getCode())) {
            orderCloth.setPayType(PayType.COMBINE.getCode());
            orderCloth.setMemberPayAmount(orderClothPayDTO.getMemberPayAmount());
            String otherPayType = orderClothPayDTO.getOtherPayType();
            if (otherPayType == null) {
                return OrderPayResultVO.payError("请先设置组合支付其他支付方式");
            }
            if (CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()).compareTo(BigDecimal.ZERO) <= 0) {
                return OrderPayResultVO.payError("组合支付金额有误");
            }
            if (otherPayType.equals(PayType.CASH.getCode())) {
                orderCloth.setCashPayAmount(CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()));
                paySuccess(orderCloth);
                return OrderPayResultVO.paySuccess(orderCloth.getOrderNo());
            } else if (otherPayType.equals(PayType.WECHAT.getCode())) {
                String payType = null;
                try {
                    payType = PayCodeUtils.getPayTypeByCode(orderClothPayDTO.getAuthCode());
                } catch (ServiceException e) {
                    return OrderPayResultVO.payError(e.getMessage());
                }
                if (payType.equals(PayType.WECHAT.getCode())) {
                    orderCloth.setWxPayAmount(CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()));
                }
                if (payType.equals(PayType.ALIPAY.getCode())) {
                    orderCloth.setAliPayAmount(CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()));
                }
                this.updateById(orderCloth);

                try {
                    return payService.faceToFacePay(PayOrderFaceToFaceDTO.createRechargeOrderPayData(orderCloth.getOrderNo(), CurrencyUtil.sub(orderClothPayDTO.getPayAmount(), orderClothPayDTO.getMemberPayAmount()), payType, orderClothPayDTO.getAuthCode()));
                } catch (Exception e) {
                    e.printStackTrace();
                    return OrderPayResultVO.payError("扫收款码支付失败");
                }
            }
        }
        //会员余额支付
        if (orderClothPayDTO.getPayType().equals(PayType.BALANCE.getCode())) {
            orderCloth.setPayType(PayType.BALANCE.getCode());
            RechargeCardPayDTO rechargeCardPayDTO = new RechargeCardPayDTO(orderCloth.getAppUserId(), orderCloth.getId(), orderCloth.getSourceType(), orderCloth.getOrgId(), orderCloth.getOrderNo(), orderCloth.getPayAmount(), OrderType.cloth.getCode());
            rechargePasswordCardService.orderPayByBalance(rechargeCardPayDTO);
            paySuccess(orderCloth);
            return OrderPayResultVO.paySuccess(orderCloth.getOrderNo());
        }
        return OrderPayResultVO.payError("请重新支付");
    }

    private void buildOrderCoupon(OrderCloth orderCloth, List<OrderClothItem> orderClothItems, List<OrderCouponDTO> orderCouponDTOS) {
        BigDecimal discountAmount = BigDecimal.ZERO;
        if (CollUtil.isNotEmpty(orderCouponDTOS)) {
            List<OrderClothItemCouponRelation> orderClothItemCouponRelations = new ArrayList<>();
            for (OrderCouponDTO orderCouponDTO : orderCouponDTOS) {
                for (OrderCouponClothDTO orderCouponClothDTO : orderCouponDTO.getOrderCouponClothDTOS()) {
                    OrderClothItemCouponRelation orderClothItemCouponRelation = new OrderClothItemCouponRelation();
                    orderClothItemCouponRelation.setClothId(orderCouponClothDTO.getId());
                    orderClothItemCouponRelation.setOrderClothItemId(orderClothItems.get(orderCouponClothDTO.getClothIndex()).getId());
                    orderClothItemCouponRelation.setCouponItemId(orderCouponDTO.getId());
                    orderClothItemCouponRelation.setOrderId(orderCloth.getId());
                    orderClothItemCouponRelation.setOrderNo(orderCloth.getOrderNo());
                    orderClothItemCouponRelation.setDiscountPrice(orderCouponClothDTO.getDeductAmount());
                    orderClothItemCouponRelation.buildCreateData();
                    orderClothItemCouponRelations.add(orderClothItemCouponRelation);
                    orderClothItems.get(orderCouponClothDTO.getClothIndex()).setPayPrice(orderClothItems.get(orderCouponClothDTO.getClothIndex())
                            .getPayPrice().subtract(orderCouponClothDTO.getDeductAmount()));
                    discountAmount = discountAmount.add(orderClothItemCouponRelation.getDiscountPrice());
                }
            }
            orderClothItemCouponRelationService.saveBatch(orderClothItemCouponRelations);
        }
        orderCloth.setCouponDeductAmount(discountAmount);


        //优惠券使用完后，将优惠券修改为已使用状态
        orderCouponDTOS.forEach(orderCouponDTO -> appCouponItemService.checkCouponItem(orderCouponDTO.getId(), orderCloth.getAppUserId())
        );
    }

    /**
     * @param orderCloth      衣服订单
     * @param orderClothItems 订单衣服明细
     */
    private void buildOrderTotalPrice(OrderCloth orderCloth, List<OrderClothItem> orderClothItems) {
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (OrderClothItem orderClothItem : orderClothItems) {
            totalPrice = CurrencyUtil.add(totalPrice, orderClothItem.getTotalPrice());
        }
        orderCloth.setOrderClothPrice(totalPrice);

        String deliveryAmountStr = sysConfigRecordService.getCacheConfigRecordByKey(CacheConstants.WASH_DELIVERY_AMOUNT_KEY);
        BigDecimal deliveryAmount = StringUtils.isEmpty(deliveryAmountStr) ? BigDecimal.ZERO : new BigDecimal(deliveryAmountStr);
        BigDecimal freeAmount = BigDecimal.ZERO;
        //配送费减免规则 价格1-价格2:减免费用; 多个阶梯之间用英文分号隔开
        String deliveryFreezeStr = sysConfigRecordService.getCacheConfigRecordByKey(CacheConstants.WASH_DELIVERY_FREE_KEY);
        if (StringUtils.isNotEmpty(deliveryFreezeStr)) {
            String[] deliveryFreezes = deliveryFreezeStr.split(";");
            for (String deliveryFreeze : deliveryFreezes) {
                String[] deliveryFreezeArr = deliveryFreeze.split(":");
                String[] amountArr = deliveryFreezeArr[0].split("-");
                if (totalPrice.doubleValue() >= Double.parseDouble(amountArr[0]) && totalPrice.doubleValue() <= Double.parseDouble(amountArr[1])) {
                    freeAmount = new BigDecimal(deliveryFreezeArr[1]);
                }
            }
        }
        BigDecimal totalDeliveryAmount = BigDecimal.ZERO;
        // 上门收衣-计算收衣配送费
        if (orderCloth.getTakeClothWay().equals(TakeOrSendClothWay.DELIVERY.getCode())) {
            totalDeliveryAmount = deliveryAmount;
        }
        orderCloth.setDeliveryAmount(totalDeliveryAmount);
        orderCloth.setOrderAmount(CurrencyUtil.add(totalPrice, totalDeliveryAmount));
        orderCloth.setDeliveryDeductAmount(freeAmount.compareTo(totalDeliveryAmount) > 0 ? totalDeliveryAmount : freeAmount);
        orderCloth.setCashPayAmount(BigDecimal.ZERO);
        orderCloth.setWxPayAmount(BigDecimal.ZERO);
        orderCloth.setAliPayAmount(BigDecimal.ZERO);
        orderCloth.setMemberPayAmount(BigDecimal.ZERO);
    }

    /**
     * 封装订单衣服详情数据
     *
     * @param orderClothItemDTOS
     */
    private List<OrderClothItem> buildOrderClothItemData(List<OrderClothItemDTO> orderClothItemDTOS, OrderCloth orderCloth) {
        Map<Long, ClothSpeed> clothSpeedMap = clothSpeedService.list(new QueryWrapper<ClothSpeed>().lambda()
                        .eq(ClothSpeed::getDelFlag, DeleteStatus.OK.getCode())
                        .eq(ClothSpeed::getStatus, StatusType.OK.getCode())).stream()
                .collect(Collectors.toMap(ClothSpeed::getId, ClothSpeed -> ClothSpeed));
        Map<Long, ClothWashMode> clothWashModeMap = clothWashModeService.list(new QueryWrapper<ClothWashMode>().lambda()
                        .eq(ClothWashMode::getDelFlag, DeleteStatus.OK.getCode())
                        .eq(ClothWashMode::getStatus, StatusType.OK.getCode())).stream()
                .collect(Collectors.toMap(ClothWashMode::getId, ClothWashMode -> ClothWashMode));

        Set<Long> clothFlawIds = new HashSet<>();
        Set<Long> clothColorIds = new HashSet<>();
        Set<Long> clothCraftIds = new HashSet<>();
        orderClothItemDTOS.forEach(clothItemDTO -> {
            clothFlawIds.addAll(clothItemDTO.getOrderClothFlawDTOS().stream()
                    .map(OrderClothFlawDTO::getClothFlawId).collect(Collectors.toSet()));
            clothColorIds.addAll(clothItemDTO.getOrderClothColorDTOS().stream()
                    .map(OrderClothColorDTO::getClothColorId).collect(Collectors.toSet()));
            clothCraftIds.addAll(clothItemDTO.getOrderClothCraftDTOS().stream()
                    .map(OrderClothCraftDTO::getClothCraftId).collect(Collectors.toSet()));
        });
        Map<Long, ClothFlaw> clothFlawMap = clothFlawService.list(new QueryWrapper<ClothFlaw>().lambda()
                        .eq(ClothFlaw::getDelFlag, DeleteStatus.OK.getCode())
                        .eq(ClothFlaw::getStatus, StatusType.OK.getCode())
                        .in(ClothFlaw::getId, clothFlawIds))
                .stream()
                .collect(Collectors.toMap(ClothFlaw::getId, ClothFlaw -> ClothFlaw));
        Map<Long, ClothFlawType> clothFlawTypeMap = clothFlawTypeService.list(new QueryWrapper<ClothFlawType>().lambda()
                        .eq(ClothFlawType::getDelFlag, DeleteStatus.OK.getCode())
                        .eq(ClothFlawType::getStatus, StatusType.OK.getCode())).stream()
                .collect(Collectors.toMap(ClothFlawType::getId, ClothFlawType -> ClothFlawType));
        Map<Long, ClothColor> clothColorMap = clothColorService.list(new QueryWrapper<ClothColor>().lambda()
                        .eq(ClothColor::getDelFlag, DeleteStatus.OK.getCode())
                        .eq(ClothColor::getStatus, StatusType.OK.getCode())
                        .in(ClothColor::getId, clothColorIds))
                .stream()
                .collect(Collectors.toMap(ClothColor::getId, ClothColor -> ClothColor));
        Map<Long, ClothCraft> clothCraftMap = new HashMap<>();
        if (clothCraftIds.size() > 0) {
            clothCraftMap = clothCraftService.list(new QueryWrapper<ClothCraft>().lambda()
                            .eq(ClothCraft::getDelFlag, DeleteStatus.OK.getCode())
                            .eq(ClothCraft::getStatus, StatusType.OK.getCode())
                            .in(ClothCraft::getId, clothCraftIds))
                    .stream().collect(Collectors.toMap(ClothCraft::getId, ClothCraft -> ClothCraft));
        }
        List<OrderClothItem> orderClothItems = new ArrayList<>();
        for (OrderClothItemDTO orderClothItemDTO : orderClothItemDTOS) {
            OrderClothItem orderClothItem = new OrderClothItem();
            orderClothItem.setOrderId(orderCloth.getId());
            orderClothItem.setOrderNo(orderCloth.getOrderNo());
            orderClothItem.setAppUserId(orderCloth.getAppUserId());
            orderClothItem.setOrgId(orderCloth.getOrgId());
            orderClothItem.setSourceType(orderCloth.getSourceType());
            orderClothItem.setFactoryId(orderCloth.getFactoryId());
            orderClothItem.setWashCode(orderNoUtils.getClothWashCode());
            orderClothItem.setClothItemId(orderClothItemDTO.getClothItemId());
            orderClothItem.setClothItemName(orderClothItemDTO.getClothItemName());
            orderClothItem.setClothBrandId(orderClothItemDTO.getClothBrandId());
            orderClothItem.setClothBrandName(orderClothItemDTO.getClothBrandName());
            orderClothItem.setClothSpeedId(orderClothItemDTO.getClothSpeedId());
            //如果是取衣款，则直接赋值待入厂，否则不赋值，支付成功后设置
            if (ClothOrderPayTimeType.send_cloth_pay.getCode().equals(orderCloth.getPayTimeType())) {
                orderClothItem.setFlowStatus(ClothOrderFlowStatus.waitingForWash.getCode());
            } else {
                orderClothItem.setFlowStatus(null);
            }
            orderClothItem.setClothSpeedName(clothSpeedMap.get(orderClothItemDTO.getClothSpeedId()).getName());
            orderClothItem.setClothMultiple(clothSpeedMap.get(orderClothItemDTO.getClothSpeedId()).getMultiple());
            orderClothItem.setClothWashDayNum(clothSpeedMap.get(orderClothItemDTO.getClothSpeedId()).getDayNum());
            orderClothItem.setPlanSendClothTime(DateUtils.addDays(new Date()
                    , clothSpeedMap.get(orderClothItemDTO.getClothSpeedId()).getDayNum()));
            if (orderCloth.getPlanSendToUserTime() == null || orderCloth.getPlanSendToUserTime().getTime() < orderClothItem.getPlanSendClothTime().getTime()) {
                orderCloth.setPlanSendToUserTime(orderClothItem.getPlanSendClothTime());
            }
            orderClothItem.setPrice(orderClothItemDTO.getDefaultPrice());
            if (orderClothItemDTO.getClothWashModeId() != null) {
                orderClothItem.setClothWashModeId(orderClothItemDTO.getClothWashModeId());
                orderClothItem.setClothWashModeName(clothWashModeMap.get(orderClothItemDTO.getClothWashModeId()).getName());
            }
            orderClothItem.setRepeatCount(0);
            orderClothItem.setPics(orderClothItemDTO.getPics());
            orderClothItem.setIsHedging(orderClothItemDTO.getIsHedging());
            orderClothItem.setHedgingPrice(orderClothItemDTO.getHedgingPrice());
            orderClothItem.setIsCustomPrice(orderClothItemDTO.getIsCustomPrice());
            orderClothItem.setSpecialPrice(buildOrderClothItemSpecialPrice(orderClothItemDTO, clothSpeedMap.get(orderClothItemDTO.getClothSpeedId())));
            orderClothItem.setTotalPrice(orderClothItem.getPrice().add(orderClothItem.getSpecialPrice()));
//            if (SysBoolType.YES.getCode().equals(orderClothItem.getIsHedging())) {
//                orderClothItem.setTotalPrice(orderClothItem.getTotalPrice().add(orderClothItem.getHedgingPrice()
//                        .multiply(new BigDecimal(sysConfigService.selectConfigByKey(SysConfigKey.OrderClothHedgingRate.getCode())))));
//            }
            orderClothItem.setPayPrice(orderClothItem.getTotalPrice());
            orderClothItem.setRemark(orderClothItemDTO.getRemark());
            orderClothItem.buildCreateData();
            orderClothItems.add(orderClothItem);
        }
        orderClothItemService.saveBatch(orderClothItems);

        //衣服瑕疵
        List<OrderClothFlaw> orderClothFlaws = new ArrayList<>();
        //衣服颜色
        List<OrderClothColor> orderClothColors = new ArrayList<>();
        //衣服工艺
        List<OrderClothCraft> orderClothCrafts = new ArrayList<>();
        //衣服类型
        List<OrderClothType> orderClothTypes = new ArrayList<>();
        //衣服附件
        List<OrderClothAdjunct> orderClothAdjuncts = new ArrayList<>();
        for (int i = 0; i < orderClothItems.size(); i++) {
            for (OrderClothFlawDTO orderClothFlawDTO : orderClothItemDTOS.get(i).getOrderClothFlawDTOS()) {
                OrderClothFlaw orderClothFlaw = new OrderClothFlaw();
                orderClothFlaw.setClothFlawId(orderClothFlawDTO.getClothFlawId());
                orderClothFlaw.setClothFlawName(clothFlawMap.get(orderClothFlawDTO.getClothFlawId()).getName());
                orderClothFlaw.setClothFlawTypeId(clothFlawMap.get(orderClothFlawDTO.getClothFlawId()).getFlawTypeId());
                orderClothFlaw.setClothFlawTypeName(clothFlawTypeMap.get(clothFlawMap
                        .get(orderClothFlawDTO.getClothFlawId()).getFlawTypeId()).getName());
                orderClothFlaw.buildCreateData();
                orderClothFlaw.setOrderId(orderCloth.getId());
                orderClothFlaw.setOrderClothId(orderClothItems.get(i).getId());
                orderClothFlaws.add(orderClothFlaw);
            }

            for (OrderClothColorDTO orderClothColorDTO : orderClothItemDTOS.get(i).getOrderClothColorDTOS()) {
                OrderClothColor orderClothColor = new OrderClothColor();
                orderClothColor.setClothColorId(orderClothColorDTO.getClothColorId());
                orderClothColor.setClothColorName(clothColorMap.get(orderClothColorDTO.getClothColorId()).getName());
                orderClothColor.setClothColorCode(clothColorMap.get(orderClothColorDTO.getClothColorId()).getCode());
                orderClothColor.setClothColorType(clothColorMap.get(orderClothColorDTO.getClothColorId()).getColorType());
                orderClothColor.setImgUrl(clothColorMap.get(orderClothColorDTO.getClothColorId()).getImgUrl());
                orderClothColor.setOrderId(orderCloth.getId());
                orderClothColor.setOrderClothId(orderClothItems.get(i).getId());
                orderClothColor.buildCreateData();
                orderClothColors.add(orderClothColor);
            }

            for (OrderClothCraftDTO orderClothCraftDTO : orderClothItemDTOS.get(i).getOrderClothCraftDTOS()) {
                OrderClothCraft orderClothCraft = new OrderClothCraft();
                orderClothCraft.setClothCraftId(orderClothCraftDTO.getClothCraftId());
                orderClothCraft.setClothCraftName(clothCraftMap.get(orderClothCraftDTO.getClothCraftId()).getCraftName());
                orderClothCraft.setPrice(orderClothCraftDTO.getPrice());
                orderClothCraft.setOrderId(orderCloth.getId());
                orderClothCraft.setOrderClothId(orderClothItems.get(i).getId());
                orderClothCraft.buildCreateData();
                orderClothCrafts.add(orderClothCraft);
            }

            for (OrderClothTypeDTO orderClothTypeDTO : orderClothItemDTOS.get(i).getOrderClothTypeDTOS()) {
                OrderClothType orderClothType = new OrderClothType();
                BeanUtils.copyProperties(orderClothTypeDTO, orderClothType);
                orderClothType.setOrderId(orderCloth.getId());
                orderClothType.setOrderClothId(orderClothItems.get(i).getId());
                orderClothType.buildCreateData();
                orderClothTypes.add(orderClothType);
            }

            for (OrderClothAdjunctDTO orderClothAdjunctDTO : orderClothItemDTOS.get(i).getOrderClothAdjunctDTOS()) {
                if (orderClothAdjunctDTO.getNum() > 1) {
                    for (int j = 0; j < orderClothAdjunctDTO.getNum(); j++) {
                        OrderClothAdjunct orderClothAdjunct = new OrderClothAdjunct();
                        orderClothAdjunct.setAdjunctId(orderClothAdjunctDTO.getAdjunctId());
                        orderClothAdjunct.setAdjunctName(orderClothAdjunctDTO.getAdjunctName() + (j + 1));
                        orderClothAdjunct.setAdjunctNo(orderNoUtils.getClothWashAdjustCode());
                        orderClothAdjunct.setOrderId(orderCloth.getId());
                        orderClothAdjunct.setFlowStatus(ClothOrderFlowStatus.waitingForWash.getCode());
                        orderClothAdjunct.setNum(1);
                        orderClothAdjunct.setRepeatCount(0);
                        orderClothAdjunct.setFactoryId(orderCloth.getFactoryId());
                        orderClothAdjunct.setStoreId(orderCloth.getOrgId());
                        orderClothAdjunct.setOrderClothId(orderClothItems.get(i).getId());
                        orderClothAdjunct.buildCreateData();
                        orderClothAdjuncts.add(orderClothAdjunct);
                    }
                } else {
                    OrderClothAdjunct orderClothAdjunct = new OrderClothAdjunct();
                    BeanUtils.copyProperties(orderClothAdjunctDTO, orderClothAdjunct);
                    orderClothAdjunct.setAdjunctNo(orderNoUtils.getClothWashAdjustCode());
                    orderClothAdjunct.setOrderId(orderCloth.getId());
                    orderClothAdjunct.setStoreId(orderCloth.getOrgId());
                    orderClothAdjunct.setRepeatCount(0);
                    orderClothAdjunct.setFactoryId(orderCloth.getFactoryId());
                    orderClothAdjunct.setFlowStatus(ClothOrderFlowStatus.waitingForWash.getCode());
                    orderClothAdjunct.setOrderClothId(orderClothItems.get(i).getId());
                    orderClothAdjunct.buildCreateData();
                    orderClothAdjuncts.add(orderClothAdjunct);
                }
            }
        }
        orderClothFlawService.saveBatch(orderClothFlaws);
        orderClothColorService.saveBatch(orderClothColors);
        orderClothCraftService.saveBatch(orderClothCrafts);
        orderClothTypeService.saveBatch(orderClothTypes);
        orderClothAdjunctService.saveBatch(orderClothAdjuncts);

        return orderClothItems;
    }

    private BigDecimal buildOrderClothItemSpecialPrice(OrderClothItemDTO orderClothItemDTO, ClothSpeed clothSpeed) {
        BigDecimal specialPrice = BigDecimal.ZERO;
        if (SysBoolType.YES.getCode().equals(orderClothItemDTO.getIsHedging())) {
            specialPrice = specialPrice.add(orderClothItemDTO.getHedgingPrice().multiply(new BigDecimal(0.01)));
        }
        for (OrderClothCraftDTO orderClothCraftDTO : orderClothItemDTO.getOrderClothCraftDTOS()) {
            specialPrice = specialPrice.add(orderClothCraftDTO.getPrice());
        }
        if (clothSpeed.getMultiple().subtract(BigDecimal.ONE).doubleValue() > 0) {
            specialPrice = specialPrice.add(orderClothItemDTO.getDefaultPrice().multiply(clothSpeed.getMultiple().subtract(BigDecimal.ONE)));
        }
        return specialPrice;
    }

    /**
     * 配置订单基本数据
     *
     * @param orderCloth
     * @param orderClothDTO
     */
    private void buildClothOrderInfo(OrderCloth orderCloth, OrderClothDTO orderClothDTO) {
        if (StringUtils.isEmpty(orderCloth.getOrderNo())) {
            orderCloth.setOrderNo(orderNoUtils.getClothOrderNo());
        }
        //如果为空则默认普洗
        if (orderClothDTO.getSpeedId() == null) {
            orderCloth.setClothSpeedId(ClothSpeedType.NORMAL_WASH.getId());
        }
        orderCloth.setPayType(orderClothDTO.getPayType());
        orderCloth.setClothSpeedId(orderClothDTO.getSpeedId());
        if (orderClothDTO.getSpeedId() == null) {
            orderCloth.setClothSpeedId(ClothSpeedType.NORMAL_WASH.getId());
        }
        orderCloth.setOrderStatus(ClothOrderStatusType.APPOINTMENT.getCode());
        orderCloth.setCashDeductAmount(orderClothDTO.getCashDeductAmount() == null ? BigDecimal.ZERO : orderClothDTO.getCashDeductAmount());
        orderCloth.setActivityDiscountAmount(orderClothDTO.getActivityDiscountAmount() == null ? BigDecimal.ZERO : orderClothDTO.getActivityDiscountAmount());
        orderCloth.setIsSpecial(StringUtils.isEmpty(orderClothDTO.getIsSpecial()) ? SysBoolType.NO.getCode() : orderClothDTO.getIsSpecial());
        orderCloth.setSetPriceTime(DateUtils.getNowDate());
        orderCloth.setRemark(orderClothDTO.getRemark());
        orderCloth.setOrderClothCount(orderClothDTO.getOrderClothItemDTOS().size());
        if (!SysBoolType.YES.getCode().equals(orderClothDTO.getIsAppointment())) {
            orderCloth.setOrderSource(OrderSourceType.OFFLINE.getCode());
        }
        orderCloth.setPayTimeType(orderClothDTO.getPayTimeType());
        orderCloth.setPayStatus(PayStatus.WAITING_TO_PAY.getCode());
        // 取衣方式
        orderCloth.setSendClothWay(orderClothDTO.getSendClothWay());
        //
        if (StringUtils.isEmpty(orderCloth.getContactPhone()) && orderCloth.getAppUserId() != null) {
            AppUser appUser = appUserService.getById(orderCloth.getAppUserId());
            orderCloth.setContactPhone(appUser.getPhoneNumber());
            orderCloth.setContactName(appUser.getRealName());
        }
    }

    /**
     * 配置订单洗衣速度
     *
     * @param orderCloth
     */
    private void buildClothSpeedIntoOrder(OrderCloth orderCloth) {
        ClothSpeed clothSpeed = clothSpeedService.getOne(new QueryWrapper<ClothSpeed>().lambda()
                .eq(ClothSpeed::getId, orderCloth.getClothSpeedId())
                .eq(ClothSpeed::getDelFlag, DeleteStatus.OK.getCode())
                .eq(ClothSpeed::getStatus, StatusType.OK.getCode()), false);
        orderCloth.setClothSpeedName(clothSpeed.getName());
    }

    /**
     * 配置组织信息
     *
     * @param orderCloth
     */
    private void buildOrgIntoOrder(OrderCloth orderCloth) {
        orderCloth.setSourceType(SecurityUtils.getLoginUser().getSourceType());
        orderCloth.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        if (SourceType.STORE.getCode().equals(orderCloth.getSourceType())) {
            SysStore sysStore = sysStoreService.getOne(new QueryWrapper<SysStore>().lambda()
                    .eq(SysStore::getId, orderCloth.getOrgId())
                    .eq(SysStore::getStatus, StatusType.OK.getCode())
                    .eq(SysStore::getDelFlag, DeleteStatus.OK.getCode()), false);
            if (sysStore == null) {
                throw new ServiceException("未查询到门店");
            }
            orderCloth.setFactoryId(sysStore.getFactoryId());
        } else {
            throw new ServiceException("工厂没有权限");
        }
    }

    /**
     * 配置用户信息
     *
     * @param orderCloth
     */
    private void buildAppUserInfoOrder(OrderCloth orderCloth) {
        AppUser appUser = appUserService.getOne(new QueryWrapper<AppUser>().lambda().eq(AppUser::getId, orderCloth.getAppUserId()), false);
        orderCloth.setContactName(appUser.getRealName());
        orderCloth.setContactPhone(appUser.getPhoneNumber());
    }
    //</editor-folder>

    /**
     * 查询洗衣订单
     *
     * @param id 洗衣订单主键
     * @return 洗衣订单
     */
    @Override
    public OrderCloth selectOrderClothById(Long id) {
        return baseMapper.selectOrderClothById(id);
    }

    /**
     * 查询洗衣订单列表
     *
     * @param orderCloth 洗衣订单
     * @return 洗衣订单
     */
    @Override
    public List<OrderCloth> selectOrderClothList(OrderCloth orderCloth) {
        return baseMapper.selectOrderClothList(orderCloth);
    }

    /**
     * 新增洗衣订单
     *
     * @param orderCloth 洗衣订单
     * @return 结果
     */
    @Override
    public int insertOrderCloth(OrderCloth orderCloth) {
        orderCloth.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(orderCloth);
    }

    /**
     * 修改洗衣订单
     *
     * @param orderCloth 洗衣订单
     * @return 结果
     */
    @Override
    public int updateOrderCloth(OrderCloth orderCloth) {
        orderCloth.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(orderCloth);
    }

    /**
     * 批量删除洗衣订单
     *
     * @param ids 需要删除的洗衣订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderClothByIds(Long[] ids) {
        return baseMapper.deleteOrderClothByIds(ids);
    }

    /**
     * 删除洗衣订单信息
     *
     * @param id 洗衣订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderClothById(Long id) {
        return baseMapper.deleteOrderClothById(id);
    }

    /**
     * 查询待上挂洗衣订单衣服明细列表
     */
    @Override
    public List<ClothHangerOrderRelationVO> getNoHangerOrderClothList() {
        return null;
    }

    /**
     * 查询上挂洗衣订单衣服明细
     */
    @Override
    public ClothHangerOrderRelationVO getOrderClothInfoByWashCode(String washCode) {
        return null;
    }

    @Override
    public List<OrderClothRecordVO> getDeliveryOrderRecordList(AppDeliveryManListQueryDTO appDeliveryManListQueryDTO) {
        return baseMapper.getDeliveryOrderRecordList(appDeliveryManListQueryDTO);
    }

    @Override
    public List<OrderClothAppointmentVO> getAppointmentClothOrderList(OrderAppointmentDTO2 orderAppointmentDTO2) {
        if (!SourceType.MANAGER.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            orderAppointmentDTO2.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        }
        Integer[] orderStatus = new Integer[]{0};
        /**
         * 虚拟状态对应实际状态
         * {@link com.yiqi.common.enums.ClothOrderStatusType}
         */
        switch (orderAppointmentDTO2.getVirtualListStatus()) {
            case 1:
                // 取衣中
                orderStatus = new Integer[]{1, 2, 3};
                break;
            case 6:
                // 清洗中
                orderStatus = new Integer[]{6, 7};
                break;
            case 12:
                // 已完成
                orderStatus = new Integer[]{11, 12};
                orderAppointmentDTO2.setSendClothWay("1");
                break;
            default:
                orderStatus = new Integer[]{orderAppointmentDTO2.getVirtualListStatus()};
                break;
        }
        orderAppointmentDTO2.setQueryOrderStatus(Arrays.asList(orderStatus));
        List<OrderClothAppointmentVO> orderClothAppointmentVOList = baseMapper.getAppointmentClothOrderList(orderAppointmentDTO2);
        for (OrderClothAppointmentVO orderClothAppointmentVO : orderClothAppointmentVOList) {
            orderClothAppointmentVO.setOrderClothAddress(orderClothAddressService.getByorderSn(orderClothAppointmentVO.getOrderNo()));
        }
        return orderClothAppointmentVOList;
    }

    @Override
    public void checkAllOrderStatus(Long orderClothId, String orderStatus) {
        LambdaQueryWrapper<OrderCloth> queryWrapper = new QueryWrapper<OrderCloth>().lambda()
                .eq(OrderCloth::getDelFlag, DeleteStatus.OK.getCode())
                .eq(orderClothId != null, OrderCloth::getId, orderClothId)
                .ne(OrderCloth::getRefundStatus, OrderRefundStatus.REFUND_SUCCESS.getCode());
        //查询一个月内的数据
        queryWrapper.ge(BaseEntity::getCreateTime, DateUtils.addDays(new Date(), -10));
        // 1. 查询洗衣订单
        List<String> orderStatuss = CollUtil.newArrayList(
                ClothOrderStatusType.WAIT_FACTORY.getCode(),
                ClothOrderStatusType.WASHING.getCode(),
                ClothOrderStatusType.HAS_WASH.getCode(),
                ClothOrderStatusType.WAITING_FOR_HANG.getCode()
        );
        queryWrapper.in(OrderCloth::getOrderStatus, orderStatuss);
        List<OrderCloth> orderCloths = baseMapper.selectList(queryWrapper);
        for (OrderCloth orderCloth : orderCloths) {
            if (orderStatus == null) {
                orderStatus = orderCloth.getOrderStatus();
            }
            if (orderStatus.equals(ClothOrderStatusType.WAIT_FACTORY.getCode())) {
                //待入厂，判断所有的衣服和附件是否都已经入厂，如果都入厂，则改变状态
                Boolean res = orderClothItemService.checkClothItemStatus(orderCloth.getId(), ClothOrderFlowStatus.inFactory.getCode());
                if (res) {
                    OrderCloth orderClothUpdate = new OrderCloth();
                    orderClothUpdate.setId(orderCloth.getId());
                    orderClothUpdate.setOrderStatus(ClothOrderStatusType.WASHING.getCode());
                    orderClothUpdate.setUpdateTime(new Date());
                    baseMapper.updateById(orderClothUpdate);
                }
            }
            if (orderStatus.equals(ClothOrderStatusType.WASHING.getCode())) {
                //待入厂，判断所有的衣服和附件是否都已经入厂，如果都入厂，则改变状态
                Boolean res = orderClothItemService.checkClothItemStatus(orderCloth.getId(), ClothOrderFlowStatus.outFactory.getCode());
                if (res) {
                    OrderCloth orderClothUpdate = new OrderCloth();
                    orderClothUpdate.setId(orderCloth.getId());
                    orderClothUpdate.setOrderStatus(ClothOrderStatusType.HAS_WASH.getCode());
                    orderClothUpdate.setUpdateTime(new Date());
                    baseMapper.updateById(orderClothUpdate);
                }
            }
            if (orderStatus.equals(ClothOrderStatusType.HAS_WASH.getCode())) {
                //已出厂，判断所有的衣服和附件是否都已经入厂，如果都入厂，则改变状态
                Boolean res = orderClothItemService.checkClothItemStatus(orderCloth.getId(), ClothOrderFlowStatus.hangering.getCode());
                if (res) {
                    OrderCloth orderClothUpdate = new OrderCloth();
                    orderClothUpdate.setId(orderCloth.getId());
                    orderClothUpdate.setOrderStatus(ClothOrderStatusType.WAITING_FOR_HANG.getCode());
                    orderClothUpdate.setUpdateTime(new Date());
                    baseMapper.updateById(orderClothUpdate);
                }
            }
            if (orderStatus.equals(ClothOrderStatusType.WAITING_FOR_HANG.getCode())) {
                //已到店，如果所有衣服已取完，则变成已完成
                Boolean res = orderClothItemService.checkClothItemStatus(orderCloth.getId(), ClothOrderFlowStatus.hasTake.getCode());
                if (res) {
                    OrderCloth orderClothUpdate = new OrderCloth();
                    orderClothUpdate.setId(orderCloth.getId());
                    orderClothUpdate.setOrderStatus(ClothOrderStatusType.FINISH.getCode());
                    orderClothUpdate.setUpdateTime(new Date());
                    baseMapper.updateById(orderClothUpdate);
                }
            }
        }
    }

}
