package cn.iocoder.yudao.module.tickets.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.common.RecordTypeEnum;
import cn.iocoder.yudao.common.RepairRoleEnum;
import cn.iocoder.yudao.common.SoStatusEnum;
import cn.iocoder.yudao.common.TicketsItemStatusEnum;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.entity.RepairWorker;
import cn.iocoder.yudao.module.base.service.RepairRecordsService;
import cn.iocoder.yudao.module.base.service.RepairWorkerService;
import cn.iocoder.yudao.module.project.entity.RepairWares;
import cn.iocoder.yudao.module.project.service.RepairWaresService;
import cn.iocoder.yudao.module.stockOperate.entity.DlRepairSoi;
import cn.iocoder.yudao.module.stockOperate.mapper.DlRepairSoMapper;
import cn.iocoder.yudao.module.stockOperate.service.DlRepairSoService;
import cn.iocoder.yudao.module.stockOperate.service.DlRepairSoiService;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleReqDTO;
import cn.iocoder.yudao.module.tickets.entity.DlRepairTickets;
import cn.iocoder.yudao.module.tickets.entity.DlRepairTitem;
import cn.iocoder.yudao.module.tickets.entity.DlTicketWares;
import cn.iocoder.yudao.module.tickets.entity.DlTwItem;
import cn.iocoder.yudao.module.tickets.mapper.DlTicketWaresMapper;
import cn.iocoder.yudao.module.tickets.service.DlRepairTicketsService;
import cn.iocoder.yudao.module.tickets.service.DlRepairTitemService;
import cn.iocoder.yudao.module.tickets.service.DlTicketWaresService;
import cn.iocoder.yudao.module.tickets.service.DlTwItemService;
import cn.iocoder.yudao.module.tickets.vo.DlTicketWaresReqVO;
import cn.iocoder.yudao.module.tickets.vo.DlTicketWaresRespVO;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;

/**
 * 针对表【dl_ticket_wares(工单配件申请/退回表)】的数据库操作Service实现
 *
 * @author 小李
 * @date 11:56 2024/10/15
 **/
@Service
public class DlTicketWaresServiceImpl extends ServiceImpl<DlTicketWaresMapper, DlTicketWares> implements DlTicketWaresService {


    @Resource
    private DlTwItemService twItemService;

    @Resource
    @Lazy
    private DlRepairTicketsService repairTicketsService;

    @Resource
    @Lazy
    private RepairWorkerService repairWorkerService;

    @Resource
    @Lazy
    private DlRepairTitemService repairTitemService;

    @Resource
    @Lazy
    private DlRepairSoService repairSoService;

    @Resource
    @Lazy
    private DlRepairSoiService repairSoiService;

    @Resource
    @Lazy
    private RepairWaresService repairWaresService;

    @Resource
    @Lazy
    private DlRepairSoMapper dlRepairSoMapper;

    @Resource
    @Lazy
    private RoleApi roleApi;

    @Resource
    @Lazy
    private PermissionApi permissionApi;
    @Resource
    private RepairRecordsService repairRecordsService;

    /**
     * 分页查询
     *
     * @param reqVO 请求对象
     * @author 小李
     * @date 12:01 2024/10/15
     **/
    @Override
    public IPage<DlTicketWares> getPage(DlTicketWaresReqVO reqVO, Page<DlTicketWares> page) {
        // 确认查看者身份
        String userRoleCode = repairTicketsService.getUserRole();
        if (userRoleCode.equals(RepairRoleEnum.ADMIN.getCode()) || userRoleCode.equals(RepairRoleEnum.INSPECTION.getCode())) {
            //维修管理员和总检，看所有数据
        } else if (userRoleCode.equals(RepairRoleEnum.ADVISOR.getCode())) {
            //服务顾问
            reqVO.setAdviserId(SecurityFrameworkUtils.getLoginUserId());
        } else if (userRoleCode.equals(RepairRoleEnum.REPAIR_STAFF.getCode())) {
            //维修工，进一步判断是否是班组长
            boolean ifLeader = repairWorkerService.getIfLeader();
            if (ifLeader) {
                //班组长，看本班组所有数据
                RepairWorker one = repairWorkerService.getOne(new LambdaQueryWrapper<RepairWorker>().eq(RepairWorker::getUserId, SecurityFrameworkUtils.getLoginUserId()));
                // 查自己班组的员工信息
                List<RepairWorker> list = repairWorkerService.list(new LambdaQueryWrapper<RepairWorker>().eq(RepairWorker::getWorkType, one.getWorkType()));
                // 所有的员工信息
                List<Long> userIds = list.stream().map(RepairWorker::getUserId).collect(Collectors.toList());
                reqVO.setUserIds(userIds);
            } else {
                //普通维修工
                reqVO.setUserIds(Collections.singletonList(SecurityFrameworkUtils.getLoginUserId()));
            }
        } else if (userRoleCode.equals(RepairRoleEnum.WAREHOUSE.getCode())) {
            // 维修仓库管理员
            reqVO.setStatus(null);
            reqVO.setUserRole(5);
        } else {
            return null;
        }
        return baseMapper.getPage(reqVO, page);
    }

    /**
     * 查询当前工单下的配件申请单
     *
     * @param reqVO DlTicketWaresReqVO
     * @return java.util.List<cn.iocoder.yudao.module.tickets.entity.DlTicketWares>
     * @author PQZ
     * @date 13:44 2024/10/19
     **/
    @Override
    public List<DlTicketWares> listByTicket(DlTicketWaresReqVO reqVO) {
        // 确认查看者身份
        String userRoleCode = repairTicketsService.getUserRole();
        List<DlTicketWares> result = new ArrayList<>();
        //维修业务管理员、总检、服务顾问均可以进行审批
        if (userRoleCode.equals(RepairRoleEnum.ADMIN.getCode()) || userRoleCode.equals(RepairRoleEnum.INSPECTION.getCode()) || userRoleCode.equals(RepairRoleEnum.ADVISOR.getCode())) {
            LambdaQueryWrapper<DlTicketWares> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DlTicketWares::getTicketId, reqVO.getTicketId());
            if (null != reqVO.getStatus()) {
                lambdaQueryWrapper.eq(DlTicketWares::getStatus, reqVO.getStatus());
            }
            result = list(lambdaQueryWrapper);
        }
        return result;
    }

    /**
     * 新增、修改
     *
     * @param respVO 请求对象
     * @author 小李
     * @date 12:14 2024/10/15
     **/
    @Override
    @DSTransactional
    public void updateTicketWares(DlTicketWaresRespVO respVO) {
        // 新增、修改主表
        // 查询操作人的工人信息
        RepairWorker one = repairWorkerService.getOne(new LambdaQueryWrapper<RepairWorker>().eq(RepairWorker::getUserId, SecurityFrameworkUtils.getLoginUserId()));
        respVO.setRepairId(one.getUserId());
        respVO.setRepairName(one.getUserName());
        baseMapper.insertOrUpdate(respVO);
        // 新增、修改子表
        List<DlTwItem> list = respVO.getItems().stream().map(item -> item.setTwId(respVO.getId())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(list)) {
            throw exception0(500, "配件列表为空");
        }
        twItemService.saveOrUpdateBatch(list);

        // 通知对应的维修服务顾问和总检
        // 维修服务顾问即创建工单时选的是谁
        DlRepairTickets tickets = repairTicketsService.getById(respVO.getTicketId());
        repairWorkerService.sentMessage(Long.valueOf(tickets.getAdviserId()), "您有新的配件申请单需要审核");
        // 总检查角色包含总检的员工
        // 取这个角色的角色信息
        RoleReqDTO roleInfo = roleApi.getRoleInfo(RepairRoleEnum.INSPECTION.getCode());
        // 通过角色信息查有这个角色的人
        List<Long> ids = permissionApi.getUserIdByRoleId(roleInfo.getId());
        // 发通知
        if (CollectionUtil.isNotEmpty(ids)) {
            ids.forEach(id -> repairWorkerService.sentMessage(id, "您有新的配件申请单需要审核"));
        }
    }

    /**
     * 删除
     *
     * @param id id
     * @author 小李
     * @date 12:21 2024/10/15
     **/
    @Override
    @DSTransactional
    public void removeTicketWares(String id) {
        // 删除主表
        baseMapper.deleteById(id);
        // 删除子表
        twItemService.remove(new LambdaQueryWrapper<DlTwItem>().eq(DlTwItem::getTwId, id));
    }

    /**
     * 审核
     *
     * @param respVO 请求对象
     * @author 小李
     * @date 21:15 2024/10/15
     **/
    @Override
    @DSTransactional
    public void auditTicketWares(DlTicketWaresRespVO respVO) {
        // 设置单据状态
        //配件申请单id
        String mainId = respVO.getId();
        //单据类型，现在只有配件申请单  01
        String type = respVO.getType();
        //单据状态  02 通过   05驳回
        String status = respVO.getStatus();
        //配件信息
        List<DlRepairTitem> repairItemList = respVO.getWares();
        DlTicketWares updateObj = this.getById(mainId);
        String ticketMainId = updateObj.getTicketId();
        updateObj.setStatus(status);
        this.updateById(updateObj);
        // 如果是通过并且是领料就还需要把配件信息加入到工单中
        if (ObjectUtil.isNotEmpty(status) && status.equals("02") && type.equals("01")) {
            // 更新维修工单
            if(null!=respVO.getRepairWaresList()){
                repairItemList= new ArrayList<>();
                //走的是更新配件库价格
                Map<String,BigDecimal> updateMap = respVO.getRepairWaresList().stream().collect(Collectors.toMap(RepairWares::getId,RepairWares::getPrice));
                //更新配件库的价格
                List<RepairWares> updateWaresList = new ArrayList<>();
                //去库里面查需要的配件
                LambdaQueryWrapper<DlTwItem> queryWrapper = new LambdaQueryWrapper<DlTwItem>()
                        .eq(DlTwItem::getTwId, mainId);
                List<DlTwItem> applyList = twItemService.list(queryWrapper);
                if (!applyList.isEmpty()) {
                    //查配件库
                    List<RepairWares> waresList = repairWaresService.listByIds(applyList.stream().map(DlTwItem::getWaresId).collect(Collectors.toList()));
                    Map<String, RepairWares> waresMap = waresList.stream().collect(Collectors.toMap(RepairWares::getId, Function.identity()));
                    //组装工单子表数据
                    for (DlTwItem item : applyList) {
                        DlRepairTitem repairTitem = new DlRepairTitem();
                        repairTitem.setTicketId(ticketMainId);
                        repairTitem.setItemCount(item.getWaresCount());
                        repairTitem.setItemName(item.getWaresName());
                        repairTitem.setItemUnit(waresMap.get(item.getWaresId()).getUnit());
                        //取前端传过来的销售价格
                        repairTitem.setItemPrice(updateMap.get(item.getId()));
                        //默认不打折为1
                        repairTitem.setItemDiscount(new BigDecimal(1));
                        repairTitem.setItemMoney(new BigDecimal(repairTitem.getItemCount()).multiply(repairTitem.getItemPrice()));
                        //类型是配件
                        repairTitem.setItemType("02");
                        repairTitem.setPartId(item.getWaresId());
                        repairTitem.setItemStatus(TicketsItemStatusEnum.WAITING_RECEIVE.getCode());
                        repairItemList.add(repairTitem);
                        //组装配件库更新价格
                        RepairWares update = new RepairWares();
                        update.setId(item.getWaresId());
                        update.setPrice(updateMap.get(item.getId()));
                        updateWaresList.add(update);
                    }
                }
                if(!updateWaresList.isEmpty()){
                    repairWaresService.updateBatchById(updateWaresList);
                }
            }
            // 更新维修工单子表----需要合并相同的配件，故修改
            // 先查维修工单的子表中的配件相关的信息
            List<DlRepairTitem> oldTitem = repairTitemService.list(new LambdaQueryWrapper<DlRepairTitem>().and(i -> i.eq(DlRepairTitem::getTicketId, ticketMainId).eq(DlRepairTitem::getItemType, "02")));
            // 过滤出新申请的配件里面有没有已经存在于工单子表的
            List<String> waresIds = oldTitem.stream().map(DlRepairTitem::getPartId).collect(Collectors.toList());
            List<DlRepairTitem> already = repairItemList.stream().filter(item -> waresIds.contains(item.getPartId())).collect(Collectors.toList());
            // 更新已经存在的配件
            if (CollectionUtil.isNotEmpty(already)) {
                List<DlRepairTitem> updateItems = new ArrayList<>();
                already.forEach(item -> {
                    DlRepairTitem titem = oldTitem.stream().filter(i -> i.getPartId().equals(item.getPartId())).findFirst().orElse(null);
                    if (titem != null) {
                        DlRepairTitem newItem = new DlRepairTitem();
                        newItem.setId(titem.getId());
                        newItem.setItemCount(titem.getItemCount() + item.getItemCount());
                        // 如果设置了折扣就用，没有就是1
                        BigDecimal itemDiscount = titem.getItemDiscount() == null ? new BigDecimal(1) : titem.getItemDiscount();
                        // titem取价格、newItem取数量
                        newItem.setItemMoney(titem.getItemPrice().multiply(BigDecimal.valueOf(newItem.getItemCount())).multiply(itemDiscount));
                        updateItems.add(newItem);
                    }
                });
                if (CollectionUtil.isNotEmpty(updateItems)) {
                    repairTitemService.updateBatchById(updateItems);
                }
            }
            // 新增维修工单中没有的配件
            List<DlRepairTitem> newItems = repairItemList.stream().filter(item -> !waresIds.contains(item.getPartId())).collect(Collectors.toList());
            newItems.forEach(item -> {
                // 主表id
                item.setTicketId(ticketMainId);
                // 类型为配件
                item.setItemType("02");
                // 状态为未领料
                item.setItemStatus(TicketsItemStatusEnum.WAITING_RECEIVE.getCode());
            });
            repairTitemService.saveBatch(newItems);

            // 重新计算工单
            boolean flag = repairTicketsService.computeTicket(ticketMainId);
            if (!flag) {
                throw exception0(500, "系统异常");
            }

            // 更新仓库
            if (CollectionUtil.isNotEmpty(repairItemList)){
                List<RepairWares> updateWares = repairItemList.stream().map(item -> {
                    RepairWares wares = new RepairWares();
                    wares.setId(item.getPartId());
                    wares.setPrice(item.getItemPrice());
                    return wares;
                }).collect(Collectors.toList());
                repairWaresService.updateBatchById(updateWares);
            }

            // 发送通过的消息给仓库
            RoleReqDTO roleInfo = roleApi.getRoleInfo(RepairRoleEnum.WAREHOUSE.getCode());
            List<Long> ids = permissionApi.getUserIdByRoleId(roleInfo.getId());
            if (CollectionUtil.isNotEmpty(ids)) {
                ids.forEach(id -> repairWorkerService.sentMessage(id, "您有新的配件申请单需要处理"));
            }
        }
        // 如果是驳回，通知维修工
        if (status.equals("05")) {
            // 发送没有通过的消息给员工
            DlTicketWares ticketWares = baseMapper.selectById(respVO.getId());
            repairWorkerService.sentMessage(ticketWares.getRepairId(), "您的配件申请单被驳回了");
        }
        //插入记录
        repairRecordsService.saveRepairRecord(respVO.getTicketId(),null,RecordTypeEnum.SPPJSQD.getCode(),"审批配件申请单",null);
    }

    /**
     * 仓库通知领料、退料
     *
     * @param respVO 请求对象
     * @author 小李
     * @date 20:45 2024/10/16
     **/
    @Override
    @DSTransactional
    public void passTicketWares(DlTicketWaresRespVO respVO) {
        respVO.getRepairSo().setSoTime(new Date());
        // 把单据类型先取出来（02是领料，04是退料）
        String type = respVO.getRepairSo().getSoType();
        // 查工单子表中的配件信息
        List<DlRepairTitem> list = repairTitemService.list(new LambdaQueryWrapper<DlRepairTitem>().and(i -> {
                    i.eq(DlRepairTitem::getTicketId, respVO.getTicketId())
                            .in(DlRepairTitem::getPartId, respVO.getRepairSois()
                                    .stream()
                                    .map(DlRepairSoi::getGoodsId)
                                    .collect(Collectors.toList()));
                })
        );
        // 计算总价 （通知领料的数量可能和请求的不一样，所以需要这样计算）
        BigDecimal reduce = list.stream()
                /*
                    item：维修工单子表中的每一个配件
                    map中是找到与item对应的领料单子表的配件，记soi
                    将item的价格设置给soi的价格
                 */
                .map(item -> {
                    DlRepairSoi repairSoi = respVO.getRepairSois().stream()
                            .filter(i -> i.getGoodsId().equals(item.getPartId())).findFirst()
                            .orElse(null);
                    if (repairSoi != null) {
                        repairSoi.setGoodsPrice(item.getItemPrice());
                    }
                    return repairSoi;
                })
                .filter(Objects::nonNull)
                // 计算soi的价格
                .map(i -> new BigDecimal(i.getGoodsCount()).multiply(i.getGoodsPrice()))
                // 计算总价
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 生成领料单、退料单
        respVO.getRepairSo().setTotalPrice(reduce);
        respVO.getRepairSo().setItemCount(respVO.getRepairSois().stream().mapToInt(DlRepairSoi::getGoodsCount).sum());
        respVO.getRepairSo().setTwId(respVO.getId());
        repairSoService.save(respVO.getRepairSo());
        // 生成领料单、退料单子表
        respVO.getRepairSois().forEach(item -> {
            item.setSoId(respVO.getRepairSo().getId());
        });
        repairSoiService.saveBatch(respVO.getRepairSois());
        // 更新配件申请子表
        // 分领料和退料
        // 先取出要操作的子表数据
        List<DlTwItem> oldData = twItemService.list(new LambdaQueryWrapper<DlTwItem>().and(item -> {
            item.eq(DlTwItem::getTwId, respVO.getRepairSo().getTwId())
                    .in(DlTwItem::getWaresId, respVO.getRepairSois().stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList()));
        }));
        // 要操作的库存数据
        List<RepairWares> wares = repairWaresService.list(new LambdaQueryWrapper<RepairWares>().in(RepairWares::getId, respVO.getRepairSois().stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList())));
        if (type.equals("02")) { // 领料
            // 构造新数据
            List<DlTwItem> newData = oldData.stream().map(item -> {
                DlTwItem dlTwItem = new DlTwItem();
                dlTwItem.setId(item.getId());
                respVO.getRepairSois().stream()
                        .filter(i -> i.getGoodsId().equals(item.getWaresId()))
                        .findFirst()
                        .ifPresent(repairSoi -> {
                            // 先取该申请配件的已领料数量，如过是第一次就是0
                            Integer waresAlreadyCount = item.getWaresAlreadyCount() == null ? 0 : item.getWaresAlreadyCount();
                            // 取本来的已领取数量+本次要领取的数量
                            dlTwItem.setWaresAlreadyCount(repairSoi.getGoodsCount() + waresAlreadyCount);
                            // 可领取数量就是申请数量-已领料数量
                            // item是操作的申请配件的数量，dlTwItem取最新的已领取数量
                            dlTwItem.setWaresCouldCount(item.getWaresCount() - dlTwItem.getWaresAlreadyCount());
//                            dlTwItem.setWaresStatus(repairSoi.getGoodsCount().equals(item.getWaresCount()) ? "04" : item.getWaresStatus());
                            // 如果已领取数量等于申请数量，那这个配件就是领料完了，为01已领料，反之不变
                            dlTwItem.setWaresStatus(item.getWaresCount().equals(dlTwItem.getWaresAlreadyCount()) ? "01" : item.getWaresStatus());
                        });
                return dlTwItem;
            }).collect(Collectors.toList());
            twItemService.updateBatchById(newData);

            // 同时操作库存扣减
            // 构造新数据
            List<RepairWares> newWares = wares.stream().map(item -> {
                RepairWares ware = new RepairWares();
                ware.setId(item.getId());
                respVO.getRepairSois().stream().filter(i -> i.getGoodsId().equals(item.getId())).findFirst().ifPresent(repairSoi -> ware.setStock(item.getStock().subtract(BigDecimal.valueOf(repairSoi.getGoodsCount()))));
                return ware;
            }).collect(Collectors.toList());
            // 更新库存
            repairWaresService.updateBatchById(newWares);
        } else { // 退料
            // 构造新数据
            List<DlTwItem> newData = oldData.stream().map(item -> {
                DlTwItem dlTwItem = new DlTwItem();
                dlTwItem.setId(item.getId());
                respVO.getRepairSois().stream()
                        .filter(i -> i.getGoodsId().equals(item.getWaresId()))
                        .findFirst()
                        .ifPresent(repairSoi -> {
                            // 取本来的已领取数量-本次要退料的数量
                            dlTwItem.setWaresAlreadyCount(item.getWaresAlreadyCount() - repairSoi.getGoodsCount());
                            // 可领取数量就是上次的可领取+退料数量
                            // item是操作的可领取数量，repairSoi是取本次退料的数量
                            dlTwItem.setWaresCouldCount(item.getWaresCouldCount() + repairSoi.getGoodsCount());
//                            dlTwItem.setWaresStatus(repairSoi.getGoodsCount().equals(item.getWaresCount()) ? "04" : item.getWaresStatus());
                            // 如果可领料数量等于申请数量，那这个配件就是退料完了，为03已退料，反之不变
                            dlTwItem.setWaresStatus(item.getWaresCount().equals(dlTwItem.getWaresCouldCount()) ? "03" : "02");
                        });
                return dlTwItem;
            }).collect(Collectors.toList());
            twItemService.updateBatchById(newData);

            // 同时操作库存新增
            // 构造新数据
            List<RepairWares> newWares = wares.stream().map(item -> {
                RepairWares ware = new RepairWares();
                ware.setId(item.getId());
                respVO.getRepairSois().stream().filter(i -> i.getGoodsId().equals(item.getId())).findFirst().ifPresent(repairSoi -> ware.setStock(item.getStock().add(BigDecimal.valueOf(repairSoi.getGoodsCount()))));
                return ware;
            }).collect(Collectors.toList());
            // 更新库存
            repairWaresService.updateBatchById(newWares);
        }
//        /*
//           同理，通知领料的数量可能与实际需要的数量不一致，需要重新计算状态
//         */
//        // 先查老数据，领料才需要更新
//        if (type.equals("02")) {
//            List<DlTwItem> oldData = twItemService.list(new LambdaQueryWrapper<DlTwItem>().in(DlTwItem::getId, respVO.getItems().stream().map(DlTwItem::getId).collect(Collectors.toList())));
//            // 构造新数据
//            List<DlTwItem> newData = oldData.stream().map(item -> {
//                DlTwItem dlTwItem = new DlTwItem();
//                dlTwItem.setId(item.getId());
//                respVO.getRepairSois().stream()
//                        .filter(i -> i.getGoodsId().equals(item.getWaresId()))
//                        .findFirst()
//                        .ifPresent(repairSoi -> {
//                            dlTwItem.setWaresCouldCount(repairSoi.getGoodsCount());
//                            dlTwItem.setWaresStatus(repairSoi.getGoodsCount().equals(item.getWaresCount()) ? "04" : item.getWaresStatus());
//                        });
//                return dlTwItem;
//            }).collect(Collectors.toList());
//            twItemService.updateBatchById(newData);
//        }
        //插入记录
        //最后记录操作日志--创建工单
        repairRecordsService.saveRepairRecord(respVO.getTicketId(), null, "02".equals(type)?RecordTypeEnum.TZLL.getCode():RecordTypeEnum.TZTL.getCode(),
                "02".equals(type)?"通知领料":"通知退料", null);
        // 通知维修工
        // 查维修工的userId
        repairWorkerService.sentMessage(respVO.getRepairId(), type.equals("02") ? "您有新的领料单需要确认" : "您有新的退料单需要确认");
    }

    /**
     * 员工确认领料
     *
     * @param respVO 请求对象
     * @author 小李
     * @date 22:07 2024/10/16 应该是弃用了，但不确定，先不删
     **/
    @Override
    @DSTransactional
    public void repairPassTicketWares(DlTicketWaresRespVO respVO) {
        // 更新领料申请子表
        twItemService.updateBatchById(respVO.getItems());
        // 更新领料申请表
        // 判断是全部完成完成部分完成
        List<DlTwItem> list = twItemService.list(new LambdaQueryWrapper<DlTwItem>().eq(DlTwItem::getTwId, respVO.getId()));
        List<DlTwItem> list1 = list.stream().filter(item -> item.getWaresStatus().equals(respVO.getType().equals("01") ? "01" : "03")).collect(Collectors.toList());
        respVO.setStatus(list1.size() == list.size() ? "03" : "04");
        baseMapper.updateById(respVO);
        // 操作库存
        list.forEach(item -> {
            repairWaresService.update(new LambdaUpdateWrapper<RepairWares>()
                    .setSql("stock = stock" + (respVO.getType().equals("01") ? "-" : "+") + item.getWaresCount())
                    .eq(RepairWares::getId, item.getWaresId())
            );
        });
    }

    /**
     * 仓库确认退料
     *
     * @param respVO 请求对象
     * @author 小李
     * @date 22:03 2024/10/17 应该是弃用了，但不确定，先不删
     **/
    @Override
    public void passBackTicketWares(DlTicketWaresRespVO respVO) {
        // 更新申请单子表状态
        twItemService.updateBatchById(respVO.getItems());
    }

    /**
     * 创建配件申请单
     *
     * @param respVO 请求体
     * @author vinjor-M
     * @date 14:48 2024/10/22
     **/
    @Override
    public void createApplyOrder(DlTicketWaresRespVO respVO) {
        //默认待审核
        respVO.setStatus("01");
        //查维修单信息
        DlRepairTickets tickets = repairTicketsService.getById(respVO.getTicketId());
        respVO.setLicenseNumber(tickets.getCarNo());
        respVO.setAdviserId(Long.valueOf(tickets.getAdviserId()));
        respVO.setAdviserName(tickets.getAdviserName());
        this.save(respVO);
        if (!respVO.getItems().isEmpty()) {
            List<DlTwItem> list = respVO.getItems().stream().map(dlTwItem -> dlTwItem.setTwId(respVO.getId())).collect(Collectors.toList());
            twItemService.saveBatch(list);
        }

    }

    /**
     * 维修工的角度查提交的配件申请单\待确认领料单\待确认退料单 待处理数量
     *
     * @author vinjor-M
     * @date 15:38 2024/10/22
     **/
    @Override
    public Map<String, Integer> getWorkerTodo() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<DlTicketWares> queryWrapper = new LambdaQueryWrapper<DlTicketWares>()
                .eq(DlTicketWares::getRepairId, loginUser.getId())
                .eq(DlTicketWares::getType, "01");
        List<DlTicketWares> list = this.list(queryWrapper);
        Map<String, Integer> rtnMap = new HashMap<>();
        //所有提交的
        Integer submitNum = list.size();
        //已通过的
        Integer allowNum = 0;
        //未通过的
        Integer noAllowNum = 0;
        //待确认领料单
        Integer waitingReceiveNum = dlRepairSoMapper.selectCountNum("02", loginUser.getId(), SoStatusEnum.TO_BE_PICKED.getCode());
        //待确认退料单
        Integer waitingBackNum = dlRepairSoMapper.selectCountNum("04", loginUser.getId(), SoStatusEnum.TO_BE_RETURNED.getCode());
        for (DlTicketWares wares : list) {
            if ("02".equals(wares.getStatus())) {
                //已通过
                allowNum++;
            } else if ("05".equals(wares.getStatus())) {
                //被驳回
                noAllowNum++;
            }
        }
        rtnMap.put("submitNum", submitNum);
        rtnMap.put("allowNum", allowNum);
        rtnMap.put("noAllowNum", noAllowNum);
        rtnMap.put("waitingReceiveNum", waitingReceiveNum);
        rtnMap.put("waitingBackNum", waitingBackNum);
        return rtnMap;
    }

}




