package com.yiqi.admin.controller.order;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yiqi.common.enums.ClothOrderStatusType;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.app.domain.AppUser;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.ClothOrderFlowStatus;
import com.yiqi.common.enums.SourceType;
import com.yiqi.common.utils.*;
import com.yiqi.core.domain.ClothHanger;
import com.yiqi.core.domain.ClothHangerOrderRelation;
import com.yiqi.core.service.IClothHangerOrderRelationService;
import com.yiqi.core.service.IClothHangerService;
import com.yiqi.order.domain.*;
import com.yiqi.order.domain.dto.*;
import com.yiqi.order.domain.vo.*;
import com.yiqi.order.service.*;
import com.yiqi.system.domain.SysOrg;
import com.yiqi.system.service.ISysOrgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.enums.BusinessType;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

/**
 * 洗衣订单衣服明细Controller
 *
 * @author ruoyi
 * @date 2023-10-06
 */
@Api(tags = "管理后台 - 洗衣订单衣服明细")
@RestController
@RequestMapping(UrlConstants.managerApi + "/order/clothItem")
public class OrderClothItemController extends BaseController {
    @Autowired
    private IOrderClothItemService orderClothItemService;
    @Autowired
    private IOrderClothColorService orderClothColorService;
    @Autowired
    private IOrderClothCraftService orderClothCraftService;
    @Autowired
    private IOrderClothFlawService orderClothFlawService;
    @Autowired
    private IOrderClothAdjunctService orderClothAdjunctService;
    @Autowired
    private IOrderClothTypeService orderClothTypeService;
    @Autowired
    private ISysOrgService sysOrgService;
    @Autowired
    private IOrderClothItemFlowRecordService orderClothItemFlowRecordService;

    @Autowired
    private IOrderClothRefundService orderClothRefundService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IClothHangerService clothHangerService;
    @Autowired
    private IOrderClothService orderClothService;

    @PostMapping(value = "saveOrderClothPics")
    @ApiOperation("保存衣服图片")
    public R saveOrderClothPics(@RequestParam @ApiParam("衣服图片集合，『，』分割")
                                String pics, @RequestParam @ApiParam("订单衣服ID") Long id) throws Exception {
        OrderClothItem orderClothItem = orderClothItemService.getOne(new QueryWrapper<OrderClothItem>().lambda()
                .eq(OrderClothItem::getId, id)
                .eq(OrderClothItem::getOrgId, SecurityUtils.getLoginUser().getOrgId())
                .eq(OrderClothItem::getSourceType, SecurityUtils.getLoginUser().getSourceType()));
        if (orderClothItem == null) {
            throw new ServiceException("未查询到衣服信息");
        }

        orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda().set(OrderClothItem::getPics, pics).eq(OrderClothItem::getId, id));
        return R.ok();
    }

    @ApiOperation("获取门店前台衣服数量统计")
    @GetMapping("getUnFinishedOrderClothCountGroupByStatus")
    public R<OrderClothItemCountStatisticVO> getUnFinishedOrderClothCountGroupByStatus() throws Exception {
        return R.ok(orderClothItemService.getUnFinishedOrderClothCountGroupByStatus(getFactoryId(), getStoreId()));
    }

    @ApiOperation("获取门店超时衣服数量统计")
    @GetMapping("getTimeoutOrderClothCountGroupByStatus")
    public R<OrderClothItemTimeoutCountStatisticVO> getTimeoutOrderClothCountGroupByStatus() throws Exception {
        return R.ok(orderClothItemService.getTimeoutOrderClothCountGroupByStatus(getFactoryId(), getStoreId()));
    }

    /**
     * 出厂业务不需要修改订单状态，直接出厂，门店上挂时需要判断设置订单状态，如果订单全部上挂，则修改订单为已到店
     *
     * @param orderClothItemOutFactoryDTO
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("出厂")
    @PostMapping(value = "outFactory")
    public R outFactory(@RequestBody @Valid OrderClothItemOutFactoryDTO orderClothItemOutFactoryDTO) throws Exception {
        if (orderClothItemOutFactoryDTO.getClothType().equals("1")) {
            //衣服出厂
            List<OrderClothItem> orderClothItems = orderClothItemService.outFactory(orderClothItemOutFactoryDTO);
            //衣服状态修改，判断是否全部出厂
            Set<Long> ids = orderClothItems.stream().map(OrderClothItem::getOrderId).collect(Collectors.toSet());
            for (Long orderId : ids) {
                orderClothService.checkAllOrderStatus(orderId, ClothOrderStatusType.WASHING.getCode());
            }
        } else {
            //附件出厂
            orderClothAdjunctService.outFactory(orderClothItemOutFactoryDTO);
        }
        return R.ok();
    }

    @ApiOperation("设置衣服问题")
    @PostMapping(value = "setClothProblem")
    public R setClothProblem(@RequestParam @ApiParam("订单衣服明细ID") Long id, @RequestParam @ApiParam("问题内容") String clothProblem) throws Exception {
        orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                .set(OrderClothItem::getClothProblem, clothProblem)
                .eq(OrderClothItem::getId, id));
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("工厂重洗衣服")
    @GetMapping(value = "rewashCloth")
    public R rewashCloth(@RequestParam @ApiParam("水洗唛") String washCode) throws Exception {
        if (washCode.startsWith(OrderNoUtils.cloth_wash_code_header)) {
            LambdaQueryWrapper<OrderClothItem> lambdaQueryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                    .eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId()).eq(OrderClothItem::getWashCode, washCode);
            OrderClothItem orderClothItem = orderClothItemService.getOne(lambdaQueryWrapper);
            if (orderClothItem == null) {
                throw new ServiceException("未查询到数据");
            }
            if (!ClothOrderFlowStatus.checkCloth.getCode().equals(orderClothItem.getFlowStatus())) {
                throw new ServiceException("当前状态不可进行重洗删除，当前状态【"
                        + EnumUtils.getEnumByType(orderClothItem.getFlowStatus(), ClothOrderFlowStatus.class).getInfo() + "】");
            }

            orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                    .setSql("repeat_count = repeat_count + 1, flow_status = '1' ")
                    .eq(OrderClothItem::getWashCode, washCode));

            //记录日志
            orderClothItemFlowRecordService.addRecord(orderClothItem, ClothOrderFlowStatus.reWash.getCode());
        }
        if (washCode.startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
            OrderClothAdjunct orderClothAdjunct = orderClothAdjunctService.selectOrderClothAdjunctByAdjunctNo(washCode);
            if (orderClothAdjunct == null) {
                throw new ServiceException("未查询到衣物");
            }
            if (!ClothOrderFlowStatus.checkCloth.getCode().equals(orderClothAdjunct.getFlowStatus())) {
                throw new ServiceException("当前状态不可进行重洗删除，当前状态【"
                        + EnumUtils.getEnumByType(orderClothAdjunct.getFlowStatus(), ClothOrderFlowStatus.class).getInfo() + "】");
            }
            orderClothAdjunctService.update(new UpdateWrapper<OrderClothAdjunct>().lambda()
                    .setSql("repeat_count = repeat_count + 1, flow_status = '1'")
                    .eq(OrderClothAdjunct::getAdjunctNo, washCode));
            orderClothItemFlowRecordService.addAdjunctRecord(orderClothAdjunct, ClothOrderFlowStatus.reWash.getCode());
        }
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("工厂删除入厂")
    @GetMapping(value = "/deleteInFactory")
    public R deleteInFactory(@RequestParam @ApiParam("水洗唛") String washCode) throws Exception {

        if (washCode.startsWith(OrderNoUtils.cloth_wash_code_header)) {
            LambdaQueryWrapper<OrderClothItem> lambdaQueryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                    .eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId()).eq(OrderClothItem::getWashCode, washCode);
            OrderClothItem orderClothItem = orderClothItemService.getOne(lambdaQueryWrapper);
            if (orderClothItem == null) {
                throw new ServiceException("未查询到数据");
            }
            if (!ClothOrderFlowStatus.inFactory.getCode().equals(orderClothItem.getFlowStatus())) {
                throw new ServiceException("当前状态不可进行入厂删除，当前状态【"
                        + EnumUtils.getEnumByType(orderClothItem.getFlowStatus(), ClothOrderFlowStatus.class).getInfo() + "】");
            }

            orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                    .set(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode())
                    .eq(OrderClothItem::getWashCode, washCode));

            orderClothItemFlowRecordService.addRecord(orderClothItem, ClothOrderFlowStatus.deleteInFactory.getCode());
        }
        if (washCode.startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
            OrderClothAdjunct orderClothAdjunct = orderClothAdjunctService.selectOrderClothAdjunctByAdjunctNo(washCode);
            if (orderClothAdjunct == null) {
                throw new ServiceException("未查询到衣物");
            }
            if (!ClothOrderFlowStatus.inFactory.getCode().equals(orderClothAdjunct.getFlowStatus())) {
                throw new ServiceException("当前状态不可进行入厂删除，当前状态【"
                        + EnumUtils.getEnumByType(orderClothAdjunct.getFlowStatus(), ClothOrderFlowStatus.class).getInfo() + "】");
            }
            orderClothAdjunctService.update(new UpdateWrapper<OrderClothAdjunct>().lambda()
                    .set(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode())
                    .eq(OrderClothAdjunct::getAdjunctNo, washCode));
            orderClothItemFlowRecordService.addAdjunctRecord(orderClothAdjunct, ClothOrderFlowStatus.deleteInFactory.getCode());
        }
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("工厂撤销入厂")
    @GetMapping(value = "/cancelOrderInFactory")
    public R cancelOrderInFactory(@RequestParam @ApiParam("水洗唛") String washCode) throws Exception {
        if (washCode.startsWith(OrderNoUtils.cloth_wash_code_header)) {
            LambdaQueryWrapper<OrderClothItem> lambdaQueryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                    .eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId()).eq(OrderClothItem::getWashCode, washCode);
            OrderClothItem orderClothItem = orderClothItemService.getOne(lambdaQueryWrapper);
            if (orderClothItem == null) {
                throw new ServiceException("未查询到数据");
            }
            if (orderClothItem.getRefundId() != null) {
                throw new ServiceException("当前衣服已经撤单，无法重复提交");
            }
            orderClothItemFlowRecordService.addRecord(orderClothItem, ClothOrderFlowStatus.refund.getCode());
            //生成一条工厂撤单退款申请
            orderClothService.refundOrderItemApply(orderClothItem, "工厂手动撤销");
        }
        if (washCode.startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
            throw new ServiceException("衣服附件无法单独执行撤单逻辑");
        }
        return R.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("工厂衣服入厂")
    @GetMapping(value = "inFactory")
    public R<OrderClothItemVO> inFactory(@RequestParam @ApiParam("水洗唛") String washCode) throws Exception {
        OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
        OrderClothItem orderClothItem = null;
        if (washCode.startsWith(OrderNoUtils.cloth_wash_code_header)) {
            LambdaQueryWrapper<OrderClothItem> lambdaQueryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                    .eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId()).eq(OrderClothItem::getWashCode, washCode);
            orderClothItem = orderClothItemService.getOne(lambdaQueryWrapper);
            if (orderClothItem == null) {
                throw new ServiceException("未查询到衣物");
            }
            if (ClothOrderFlowStatus.waitingForWash.getCode().equals(orderClothItem.getFlowStatus())) {
                orderClothItem.setFlowStatus(ClothOrderFlowStatus.inFactory.getCode());
                orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                        .set(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.inFactory.getCode())
                        .set(OrderClothItem::getInFactoryTime, DateUtils.getNowDate())
                        .set(OrderClothItem::getInFactoryById, AuthHolder.userId())
                        .set(OrderClothItem::getInFactoryBy, AuthHolder.nickName())
                        .eq(OrderClothItem::getWashCode, washCode)
                        .eq(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode()));
                //添加记录
                orderClothItemFlowRecordService.addRecord(orderClothItem, ClothOrderFlowStatus.inFactory.getCode());
            }
            BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
            orderClothItemVO.setIsAdjunct("N");
            orderClothItemVO.setOrderClothAdjuncts(orderClothAdjunctService.list(new QueryWrapper<OrderClothAdjunct>()
                    .lambda().eq(OrderClothAdjunct::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothColors(orderClothColorService.list(new QueryWrapper<OrderClothColor>()
                    .lambda().eq(OrderClothColor::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothCrafts(orderClothCraftService.list(new QueryWrapper<OrderClothCraft>()
                    .lambda().eq(OrderClothCraft::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothFlaws(orderClothFlawService.list(new QueryWrapper<OrderClothFlaw>()
                    .lambda().eq(OrderClothFlaw::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothTypes(orderClothTypeService.list(new QueryWrapper<OrderClothType>()
                    .lambda().eq(OrderClothType::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setFlowStatus(orderClothItem.getFlowStatus());
        }
        if (washCode.startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
            OrderClothAdjunct orderClothAdjunct = orderClothAdjunctService.selectOrderClothAdjunctByAdjunctNo(washCode);
            if (orderClothAdjunct == null) {
                throw new ServiceException("未查询到衣物");
            }
            orderClothItem = orderClothItemService.selectOrderClothItemById(orderClothAdjunct.getOrderClothId());
            if (ClothOrderFlowStatus.waitingForWash.getCode().equals(orderClothAdjunct.getFlowStatus())) {
                orderClothAdjunct.setFlowStatus(ClothOrderFlowStatus.inFactory.getCode());
                orderClothAdjunctService.update(new UpdateWrapper<OrderClothAdjunct>().lambda()
                        .set(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.inFactory.getCode())
                        .set(OrderClothAdjunct::getInFactoryTime, DateUtils.getNowDate())
                        .set(OrderClothAdjunct::getInFactoryById, AuthHolder.userId())
                        .set(OrderClothAdjunct::getInFactoryBy, AuthHolder.nickName())
                        .eq(OrderClothAdjunct::getAdjunctNo, washCode)
                        .eq(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode()));
                //添加记录
                orderClothItemFlowRecordService.addAdjunctRecord(orderClothAdjunct, ClothOrderFlowStatus.inFactory.getCode());
            }
            //如果衣服已经撤销了，则该附件也进行撤单操作
            if (orderClothItem.getRefundId() != null) {
                orderClothAdjunctService.update(new UpdateWrapper<OrderClothAdjunct>().lambda()
                        .set(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.checkCloth.getCode())
                        .set(OrderClothAdjunct::getRefundId, orderClothItem.getRefundId())
                        .eq(OrderClothAdjunct::getAdjunctNo, washCode));
                //添加记录
                orderClothItemFlowRecordService.addAdjunctRecord(orderClothAdjunct, ClothOrderFlowStatus.refund.getCode());
            }

            BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
            orderClothItemVO.setIsAdjunct("Y");
            orderClothItemVO.setWashCode(orderClothAdjunct.getAdjunctNo());
            orderClothItemVO.setClothItemName("【附件】" + orderClothItemVO.getClothItemName() + " * " + orderClothAdjunct.getAdjunctName());
            orderClothItemVO.setOrderClothAdjuncts(Arrays.asList(orderClothAdjunct));
            orderClothItemVO.setFlowStatus(orderClothAdjunct.getFlowStatus());
        }
        //只要有一件衣服已经入厂，订单就要更新成已入厂状态
        if (orderClothItem.getRefundId() == null) {
            OrderCloth orderCloth = orderClothService.getById(orderClothItem.getOrderId());
            if (Integer.parseInt(orderCloth.getOrderStatus()) < Integer.parseInt(ClothOrderStatusType.WASHING.getCode())) {
                orderCloth.setId(orderClothItem.getOrderId());
                orderCloth.setOrderStatus(ClothOrderStatusType.WASHING.getCode());
                orderCloth.buildUpdateData();
                orderClothService.updateById(orderCloth);
            }
        }
        orderClothItemVO.setOrgName(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                .eq(SysOrg::getId, orderClothItemVO.getOrgId())
                .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType()), false).getName());
        return R.ok(orderClothItemVO);
    }

    @GetMapping(value = "/oneInFactory")
    @ApiOperation("一键入厂")
    @Transactional(rollbackFor = Exception.class)
    public R oneInFactory(OrderClothItemFactoryQueryDTO orderClothItemFactoryQueryDTO) throws Exception {
        orderClothItemFactoryQueryDTO.setFactoryId(getFactoryId());
        if(orderClothItemFactoryQueryDTO.getBeginTime()!=null){
            orderClothItemFactoryQueryDTO.setBeginTime(DateUtils.getStartTime(orderClothItemFactoryQueryDTO.getBeginTime()));
        }
        if(orderClothItemFactoryQueryDTO.getEndTime()!=null){
            orderClothItemFactoryQueryDTO.setEndTime(DateUtils.getEndTime(orderClothItemFactoryQueryDTO.getEndTime()));
        }
        List<OrderClothItemVO> itemList = orderClothItemService.findAllFactoryClothPage(orderClothItemFactoryQueryDTO);
        for (OrderClothItemVO itemVO : itemList) {

            if (itemVO.getWashCode().startsWith(OrderNoUtils.cloth_wash_code_header)) {
                OrderClothItem orderClothItem = orderClothItemService.getById(itemVO.getId());
                orderClothItem.setFlowStatus(ClothOrderFlowStatus.inFactory.getCode());
                orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                        .set(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.inFactory.getCode())
                        .set(OrderClothItem::getInFactoryTime, DateUtils.getNowDate())
                        .set(OrderClothItem::getInFactoryById, AuthHolder.userId())
                        .set(OrderClothItem::getInFactoryBy, AuthHolder.nickName())
                        .eq(OrderClothItem::getId, itemVO.getId())
                        .eq(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode()));
                //添加记录
                orderClothItemFlowRecordService.addRecord(orderClothItem, ClothOrderFlowStatus.inFactory.getCode());

                //只要有一件衣服已经入厂，订单就要更新成已入厂状态
                if (orderClothItem.getRefundId() == null) {
                    OrderCloth orderCloth = orderClothService.getById(orderClothItem.getOrderId());
                    if (Integer.parseInt(orderCloth.getOrderStatus()) < Integer.parseInt(ClothOrderStatusType.WASHING.getCode())) {
                        orderCloth.setId(orderClothItem.getOrderId());
                        orderCloth.setOrderStatus(ClothOrderStatusType.WASHING.getCode());
                        orderCloth.buildUpdateData();
                        orderClothService.updateById(orderCloth);
                    }
                }
            }
            if (itemVO.getWashCode().startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
                OrderClothAdjunct orderClothAdjunct = orderClothAdjunctService.getById(itemVO.getId());
                if (ClothOrderFlowStatus.waitingForWash.getCode().equals(orderClothAdjunct.getFlowStatus())) {
                    orderClothAdjunct.setFlowStatus(ClothOrderFlowStatus.inFactory.getCode());
                    orderClothAdjunctService.update(new UpdateWrapper<OrderClothAdjunct>().lambda()
                            .set(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.inFactory.getCode())
                            .set(OrderClothAdjunct::getInFactoryTime, DateUtils.getNowDate())
                            .set(OrderClothAdjunct::getInFactoryById, AuthHolder.userId())
                            .set(OrderClothAdjunct::getInFactoryBy, AuthHolder.nickName())
                            .eq(OrderClothAdjunct::getId, itemVO.getId())
                            .eq(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode()));
                    //添加记录
                    orderClothItemFlowRecordService.addAdjunctRecord(orderClothAdjunct, ClothOrderFlowStatus.inFactory.getCode());
                }
            }
        }
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("工厂衣服检查")
    @GetMapping(value = "checkCloth")
    public R<OrderClothItemVO> checkCloth(@RequestParam @ApiParam("水洗唛") String washCode) throws Exception {
        OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
        OrderClothItem orderClothItem = null;
        if (washCode.startsWith(OrderNoUtils.cloth_wash_code_header)) {
            LambdaQueryWrapper<OrderClothItem> lambdaQueryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                    .eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId()).eq(OrderClothItem::getWashCode, washCode);
            orderClothItem = orderClothItemService.getOne(lambdaQueryWrapper);
            if (orderClothItem == null) {
                throw new ServiceException("未查询到衣物");
            }
            if (orderClothItem.getRefundId() != null) {
                throw new ServiceException("该衣服已撤单，无法进行检查");
            }
            if (!ClothOrderFlowStatus.inFactory.getCode().equals(orderClothItem.getFlowStatus())) {
                throw new ServiceException("该衣服无法检查，当前状态【"
                        + EnumUtils.getEnumByType(orderClothItem.getFlowStatus(), ClothOrderFlowStatus.class).getInfo() + "】");
            }
            BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
            orderClothItemVO.setIsAdjunct("N");
            orderClothItemVO.setOrderClothAdjuncts(orderClothAdjunctService.list(new QueryWrapper<OrderClothAdjunct>()
                    .lambda().eq(OrderClothAdjunct::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothColors(orderClothColorService.list(new QueryWrapper<OrderClothColor>()
                    .lambda().eq(OrderClothColor::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothCrafts(orderClothCraftService.list(new QueryWrapper<OrderClothCraft>()
                    .lambda().eq(OrderClothCraft::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothFlaws(orderClothFlawService.list(new QueryWrapper<OrderClothFlaw>()
                    .lambda().eq(OrderClothFlaw::getOrderClothId, orderClothItem.getId())));
            orderClothItemVO.setOrderClothTypes(orderClothTypeService.list(new QueryWrapper<OrderClothType>()
                    .lambda().eq(OrderClothType::getOrderClothId, orderClothItem.getId())));
            orderClothItemService.update(new UpdateWrapper<OrderClothItem>().lambda()
                    .set(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.checkCloth.getCode())
                    .set(OrderClothItem::getCheckClothTime, DateUtils.getNowDate())
                    .set(OrderClothItem::getCheckClothById, AuthHolder.userId())
                    .set(OrderClothItem::getCheckClothBy, AuthHolder.nickName())
                    .eq(OrderClothItem::getWashCode, washCode));
            //添加记录
            orderClothItemFlowRecordService.addRecord(orderClothItem, ClothOrderFlowStatus.checkCloth.getCode());
        }
        if (washCode.startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
            OrderClothAdjunct orderClothAdjunct = orderClothAdjunctService.selectOrderClothAdjunctByAdjunctNo(washCode);
            if (orderClothAdjunct == null) {
                throw new ServiceException("未查询到衣物");
            }
            if (!ClothOrderFlowStatus.inFactory.getCode().equals(orderClothAdjunct.getFlowStatus())) {
                throw new ServiceException("该衣服附件已检查，无法再次操作，当前状态【"
                        + EnumUtils.getEnumByType(orderClothAdjunct.getFlowStatus(), ClothOrderFlowStatus.class).getInfo() + "】");
            }
            if (orderClothAdjunct.getRefundId() != null) {
                throw new ServiceException("该衣服附件已撤单，无法进行检查");
            }
            orderClothItem = orderClothItemService.selectOrderClothItemById(orderClothAdjunct.getOrderClothId());
            BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
            orderClothItemVO.setIsAdjunct("Y");
            orderClothItemVO.setWashCode(orderClothAdjunct.getAdjunctNo());
            orderClothItemVO.setClothItemName("【附件】" + orderClothItemVO.getClothItemName() + " * " + orderClothAdjunct.getAdjunctName());
            orderClothItemVO.setOrderClothAdjuncts(Arrays.asList(orderClothAdjunct));

            orderClothAdjunctService.update(new UpdateWrapper<OrderClothAdjunct>().lambda()
                    .set(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.checkCloth.getCode())
                    .set(OrderClothAdjunct::getCheckClothTime, DateUtils.getNowDate())
                    .set(OrderClothAdjunct::getCheckClothById, AuthHolder.userId())
                    .set(OrderClothAdjunct::getCheckClothBy, AuthHolder.nickName())
                    .eq(OrderClothAdjunct::getAdjunctNo, washCode));
            //添加记录
            orderClothItemFlowRecordService.addAdjunctRecord(orderClothAdjunct, ClothOrderFlowStatus.checkCloth.getCode());
        }
        orderClothItemVO.setOrgName(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                .eq(SysOrg::getId, orderClothItemVO.getOrgId())
                .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType()), false).getName());
        orderClothItemVO.setFlowStatus(ClothOrderFlowStatus.checkCloth.getCode());
        return R.ok(orderClothItemVO);
    }

    @PostMapping(value = "findOutFactoryPageByFlowStatus")
    @ApiOperation("根据洗衣状态查询出厂衣服列表")
    public R<Page<OrderClothItemVO>> findOutFactoryPageByFlowStatus(@RequestBody @Valid OrderClothItemOutFactoryQueryDTO orderClothItemOutFactoryQueryDTO) throws Exception {
        if (orderClothItemOutFactoryQueryDTO.getClothType().equals("2")) {
            LambdaQueryWrapper<OrderClothAdjunct> queryWrapper = new QueryWrapper<OrderClothAdjunct>().lambda()
                    .eq(OrderClothAdjunct::getFlowStatus, ClothOrderFlowStatus.checkCloth.getCode());
            queryWrapper.eq(OrderClothAdjunct::getFactoryId, SecurityUtils.getLoginUser().getOrgId());
            if (orderClothItemOutFactoryQueryDTO.getOrgId() != null) {
                queryWrapper.eq(OrderClothAdjunct::getStoreId, orderClothItemOutFactoryQueryDTO.getOrgId());
            }
            if (StringUtils.isNotEmpty(orderClothItemOutFactoryQueryDTO.getWashCode())) {
                queryWrapper.like(OrderClothAdjunct::getAdjunctNo, orderClothItemOutFactoryQueryDTO.getWashCode());
            }
            Page<OrderClothAdjunct> page = orderClothAdjunctService.page(
                    new Page<>(orderClothItemOutFactoryQueryDTO.getPageNum()
                            , orderClothItemOutFactoryQueryDTO.getPageSize())
                    , queryWrapper);
            //查询附件
            List<OrderClothItemVO> orderClothItemVOS = new ArrayList<>();
            for (OrderClothAdjunct orderClothAdjunct : page.getRecords()) {
                OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
                OrderClothItem orderClothItem = orderClothItemService.selectOrderClothItemById(orderClothAdjunct.getOrderClothId());
                BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
                orderClothItemVO.setIsAdjunct("Y");
                orderClothItemVO.setId(orderClothAdjunct.getId());
                orderClothItemVO.setWashCode(orderClothAdjunct.getAdjunctNo());
                orderClothItemVO.setClothItemName("【附件】" + orderClothItemVO.getClothItemName() + " * " + orderClothAdjunct.getAdjunctName());
                orderClothItemVO.setOrgName(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                        .eq(SysOrg::getId, orderClothItemVO.getOrgId())
                        .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType()), false).getName());
                orderClothItemVO.setFlowStatus(orderClothAdjunct.getFlowStatus());
                orderClothItemVOS.add(orderClothItemVO);
            }
            Page<OrderClothItemVO> orderClothItemVOPage = new Page<>();
            orderClothItemVOPage.setRecords(orderClothItemVOS);
            orderClothItemVOPage.setTotal(page.getTotal());
            return R.ok(orderClothItemVOPage);
        }
        LambdaQueryWrapper<OrderClothItem> queryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                .eq(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.checkCloth.getCode());
        queryWrapper.eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId());
        if (orderClothItemOutFactoryQueryDTO.getOrgId() != null) {
            queryWrapper.eq(OrderClothItem::getOrgId, orderClothItemOutFactoryQueryDTO.getOrgId())
                    .eq(OrderClothItem::getSourceType, SourceType.STORE.getCode());
        }
        if (StringUtils.isNotEmpty(orderClothItemOutFactoryQueryDTO.getWashCode())) {
            queryWrapper.like(OrderClothItem::getWashCode, orderClothItemOutFactoryQueryDTO.getWashCode());
        }
        Page<OrderClothItem> page = orderClothItemService.page(
                new Page<>(orderClothItemOutFactoryQueryDTO.getPageNum()
                        , orderClothItemOutFactoryQueryDTO.getPageSize())
                , queryWrapper);
        if (page.getRecords().size() == 0) {
            Page<OrderClothItemVO> orderClothItemVOPage = new Page<>();
            orderClothItemVOPage.setRecords(new ArrayList<>());
            orderClothItemVOPage.setTotal(page.getTotal());
            return R.ok(orderClothItemVOPage);
        }
        Set<Long> orderClothItemIds = page.getRecords().stream().map(OrderClothItem::getId).collect(Collectors.toSet());
//        Map<Long, List<OrderClothAdjunct>> orderClothAdjunctMap = orderClothAdjunctService.list(
//                        new QueryWrapper<OrderClothAdjunct>().lambda().in(OrderClothAdjunct::getOrderClothId, orderClothItemIds))
//                .stream().collect(Collectors.groupingBy(OrderClothAdjunct::getOrderClothId));
        Map<Long, List<OrderClothColor>> orderClothColorMap = orderClothColorService.list(
                        new QueryWrapper<OrderClothColor>().lambda().in(OrderClothColor::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothColor::getOrderClothId));
        Map<Long, List<OrderClothCraft>> orderClothCraftMap = orderClothCraftService.list(
                        new QueryWrapper<OrderClothCraft>().lambda().in(OrderClothCraft::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothCraft::getOrderClothId));
        Map<Long, List<OrderClothFlaw>> orderClothFlawMap = orderClothFlawService.list(
                        new QueryWrapper<OrderClothFlaw>().lambda().in(OrderClothFlaw::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothFlaw::getOrderClothId));
        Map<Long, List<OrderClothType>> orderClothTypeMap = orderClothTypeService.list(
                        new QueryWrapper<OrderClothType>().lambda().in(OrderClothType::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothType::getOrderClothId));

        List<OrderClothItemVO> orderClothItemVOS = new ArrayList<>();
        for (OrderClothItem record : page.getRecords()) {
            OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
            BeanUtils.copyProperties(record, orderClothItemVO);
//            orderClothItemVO.setOrderClothAdjuncts(orderClothAdjunctMap.get(record.getId()));
            orderClothItemVO.setOrderClothColors(orderClothColorMap.get(record.getId()));
            orderClothItemVO.setOrderClothCrafts(orderClothCraftMap.get(record.getId()));
            orderClothItemVO.setOrderClothFlaws(orderClothFlawMap.get(record.getId()));
            orderClothItemVO.setOrderClothTypes(orderClothTypeMap.get(record.getId()));
            orderClothItemVO.setOrgName(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                    .eq(SysOrg::getId, orderClothItemVO.getOrgId())
                    .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType()), false).getName());
            orderClothItemVOS.add(orderClothItemVO);
        }

        Page<OrderClothItemVO> orderClothItemVOPage = new Page<>();
        orderClothItemVOPage.setRecords(orderClothItemVOS);
        orderClothItemVOPage.setTotal(page.getTotal());
        return R.ok(orderClothItemVOPage);
    }

    @GetMapping(value = "/findFactoryClothPage")
    @ApiOperation("查询工厂衣服记录")
    public TableDataInfo findFactoryClothPage(OrderClothItemFactoryQueryDTO orderClothItemFactoryQueryDTO) throws Exception {
        startPage();
        if (orderClothItemFactoryQueryDTO.getClothType() != null && orderClothItemFactoryQueryDTO.getClothType().equals("2")) {
            LambdaQueryWrapper<OrderClothAdjunct> queryWrapper = new QueryWrapper<OrderClothAdjunct>().lambda()
                    .eq(OrderClothAdjunct::getFactoryId, SecurityUtils.getLoginUser().getOrgId());
            if (StringUtils.isNotEmpty(orderClothItemFactoryQueryDTO.getFlowStatus())) {
                switch (EnumUtils.getEnumByType(orderClothItemFactoryQueryDTO.getFlowStatus(), ClothOrderFlowStatus.class)) {
                    case inFactory: {
                        queryWrapper.isNotNull(OrderClothAdjunct::getInFactoryById);
                        break;
                    }
                    case outFactory: {
                        queryWrapper.isNotNull(OrderClothAdjunct::getOutFactoryById);
                        break;
                    }
                    case checkCloth: {
                        queryWrapper.isNotNull(OrderClothAdjunct::getCheckClothById);
                        break;
                    }
                    default: {
                        throw new ServiceException("流程状态查询不正确");
                    }
                }
            }
            if (StringUtils.isNotEmpty(orderClothItemFactoryQueryDTO.getClothName())) {
                queryWrapper.like(OrderClothAdjunct::getAdjunctName, orderClothItemFactoryQueryDTO.getClothName());
            }
            if (orderClothItemFactoryQueryDTO.getBeginTime() != null) {
                queryWrapper.ge(OrderClothAdjunct::getCreateTime, orderClothItemFactoryQueryDTO.getBeginTime());
            }
            if (orderClothItemFactoryQueryDTO.getEndTime() != null) {
                queryWrapper.lt(OrderClothAdjunct::getCreateTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndTime(), 1));
            }
            if (orderClothItemFactoryQueryDTO.getBeginInFactoryTime() != null) {
                queryWrapper.ge(OrderClothAdjunct::getInFactoryTime, orderClothItemFactoryQueryDTO.getBeginInFactoryTime());
            }
            if (orderClothItemFactoryQueryDTO.getEndInFactoryTime() != null) {
                queryWrapper.lt(OrderClothAdjunct::getInFactoryTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndInFactoryTime(), 1));
            }
            if (orderClothItemFactoryQueryDTO.getBeginOutFactoryTime() != null) {
                queryWrapper.ge(OrderClothAdjunct::getOutFactoryTime, orderClothItemFactoryQueryDTO.getBeginOutFactoryTime());
            }
            if (orderClothItemFactoryQueryDTO.getEndOutFactoryTime() != null) {
                queryWrapper.lt(OrderClothAdjunct::getOutFactoryTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndOutFactoryTime(), 1));
            }
            if (orderClothItemFactoryQueryDTO.getBeginCheckClothTime() != null) {
                queryWrapper.ge(OrderClothAdjunct::getCheckClothTime, orderClothItemFactoryQueryDTO.getBeginCheckClothTime());
            }
            if (orderClothItemFactoryQueryDTO.getEndCheckClothTime() != null) {
                queryWrapper.lt(OrderClothAdjunct::getCheckClothTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndCheckClothTime(), 1));
            }
            if (orderClothItemFactoryQueryDTO.getInFactoryById() != null) {
                queryWrapper.eq(OrderClothAdjunct::getInFactoryById, orderClothItemFactoryQueryDTO.getInFactoryById());
            }
            if (orderClothItemFactoryQueryDTO.getOutFactoryById() != null) {
                queryWrapper.eq(OrderClothAdjunct::getOutFactoryById, orderClothItemFactoryQueryDTO.getOutFactoryById());
            }
            if (orderClothItemFactoryQueryDTO.getCheckClothById() != null) {
                queryWrapper.eq(OrderClothAdjunct::getCheckClothById, orderClothItemFactoryQueryDTO.getCheckClothById());
            }
            if (StringUtils.isNotEmpty(orderClothItemFactoryQueryDTO.getWashCode())) {
                queryWrapper.eq(OrderClothAdjunct::getAdjunctNo, orderClothItemFactoryQueryDTO.getWashCode());
            }
            if (orderClothItemFactoryQueryDTO.getOrgId() != null) {
                queryWrapper.eq(OrderClothAdjunct::getStoreId, orderClothItemFactoryQueryDTO.getOrgId());
            }
            queryWrapper.orderByDesc(BaseEntity::getCreateTime);

            List<OrderClothAdjunct> itemList = orderClothAdjunctService.list(queryWrapper);

            //查询附件
            List<OrderClothItemVO> orderClothItemVOS = new ArrayList<>();
            for (OrderClothAdjunct orderClothAdjunct : itemList) {
                OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
                OrderClothItem orderClothItem = orderClothItemService.selectOrderClothItemById(orderClothAdjunct.getOrderClothId());
                BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
                orderClothItemVO.setIsAdjunct("Y");
                orderClothItemVO.setId(orderClothAdjunct.getId());
                orderClothItemVO.setWashCode(orderClothAdjunct.getAdjunctNo());
                orderClothItemVO.setClothItemName("【附件】" + orderClothItemVO.getClothItemName() + " * " + orderClothAdjunct.getAdjunctName());
                orderClothItemVO.setOrgName(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                        .eq(SysOrg::getId, orderClothItemVO.getOrgId())
                        .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType()), false).getName());
                orderClothItemVO.setFlowStatus(orderClothAdjunct.getFlowStatus());
                orderClothItemVOS.add(orderClothItemVO);
            }
            return getDataTable(orderClothItemVOS, new PageInfo(itemList).getTotal());
        }

        LambdaQueryWrapper<OrderClothItem> queryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                .eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId());
        if (StringUtils.isNotEmpty(orderClothItemFactoryQueryDTO.getFlowStatus())) {
            switch (EnumUtils.getEnumByType(orderClothItemFactoryQueryDTO.getFlowStatus(), ClothOrderFlowStatus.class)) {
                case waitingForWash: {
                    queryWrapper.eq(OrderClothItem::getFlowStatus, ClothOrderFlowStatus.waitingForWash.getCode());
                    break;
                }
                case inFactory: {
                    queryWrapper.isNotNull(OrderClothItem::getInFactoryById);
                    break;
                }
                case outFactory: {
                    queryWrapper.isNotNull(OrderClothItem::getOutFactoryById);
                    break;
                }
                case checkCloth: {
                    queryWrapper.isNotNull(OrderClothItem::getCheckClothById);
                    break;
                }
                default: {
                    throw new ServiceException("流程状态查询不正确");
                }
            }
        }
        if (StringUtils.isNotEmpty(orderClothItemFactoryQueryDTO.getClothName())) {
            queryWrapper.like(OrderClothItem::getClothItemName, orderClothItemFactoryQueryDTO.getClothName());
        }
        if (orderClothItemFactoryQueryDTO.getBeginTime() != null) {
            queryWrapper.ge(OrderClothItem::getCreateTime, orderClothItemFactoryQueryDTO.getBeginTime());
        }
        if (orderClothItemFactoryQueryDTO.getEndTime() != null) {
            queryWrapper.lt(OrderClothItem::getCreateTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndTime(), 1));
        }
        if (orderClothItemFactoryQueryDTO.getBeginInFactoryTime() != null) {
            queryWrapper.ge(OrderClothItem::getInFactoryTime, orderClothItemFactoryQueryDTO.getBeginInFactoryTime());
        }
        if (orderClothItemFactoryQueryDTO.getEndInFactoryTime() != null) {
            queryWrapper.lt(OrderClothItem::getInFactoryTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndInFactoryTime(), 1));
        }
        if (orderClothItemFactoryQueryDTO.getBeginOutFactoryTime() != null) {
            queryWrapper.ge(OrderClothItem::getOutFactoryTime, orderClothItemFactoryQueryDTO.getBeginOutFactoryTime());
        }
        if (orderClothItemFactoryQueryDTO.getEndOutFactoryTime() != null) {
            queryWrapper.lt(OrderClothItem::getOutFactoryTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndOutFactoryTime(), 1));
        }
        if (orderClothItemFactoryQueryDTO.getBeginCheckClothTime() != null) {
            queryWrapper.ge(OrderClothItem::getCheckClothTime, orderClothItemFactoryQueryDTO.getBeginCheckClothTime());
        }
        if (orderClothItemFactoryQueryDTO.getEndCheckClothTime() != null) {
            queryWrapper.lt(OrderClothItem::getCheckClothTime, DateUtils.addDays(orderClothItemFactoryQueryDTO.getEndCheckClothTime(), 1));
        }
        if (orderClothItemFactoryQueryDTO.getInFactoryById() != null) {
            queryWrapper.eq(OrderClothItem::getInFactoryById, orderClothItemFactoryQueryDTO.getInFactoryById());
        }
        if (orderClothItemFactoryQueryDTO.getOutFactoryById() != null) {
            queryWrapper.eq(OrderClothItem::getOutFactoryById, orderClothItemFactoryQueryDTO.getOutFactoryById());
        }
        if (orderClothItemFactoryQueryDTO.getCheckClothById() != null) {
            queryWrapper.eq(OrderClothItem::getCheckClothById, orderClothItemFactoryQueryDTO.getCheckClothById());
        }
        if (StringUtils.isNotEmpty(orderClothItemFactoryQueryDTO.getWashCode())) {
            queryWrapper.eq(OrderClothItem::getWashCode, orderClothItemFactoryQueryDTO.getWashCode());
        }
        if (orderClothItemFactoryQueryDTO.getOrgId() != null) {
            queryWrapper.eq(OrderClothItem::getOrgId, orderClothItemFactoryQueryDTO.getOrgId());
            queryWrapper.eq(OrderClothItem::getSourceType, orderClothItemFactoryQueryDTO.getSourceType());
        }
        queryWrapper.orderByDesc(BaseEntity::getCreateTime);

        List<OrderClothItem> itemList = orderClothItemService.list(queryWrapper);
        LambdaQueryWrapper<SysOrg> sysOrgLambdaQueryWrapper = new QueryWrapper<SysOrg>().lambda();
        if (itemList.stream().filter(orderClothItemVO -> SourceType.FACTORY.getCode()
                .equals(orderClothItemVO.getSourceType())).collect(Collectors.toSet()).size() > 0) {
            sysOrgLambdaQueryWrapper.and(qw -> qw.eq(SysOrg::getSourceType, SourceType.FACTORY.getCode())
                    .in(SysOrg::getId, itemList.stream()
                            .filter(orderClothItemVO -> SourceType.FACTORY.getCode().equals(orderClothItemVO.getSourceType()))
                            .map(OrderClothItem::getOrgId).collect(Collectors.toSet())));
        }
        if (itemList.stream().filter(orderClothItemVO -> SourceType.STORE.getCode()
                .equals(orderClothItemVO.getSourceType())).collect(Collectors.toSet()).size() > 0) {
            sysOrgLambdaQueryWrapper.or(qw -> qw.eq(SysOrg::getSourceType, SourceType.STORE.getCode())
                    .in(SysOrg::getId, itemList.stream()
                            .filter(orderClothItemVO -> SourceType.STORE.getCode().equals(orderClothItemVO.getSourceType()))
                            .map(OrderClothItem::getOrgId).collect(Collectors.toSet())));
        }
        List<SysOrg> sysOrgs = sysOrgService.list(sysOrgLambdaQueryWrapper);
        Map<Long, SysOrg> storeOrgMap = sysOrgs.stream().filter(sysOrg -> SourceType.STORE.getCode()
                .equals(sysOrg.getSourceType())).collect(Collectors.toMap(SysOrg::getId, SysOrg -> SysOrg));
        List<OrderClothItemVO> itemVOList = new ArrayList<>();
        for (OrderClothItem record : itemList) {
            OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
            BeanUtils.copyProperties(record, orderClothItemVO);
            if (storeOrgMap.get(record.getOrgId()) != null) {
                orderClothItemVO.setOrgName(storeOrgMap.get(record.getOrgId()).getName());
            } else {
                orderClothItemVO.setOrgName("--");
            }
            itemVOList.add(orderClothItemVO);

        }
        return getDataTable(itemVOList, new PageInfo(itemList).getTotal());
    }


    @GetMapping(value = "/findAllFactoryClothPage")
    @ApiOperation("查询工厂衣服记录(衣服和附件一起查询)")
    public TableDataInfo findAllFactoryClothPage(OrderClothItemFactoryQueryDTO orderClothItemFactoryQueryDTO) throws Exception {
        startPage();
        orderClothItemFactoryQueryDTO.setFactoryId(getFactoryId());
        if(orderClothItemFactoryQueryDTO.getBeginTime()!=null){
            orderClothItemFactoryQueryDTO.setBeginTime(DateUtils.getStartTime(orderClothItemFactoryQueryDTO.getBeginTime()));
        }
        if(orderClothItemFactoryQueryDTO.getEndTime()!=null){
            orderClothItemFactoryQueryDTO.setEndTime(DateUtils.getEndTime(orderClothItemFactoryQueryDTO.getEndTime()));
        }
        List<OrderClothItemVO> itemList = orderClothItemService.findAllFactoryClothPage(orderClothItemFactoryQueryDTO);
        List<SysOrg> sysOrgs = sysOrgService.list();
        Map<Long, SysOrg> storeOrgMap = sysOrgs.stream().filter(sysOrg -> SourceType.STORE.getCode()
                .equals(sysOrg.getSourceType())).collect(Collectors.toMap(SysOrg::getId, SysOrg -> SysOrg));
        for (OrderClothItemVO itemVO : itemList) {
            if (storeOrgMap.get(itemVO.getStoreId()) != null) {
                itemVO.setStoreName(storeOrgMap.get(itemVO.getStoreId()).getName());
            }
        }
        return getDataTable(itemList, new PageInfo(itemList).getTotal());
    }


    /**
     * 查询洗衣订单衣服明细列表
     */
    @PreAuthorize("@ss.hasPermi('order:clothItem:list')")
    @GetMapping(value = "/list")
    @ApiOperation(value = "查询洗衣订单衣服明细列表")
    public TableDataInfo list(OrderClothItemQueryDTO orderClothItemQueryDTO) {
        //1=超时,2=超时3天,3=超时5天
        startPage();
        if (StringUtils.isNotEmpty(orderClothItemQueryDTO.getTimeoutStatus())) {
            if (orderClothItemQueryDTO.getTimeoutStatus().equals("1")) {
                orderClothItemQueryDTO.setTimeoutStartTime(DateUtils.getNowDate());
            }
            if (orderClothItemQueryDTO.getTimeoutStatus().equals("2")) {
                orderClothItemQueryDTO.setTimeoutStartTime(DateUtils.addDays(DateUtils.getNowDate(), -3));
                orderClothItemQueryDTO.setTimeoutEndTime(DateUtils.addDays(DateUtils.getNowDate(), -5));
            }
            if (orderClothItemQueryDTO.getTimeoutStatus().equals("3")) {
                orderClothItemQueryDTO.setTimeoutStartTime(DateUtils.addDays(DateUtils.getNowDate(), -5));
            }
        }
        if (getLoginUser().getSourceType().equals(SourceType.STORE.getCode())) {
            orderClothItemQueryDTO.setStoreId(getStoreId());
        }
        List<OrderClothItemVO> orderClothItemVOList = orderClothItemService.queryClothItem(orderClothItemQueryDTO);

        if (orderClothItemVOList.size() == 0) {
            return getDataTable(orderClothItemVOList, new PageInfo(orderClothItemVOList).getTotal());
        }
        Set<Long> orderClothItemIds = orderClothItemVOList.stream().map(OrderClothItemVO::getId).collect(Collectors.toSet());
        Map<Long, List<OrderClothAdjunct>> orderClothAdjunctMap = orderClothAdjunctService.list(
                        new QueryWrapper<OrderClothAdjunct>().lambda().in(OrderClothAdjunct::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothAdjunct::getOrderClothId));
        Map<Long, List<OrderClothColor>> orderClothColorMap = orderClothColorService.list(
                        new QueryWrapper<OrderClothColor>().lambda().in(OrderClothColor::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothColor::getOrderClothId));
        Map<Long, List<OrderClothCraft>> orderClothCraftMap = orderClothCraftService.list(
                        new QueryWrapper<OrderClothCraft>().lambda().in(OrderClothCraft::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothCraft::getOrderClothId));
        Map<Long, List<OrderClothFlaw>> orderClothFlawMap = orderClothFlawService.list(
                        new QueryWrapper<OrderClothFlaw>().lambda().in(OrderClothFlaw::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothFlaw::getOrderClothId));
        Map<Long, List<OrderClothType>> orderClothTypeMap = orderClothTypeService.list(
                        new QueryWrapper<OrderClothType>().lambda().in(OrderClothType::getOrderClothId, orderClothItemIds))
                .stream().collect(Collectors.groupingBy(OrderClothType::getOrderClothId));
        Map<Long, AppUser> appUserMap = appUserService.list(new QueryWrapper<AppUser>().lambda().in(AppUser::getId, orderClothItemVOList.stream()
                .map(OrderClothItemVO::getAppUserId).collect(Collectors.toSet()))).stream().collect(Collectors.toMap(AppUser::getId, AppUser -> AppUser));
        Map<Long, ClothHanger> clothHangerMap = new HashMap<>();
        if (orderClothItemVOList.stream()
                .filter(orderClothItem -> orderClothItem.getClothHangerId() != null)
                .map(OrderClothItemVO::getClothHangerId)
                .collect(Collectors.toSet()).size() > 0) {
            clothHangerMap = clothHangerService.list(new QueryWrapper<ClothHanger>().lambda()
                            .in(ClothHanger::getId, orderClothItemVOList.stream()
                                    .filter(orderClothItem -> orderClothItem.getClothHangerId() != null)
                                    .map(OrderClothItemVO::getClothHangerId)
                                    .collect(Collectors.toSet()))).stream()
                    .collect(Collectors.toMap(ClothHanger::getId, ClothHanger -> ClothHanger));
        }
        Map<Long, SysOrg> storeOrgMap = new HashMap<>();
        if (orderClothItemVOList.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, orderClothItemVOList.stream()
                            .map(OrderClothItemVO::getOrgId).collect(Collectors.toSet()))).stream()
                    .collect(Collectors.toMap(SysOrg::getId, SysOrg -> SysOrg));
        }
        List<OrderClothItemVO> orderClothItemVOS = new ArrayList<>();
        for (OrderClothItemVO orderClothItemVO : orderClothItemVOList) {
            orderClothItemVO.setOrderClothAdjuncts(orderClothAdjunctMap.get(orderClothItemVO.getId()));
            orderClothItemVO.setOrderClothColors(orderClothColorMap.get(orderClothItemVO.getId()));
            orderClothItemVO.setOrderClothCrafts(orderClothCraftMap.get(orderClothItemVO.getId()));
            orderClothItemVO.setOrderClothFlaws(orderClothFlawMap.get(orderClothItemVO.getId()));
            orderClothItemVO.setOrderClothTypes(orderClothTypeMap.get(orderClothItemVO.getId()));
            AppUser appUser = appUserMap.get(orderClothItemVO.getAppUserId());
            orderClothItemVO.setAppUserName(appUser != null ? appUser.getRealName() : "--");
            orderClothItemVO.setAppUserPhoneNumber(appUser != null ? appUser.getPhoneNumber() : "--");
            if (orderClothItemVO.getClothHangerId() != null && clothHangerMap.containsKey(orderClothItemVO.getClothHangerId())) {
                orderClothItemVO.setClothHanger(clothHangerMap.get(orderClothItemVO.getClothHangerId()));
            }
            if (orderClothItemVO.getPlanSendClothTime() != null) {
                if (orderClothItemVO.getPlanSendClothTime().getTime() < DateUtils.getNowDate().getTime()) {
                    orderClothItemVO.setTimeoutDayNum((DateUtils.getNowDate().getTime()
                            - orderClothItemVO.getPlanSendClothTime().getTime()) / (24 * 3600 * 1000) + 1);
                }
            }
            //如果为总部或工厂查询，需要带上组织信息返回
            if (SourceType.MANAGER.getCode().equals(SecurityUtils.getLoginUser().getSourceType()) ||
                    SourceType.FACTORY.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
                if (SourceType.STORE.getCode().equals(orderClothItemVO.getSourceType())) {
                    orderClothItemVO.setSysOrg(storeOrgMap.get(orderClothItemVO.getOrgId()));
                }
            }
            orderClothItemVOS.add(orderClothItemVO);
        }
        return getDataTable(orderClothItemVOS, new PageInfo(orderClothItemVOList).getTotal());
    }

    /**
     * 导出洗衣订单衣服明细列表
     */
    @PreAuthorize("@ss.hasPermi('order:cloth:export')")
    @Log(title = "洗衣订单衣服明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出洗衣订单衣服明细列表")
    public void export(HttpServletResponse response, OrderClothItem orderClothItem) {
        List<OrderClothItem> list = orderClothItemService.selectOrderClothItemList(orderClothItem);
        ExcelUtil<OrderClothItem> util = new ExcelUtil<OrderClothItem>(OrderClothItem.class);
        util.exportExcel(response, list, "洗衣订单衣服明细数据");
    }

    /**
     * 获取洗衣订单衣服明细详细信息
     */
//    @PreAuthorize("@ss.hasPermi('order:cloth:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取洗衣订单衣服明细详细信息")
    public R<OrderClothItemVO> getInfo(@PathVariable("id") Long id) {
        LambdaQueryWrapper<OrderClothItem> queryWrapper = new QueryWrapper<OrderClothItem>().lambda()
                .eq(OrderClothItem::getId, id);
        if (SourceType.FACTORY.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            queryWrapper.eq(OrderClothItem::getFactoryId, SecurityUtils.getLoginUser().getOrgId());
        }
        if (SourceType.STORE.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            queryWrapper.eq(OrderClothItem::getOrgId, SecurityUtils.getLoginUser().getOrgId());
        }
        OrderClothItem orderClothItem = orderClothItemService.getOne(queryWrapper
        );
        if (orderClothItem == null) {
            return R.ok();
//            throw new ServiceException("未查询到数据");
        }
        OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
        BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
        orderClothItemVO.setOrderClothAdjuncts(orderClothAdjunctService.list(new QueryWrapper<OrderClothAdjunct>()
                .lambda().eq(OrderClothAdjunct::getOrderClothId, orderClothItem.getId())));
        orderClothItemVO.setOrderClothColors(orderClothColorService.list(new QueryWrapper<OrderClothColor>()
                .lambda().eq(OrderClothColor::getOrderClothId, orderClothItem.getId())));
        orderClothItemVO.setOrderClothCrafts(orderClothCraftService.list(new QueryWrapper<OrderClothCraft>()
                .lambda().eq(OrderClothCraft::getOrderClothId, orderClothItem.getId())));
        orderClothItemVO.setOrderClothFlaws(orderClothFlawService.list(new QueryWrapper<OrderClothFlaw>()
                .lambda().eq(OrderClothFlaw::getOrderClothId, orderClothItem.getId())));
        orderClothItemVO.setOrderClothTypes(orderClothTypeService.list(new QueryWrapper<OrderClothType>()
                .lambda().eq(OrderClothType::getOrderClothId, orderClothItem.getId())));
        orderClothItemVO.setOrgName(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                .eq(SysOrg::getId, orderClothItemVO.getOrgId())
                .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType()), false).getName());
        if (SourceType.MANAGER.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            orderClothItemVO.setSysOrg(sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                    .eq(SysOrg::getSourceType, orderClothItemVO.getSourceType())
                    .eq(SysOrg::getId, orderClothItemVO.getOrgId())));
        }
        return R.ok(orderClothItemVO);
    }

    /**
     * 新增洗衣订单衣服明细
     */
    @PreAuthorize("@ss.hasPermi('order:cloth:add')")
    @Log(title = "洗衣订单衣服明细", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增洗衣订单衣服明细")
    public AjaxResult add(@RequestBody OrderClothItem orderClothItem) {
        orderClothItem.setCreateById(getUserId());
        orderClothItem.setCreateBy(getUsername());
        return toAjax(orderClothItemService.insertOrderClothItem(orderClothItem));
    }

    /**
     * 修改洗衣订单衣服明细
     */
    @PreAuthorize("@ss.hasPermi('order:cloth:edit')")
    @Log(title = "洗衣订单衣服明细", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改洗衣订单衣服明细")
    public AjaxResult edit(@RequestBody OrderClothItem orderClothItem) {
        orderClothItem.setUpdateById(getUserId());
        orderClothItem.setUpdateBy(getUsername());
        return toAjax(orderClothItemService.updateOrderClothItem(orderClothItem));
    }

    /**
     * 删除洗衣订单衣服明细
     */
    @PreAuthorize("@ss.hasPermi('order:cloth:remove')")
    @Log(title = "洗衣订单衣服明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除洗衣订单衣服明细")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(orderClothItemService.deleteOrderClothItemByIds(ids));
    }


    /**
     * 查询洗衣订单-待上挂衣服列表
     */
    @GetMapping("/getOrderClothItemListByUpHanger")
    @ApiOperation(value = "查询洗衣订单-待上挂衣服列表")
    public R<Page<OrderClothItemVO>> getOrderClothItemListByUpHanger(OrderClothHangerDTO orderClothHangerDTO) {

        if (StringUtils.isNotBlank(orderClothHangerDTO.getWashCode()) && orderClothHangerDTO.getWashCode().startsWith(OrderNoUtils.cloth_wash_adjust_code_header)) {
            OrderClothItemVO orderClothItemVO = new OrderClothItemVO();
            OrderClothAdjunct orderClothAdjunct = orderClothAdjunctService.selectOrderClothAdjunctByAdjunctNo(orderClothHangerDTO.getWashCode());
            if (orderClothAdjunct == null) {
                throw new ServiceException("未查询到衣物");
            }
            OrderClothItem orderClothItem = orderClothItemService.selectOrderClothItemById(orderClothAdjunct.getOrderClothId());
            BeanUtils.copyProperties(orderClothItem, orderClothItemVO);
            orderClothItemVO.setIsAdjunct("Y");
            orderClothItemVO.setWashCode(orderClothAdjunct.getAdjunctNo());
            orderClothItemVO.setClothItemName("【附件】" + orderClothItemVO.getClothItemName() + " * " + orderClothAdjunct.getAdjunctName());
            List<OrderClothItemVO> orderClothItemVOList = CollectionUtil.newArrayList(orderClothItemVO);
            Page<OrderClothItemVO> orderClothItemVOPage = new Page<>();
            orderClothItemVOPage.setRecords(orderClothItemVOList);
            orderClothItemVOPage.setTotal(1);
            return R.ok(orderClothItemVOPage);
        }
        return R.ok(orderClothItemService.getOrderClothItemListByUpHanger(orderClothHangerDTO));
    }

    /**
     * 重洗衣服
     */
    @Log(title = "重洗衣服", businessType = BusinessType.UPDATE)
    @GetMapping("/reFlowCloth")
    @ApiOperation(value = "重洗衣服")
    public AjaxResult reFlowCloth(@RequestParam Long orderClothItemId) {
        orderClothItemService.reFlowCloth(orderClothItemId);
        return toAjax(true);
    }

    /**
     * 返洗衣服
     */
    @Log(title = "返洗衣服", businessType = BusinessType.UPDATE)
    @GetMapping("/reFlowClothByStore")
    @ApiOperation(value = "返洗衣服")
    public AjaxResult reFlowClothByStore(@RequestParam Long orderClothItemId) {
        orderClothItemService.reFlowClothByStore(orderClothItemId);
        return toAjax(true);
    }
}
