package com.junmp.jyzb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.junmpProcess.dto.StartProcessInstanceDTO;
import com.junmp.junmpProcess.service.IFlowInstanceService;
import com.junmp.jyzb.Repository.BusFormRepository;
import com.junmp.jyzb.api.bean.dto.BusFormDto;
import com.junmp.jyzb.api.bean.query.BussinessOrderDetialReq;
import com.junmp.jyzb.api.bean.query.QueryBusFormReq;
import com.junmp.jyzb.api.bean.req.UpdateBusFormReq;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.InventoryExceptionEnum;
import com.junmp.jyzb.api.exception.enums.OrderExceptionEnum;
import com.junmp.jyzb.api.exception.enums.OrgExceptionEnum;
import com.junmp.jyzb.cache.MsgRedisCache;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.mapper.InventorySummaryMapper;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.mapper.BusFormMapper;
import com.junmp.jyzb.utils.BusinessUtil;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.auth.api.bean.login.LoginUser;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import com.junmp.v2.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import com.junmp.v2.sys.user.service.SysUserOrgService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author lxh专属坐骑
* @description 针对表【base_bus_form】的数据库操作Service实现
* @createDate 2023-09-25 10:16:46
*/
@Service
public class BusFormServiceImpl extends ServiceImpl<BusFormMapper, BusForm> implements BusFormService{
    @Resource
    public StocktakeService stocktakeService;
    @Resource
    private MsgRedisCache redisCache;
    @Resource
    private IFlowInstanceService FlowInstanceService;
    @Resource
    private MessageApi messageApi;
    @Resource
    private SysUserOrgService sysUserOrgService;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    protected TaskService taskService;

    @Resource
    private BusFormRepository busFormRepository;
    @Resource
    private BusFormMapper busFormMapper;

    public Object addEs() {
        List<BusForm> esDto=this.list();
        return busFormRepository.saveAll(esDto);
    }
    /**
     * 创建业务单
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String AddBussinessOrder(UpdateBusFormReq req) {
        //判断inventorySummary表中是否有这个装备的已在审核中的数量，如果数量为null或者为0，则表示可以进行审批
        if (req.getBussinessType().equals("remove") && ObjectUtil.isNotEmpty(req.getProcessDefinitionId())){
            Boolean aBoolean = addOrRevokeAgentBrokenNum(req,true);
        }

        BusForm busForm1=null;
        if (ObjectUtil.isNotNull(req.getId()) && !req.getId().trim().isEmpty()){

            busForm1 = this.getById(req.getId());
        }
        if (busForm1!=null) {
            //判断该单据是否可以进行修改(如果审核中则不允许修改)\
            if (ObjectUtil.isNotNull(busForm1.getExamineState()) && busForm1.getExamineState().equals("working")){
                throw new ServiceException(OrderExceptionEnum.ORDER_CAN_NOT_UPDATE);
            }
        }

        if (ObjectUtil.isEmpty(req.getProcessDefinitionId()))
        {
            req.setExamineState("none");
        }
        else
        {
            req.setExamineState("working");
        }


        BusForm busForm = new BusForm();
        BeanUtil.copyProperties(req,busForm);
        //设置业务单的使用次数（默认是出库一次，入库一次）
        busForm.setOrderCurrentState("bothuseing");
        busForm.setOrderLastState("bothuseing");
        if (ObjectUtil.isNull(req.getId())){
            String id= UUID.randomUUID().toString();
            busForm.setId(id);
            //设置单据号（调拨的单号根据和登录人员的组织机构id有关）
            //根据userId去查询组织机构id
            OrderNum orderNum=new OrderNum();
            if (req.getBussinessType().equals("allocate")){
                if (req.getStartOrgId() == req.getOrgId()){
                    orderNum = stocktakeService.setOrderCode(req.getBussinessType(), req.getStartOrgId());
                } else {
                    orderNum = stocktakeService.setOrderCode(req.getBussinessType(), req.getEndOrgId());
                }
            }else {
                orderNum = stocktakeService.setOrderCode(req.getBussinessType(), req.getOrgId());
            }
            String codeValue=String.format("%04d",orderNum.getNum());
            busForm.setBussinessCode(orderNum.getBussinessType()+orderNum.getYear()+
                    String.format("%02d",LocalDateTime.now().getMonth().getValue())+
                    String.format("%02d",LocalDateTime.now().getDayOfMonth())+codeValue);

            busForm.setCreateTime(DateTimeUtil.getCurrentDateTime());
        }
        String processInstanceId=null;
        //执行工作流
        if (req.getExamineState().equals("working"))
        {
            StartProcessInstanceDTO startProcessInstanceDTO = setParams(req,busForm);
            processInstanceId= FlowInstanceService.startProcessInstanceById(startProcessInstanceDTO);

        }
        //判断当前审核是否跳过
        if (processInstanceId!=null && processInstanceId.substring(0,4).equals("skip") ){
            String substring = processInstanceId.substring(4);
            busForm.setProcessId(substring);
            if (busForm1!=null) {
                updateById(busForm);
            } else {
                //保存
                this.save(busForm);
            }
            Task currentTask = taskService.createTaskQuery().processInstanceId(substring).singleResult();
            // 直接完成当前任务
            taskService.complete(currentTask.getId());
        }else if (processInstanceId!=null){
            busForm.setProcessId(processInstanceId);

            String assigns= FlowInstanceService.GetNextAssign(processInstanceId);//这里需要手动更新审核人信息
            busForm.setCurrentAssign(assigns);
            if (busForm1!=null) {
                //已经是一个草稿，在点击提交的时候只需要更新即可，因为数据库中已经存在该单据
                updateById(busForm);
            } else {
                //保存
                this.save(busForm);
            }
        }else {
            if (busForm1!=null) {
                //已经是一个草稿，在点击提交的时候只需要更新即可，因为数据库中已经存在该单据
                updateById(busForm);
            } else {
                //保存
                this.save(busForm);
            }
        }
        busFormRepository.save(busForm);
        String objJson= redisCache.get(busForm.getProcessId());
        redisCache.remove(busForm.getProcessId());
        List<MessageSendReq> msgs= JSONObject.parseArray(objJson,MessageSendReq.class);
        if (CollectionUtil.isNotEmpty(msgs)){
            msgs.forEach(msg->
                    {
                        messageApi.sendMessage(msg);
                    }

            );
        }

        return busForm.getId();
    }

    private StartProcessInstanceDTO setParams(UpdateBusFormReq req,BusForm busForm){
        StartProcessInstanceDTO startProcessInstanceDTO=new StartProcessInstanceDTO();
        startProcessInstanceDTO.setProcessDefinitionId(req.getProcessDefinitionId());
        startProcessInstanceDTO.setOrderId(busForm.getId());
        startProcessInstanceDTO.setTypeOrder("bussinessOrder");
        startProcessInstanceDTO.setUserId(req.getApplyUserId());
        startProcessInstanceDTO.setBussinessType(req.getBussinessType());
        //设置领用人
        startProcessInstanceDTO.setUserName(ObjectUtil.isNotNull(req.getReturnUser())?req.getReturnUser():null);
        //发物单位和收物单位
        switch (req.getBussinessType()){
            case "use":
                startProcessInstanceDTO.setStartOrgName(req.getOrgName());
                break;
            case "purchase":
                startProcessInstanceDTO.setStartOrgName(req.getSupplierName());
                startProcessInstanceDTO.setEndOrgName(req.getOrgName());
                break;
            case "allocate":
                startProcessInstanceDTO.setStartOrgName(req.getStartOrgName());
                startProcessInstanceDTO.setEndOrgName(req.getEndOrgName());
                break;
            case "repair":
            case "destruction":
                startProcessInstanceDTO.setStartOrgName(req.getOrgName());
                startProcessInstanceDTO.setEndOrgName(req.getSupplierName());
                break;
            case "remove":
                startProcessInstanceDTO.setStartOrgName(req.getOrgName());
                startProcessInstanceDTO.setEndOrgName(req.getOrgName());
                break;
        }
        //装备列表
        startProcessInstanceDTO.setInvList(req.getInvList());
        //业务类型
        startProcessInstanceDTO.setType("busFormDto");

//            Object A= JSON.toJSONString(req);
        Object A= JSON.toJSONString(req, SerializerFeature.WriteDateUseDateFormat);
        JSONObject jsonObject = JSON.parseObject(A.toString());

        startProcessInstanceDTO.setFormData(jsonObject);
        return startProcessInstanceDTO;
    }

    //在提交审核或者保存草稿的时候判断申请报废数+审核中数量+报废区数量是否等于在库数，如果大于则报错
    //flag表示一个标识，如果是提交业务单那么flag=true，如果是审核拒绝，那么flag就为false
    public boolean addOrRevokeAgentBrokenNum(UpdateBusFormReq req,boolean flag){
        List<BussinessOrderDetialReq> list = JSON.parseArray(req.getDetailList(), BussinessOrderDetialReq.class);
        List<Object[]> searchItem=new ArrayList<>();
        for (BussinessOrderDetialReq detialReq:list) {
            //我先去数据库查询summary表中的数据
            Object[] item=new Object[]{req.getOrgId(),detialReq.getLocationId(),detialReq.getTypeId(),detialReq.getSizeId(),detialReq.getPrice()};
            searchItem.add(item);
        }
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
        String msg="";
        for (BussinessOrderDetialReq detialReq:list) {
            for (InventorySummary is:inventorySummaryList) {
                if (ObjectUtil.isNull(is.getAgentBrokenNum())){
                    is.setAgentBrokenNum(0);
                }
                if (detialReq.getLocationId().equals(is.getLocationId()) && detialReq.getTypeId().equals(is.getTypeId())
                        && detialReq.getSizeId().equals(is.getSizeId()) && detialReq.getPrice().compareTo(is.getUnitPrice())==0){
                    if (flag){
                        //判断审核中的数量是否为0，如果为0 ，那么直接进行添加，如果不为0，则需要判断审核中的数量加申请报废的数量是否超过可以报废的数量
                        //如果超过那么则直接进行报错提醒
                        if (detialReq.getPlanNum()+is.getAgentBrokenNum()<=is.getStockNumber()){
                            //将库存的审核中的报废数量根据单据重新进行计算
                            is.setAgentBrokenNum(is.getAgentBrokenNum()+detialReq.getPlanNum());
                        }else {
                            msg=msg+"装备：" +detialReq.getTypeName()+"号型："+detialReq.getSizeName()+"已存在审核最大可报废数量;";
                        }
                    }else {
                        //直接将在审核中的数量修改为审核之前的状态
                        is.setAgentBrokenNum(is.getAgentBrokenNum()-detialReq.getPlanNum());
                    }

                }
                break;
            }

        }
        if (!msg.trim().isEmpty()){
            throw new JYZBAppException(InventoryExceptionEnum.EQUIPMENT_NOT_EXIST, msg);
        }
        return inventorySummaryService.updateBatchById(inventorySummaryList);

    }



    @Override
    public Object showOrderByBusOrderId(QueryBusFormReq req) {
        List<BusFormDto> busFormDtos = busFormMapper.showOrderByBusOrderId(req.getId());
        Map<String,Object> map=new HashMap<>();
        if (busFormDtos.size()>1){
            for (BusFormDto busFormDto:busFormDtos) {
                if (ObjectUtil.isNotNull(busFormDto.getOutAndInState()) && busFormDto.getOutAndInState().equals("in")){
                    if (map.containsKey("busForm")) {
                        Object busForm = map.get("busForm");
                        BusFormDto busForm1 = (BusFormDto) busForm;
                        busForm1.setInOrderMainId(busFormDto.getOrderMainId());
                        map.put("busForm",busForm1);
                    }else {
                        busFormDto.setInOrderMainId(busFormDto.getOrderMainId());
                        busFormDto.setOrderMainId(null);
                        map.put("busForm",busFormDto);
                    }

                }else if (ObjectUtil.isNotNull(busFormDto.getOutAndInState()) && busFormDto.getOutAndInState().equals("out")){
                    if (map.containsKey("busForm")) {
                        Object busForm = map.get("busForm");
                        BusFormDto busForm1 = (BusFormDto) busForm;
                        busForm1.setOutOrderMainId(busFormDto.getOrderMainId());
                        map.put("busForm",busForm1);

                    }else {
                        busFormDto.setOutOrderMainId(busFormDto.getOrderMainId());
                        map.put("busForm",busFormDto);
                    }

                }
            }
        }else {
            map.put("busForm",busFormDtos.get(0));
        }


        return map.get("busForm");
    }


    /**
     * 查询业务单，（可以根据业务单进行修改）
     * @param
     * @return
     */
    @Override
    public PageResult<BusForm> showBussinessOrder(QueryBusFormReq req) {
        //(如果传其他不是数据库字段参数或者排序规则不是deac或者asc可能会出现错误)
        if (ObjectUtil.isNotNull(req.getColumn()) && !req.getColumn().trim().isEmpty() &&
                (req.getOrder().equalsIgnoreCase("asc")|| req.getOrder().equalsIgnoreCase("desc")) &&
                ObjectUtil.isNotNull(req.getOrder()) && !req.getOrder().trim().isEmpty()) {
            //修改字段，和数据库字段进行统一
            req.setColumn(req.getColumn().replaceAll("[A-Z]", "_$0").toLowerCase());
            req.setOrder(req.getOrder().toLowerCase());
        }
        LambdaQueryWrapper<BusForm> eq = createWrapper(req);
        Page<BusForm> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        List<BusForm> records = page.getRecords();
        int size = records.size();
        //是否创建创建空的数据返回前端
        if(req.getIsCreateNullDate()==null || req.getIsCreateNullDate()){
            Class<BusForm> busForm=BusForm.class;
            List<BusForm> nullData = BusinessUtil.createNullData((long)size, req.getPageNo(), req.getPageSize(), busForm);
            records.addAll(nullData);
        }
        return PageResultFactory.createPageResult(page);
    }


    //根据调拨单，一键生成采购单
//    @Override
//    public List<GeneratePurchaseQuicklyDto> GeneratePurchaseQuickly(GeneratePurchaseQuicklyReq req) {
//        //先把所有发物单位是自己的业务单全部查询出来，然后一一进行比较到底那个是前端传递的数据
////        List<BusForm> list = list(new LambdaQueryWrapper<BusForm>()
////                .eq(BusForm::getOrgId, req.getOrgId())
////                .eq(BusForm::getBussinessType, req.getBussinessType()));
//
//        //将所有调拨单中的装备添加到totalList,之后进行去重并且相应数量相加
//        List<BussinessOrderDetialReq> totalList=new ArrayList<>();
//        //将所有调拨单获取
//        List<UpdateBusFormReq> busFormList = req.getBusFormList();
//        for (UpdateBusFormReq updateBusFormReq:busFormList) {
//            String detailList = updateBusFormReq.getDetailList();
//            List<BussinessOrderDetialReq> list = JSONObject.parseArray(detailList, BussinessOrderDetialReq.class);
//            totalList.addAll(list);
//        }
//        //newList用来去重，把相同size和type的数量进行相加
//        List<BussinessOrderDetialReq> newList=new ArrayList<>();
//        for (BussinessOrderDetialReq item :totalList) {
//            boolean found=false;
//            if (newList.size()==0){
//                newList.add(item);
//                continue;
//            }
//            for (BussinessOrderDetialReq listItem:newList) {
//                if (listItem.getSizeId().equals(item.getSizeId()) && listItem.getTypeId().equals(item.getTypeId())) {
//                    // 如果存在匹配的元素，则更新 num 值
//                    listItem.setPlanNum(listItem.getPlanNum() + item.getPlanNum());
//                    found = true;
//                    break;
//                }
//            }
//            if (!found){
//                newList.add(item);
//            }
//        }
//        //创建list，返回给前端（只返回库存不足的装备和数量）
//        List<GeneratePurchaseQuicklyDto> returnList=new ArrayList<>();
//        //查询库存数量（将该组织机构下面的所有类型和号型的数量查询出来）
//        List<InventorySummary> sumList = inventorySummaryMapper.selectByEqs(req.getOrgId());
//        for (BussinessOrderDetialReq bussinessOrderDetial:newList) {
//            boolean flag=false;
//            for (InventorySummary inventorySummary:sumList) {
//                if (bussinessOrderDetial.getSizeId().equals(inventorySummary.getSizeId())
//                        && bussinessOrderDetial.getTypeId().equals(inventorySummary.getSizeId())){
//                    //判断两个数量谁打谁小
//                    if (bussinessOrderDetial.getPlanNum()-inventorySummary.getStockNumber()>0){
//                        GeneratePurchaseQuicklyDto generatePurchaseQuicklyDto = new GeneratePurchaseQuicklyDto();
//                        generatePurchaseQuicklyDto.setNumber(bussinessOrderDetial.getPlanNum()-inventorySummary.getStockNumber());
//                        generatePurchaseQuicklyDto.setSizeId(bussinessOrderDetial.getSizeId());
//                        generatePurchaseQuicklyDto.setSizeName(bussinessOrderDetial.getSizeName());
//                        generatePurchaseQuicklyDto.setTypeId(bussinessOrderDetial.getTypeId());
//                        generatePurchaseQuicklyDto.setTypeName(bussinessOrderDetial.getTypeName());
//                        returnList.add(generatePurchaseQuicklyDto);
//                    }
//                    flag=true;
//                    break;
//                }
//
//            }
//            if (!flag){
//                GeneratePurchaseQuicklyDto generatePurchaseQuicklyDto = new GeneratePurchaseQuicklyDto();
//                generatePurchaseQuicklyDto.setNumber(bussinessOrderDetial.getPlanNum());
//                generatePurchaseQuicklyDto.setSizeId(bussinessOrderDetial.getSizeId());
//                generatePurchaseQuicklyDto.setSizeName(bussinessOrderDetial.getSizeName());
//                generatePurchaseQuicklyDto.setTypeId(bussinessOrderDetial.getTypeId());
//                generatePurchaseQuicklyDto.setTypeName(bussinessOrderDetial.getTypeName());
//                returnList.add(generatePurchaseQuicklyDto);
//            }
//        }
//
//        return returnList;
//    }

    //更新报废数（inventorySummary,审核通过之后更新）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBrokenResult(BusForm busForm) {
        //获取数量
        String detailList = busForm.getDetailList();
        List<BussinessOrderDetialReq> list = JSON.parseArray(detailList, BussinessOrderDetialReq.class);
        //更新inventory表的表达式
        LambdaUpdateWrapper<Inventory> updateStateWrapper = Wrappers.lambdaUpdate();
        List<Object[]> searchItem=new ArrayList<>();
        for (BussinessOrderDetialReq detialReq:list) {
            //我先去数据库查询summary表中的数据
            Object[] item=new Object[]{busForm.getOrgId(),detialReq.getLocationId(),detialReq.getTypeId(),detialReq.getSizeId(),detialReq.getPrice()};
            searchItem.add(item);

        }
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
        List<InventorySummary> updateSummaryList=new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("组织机构为:"+busForm.getOrgId()+"单号为:"+busForm.getBussinessCode()+"的报废业务单将报废数量进行修改:");
        boolean a=false;
        for (BussinessOrderDetialReq detialReq:list) {
            for (InventorySummary is:inventorySummaryList) {
                if (detialReq.getLocationId().equals(is.getLocationId()) && detialReq.getTypeId().equals(is.getTypeId())
                    && detialReq.getSizeId().equals(is.getSizeId()) && detialReq.getPrice().compareTo(is.getUnitPrice())==0){
                    //如果数量相同则直接将全部在库数的装备表中的该仓库的装备状态全部设置为报废，并且修改库存汇总表中的数据
                    if (detialReq.getPlanNum()+is.getBrokenNumber()==is.getStockNumber()){
                        a=true;
                        //修改装备状态表达式
                        updateStateWrapper.or().eq(Inventory::getOrgId, busForm.getOrgId())
                                .eq(Inventory::getLocationId, detialReq.getLocationId())
                                .eq(Inventory::getTypeId, detialReq.getTypeId())
                                .eq(Inventory::getSizeId, detialReq.getSizeId())
                                .eq(Inventory::getPrice, detialReq.getPrice())
                                .eq(Inventory::getLocationType,1)
                                .eq(Inventory::getLocationState,"in")
                                .set(Inventory::getState, "broken");

                        //将库存的报废数量根据单据重新进行计算
                        Integer brokenNum=detialReq.getPlanNum()+is.getBrokenNumber();
                        stringBuilder.append("装备为"+detialReq.getTypeName()+","+detialReq.getSizeName()+"的报废数量从"+is.getBrokenNumber()+"改成"+brokenNum+",");
                        is.setBrokenNumber(brokenNum);
                        updateSummaryList.add(is);
                    } else if (detialReq.getPlanNum()+detialReq.getBrokenNumber()<detialReq.getStockNumber()){
                        //如果数量不相等，状态不进行修改，只修改库存汇总表中的信息
                        //将库存的报废数量根据单据重新进行计算
                        Integer brokenNum=detialReq.getPlanNum()+is.getBrokenNumber();
                        stringBuilder.append("装备为"+detialReq.getTypeName()+","+detialReq.getSizeName()+"的报废数量从"+is.getBrokenNumber()+"改成"+brokenNum+",");
                        is.setBrokenNumber(brokenNum);
                        updateSummaryList.add(is);
                    }else {
                        throw new ServiceException(InventoryExceptionEnum.INVENTORY_BEYOND_STOCK);
                    }
                    break;
                }

            }
        }
        boolean b=true;
        //改inventory表中的装备状态
        if (a){
            b=inventoryService.update(updateStateWrapper);
        }
        //批量修改inventtorySummary表中的数据
        boolean c=true;
        if (updateSummaryList.size()>0){
            c=inventorySummaryService.updateBatchById(updateSummaryList);
        }
        //创建log记录日志
        String string = stringBuilder.toString();
        string=string.substring(0,string.length()-1);
        OrderLog orderLog = new OrderLog();
        orderLog.setHistoryMsg(string);
        orderLog.setOrgId(busForm.getOrgId());
        orderLog.setBussinessType(busForm.getBussinessType());
        orderLog.setOrderCode(busForm.getBussinessCode());
        orderLog.setOrderId(busForm.getId());
        orderLog.setOrgName(busForm.getOrgName());
        orderLog.setCreateTime(DateTimeUtil.getCurrentDateTime());
        orderLogService.save(orderLog);

        return (b && c);
    }


    private LambdaQueryWrapper<BusForm> createWrapper(QueryBusFormReq req) {
        LambdaQueryWrapper<BusForm> eq = new LambdaQueryWrapper<BusForm>()
                //组织机构
                .eq(ObjectUtil.isNotNull(req.getOrgId()) && !req.getBussinessType().equals("allocate"),BusForm::getOrgId,req.getOrgId())
                .eq(ObjectUtil.isNotNull(req.getProcessId()),BusForm::getProcessId,req.getProcessId())
                //装备名称模糊查询
                .like(ObjectUtil.isNotNull(req.getTypeName()),BusForm::getInvList,req.getTypeName())
                //单号
                .like(ObjectUtil.isNotNull(req.getBussinessCode()),BusForm::getBussinessCode,req.getBussinessCode())
                //领用人
                .like(ObjectUtil.isNotNull(req.getReturnUser()),BusForm::getReturnUser,req.getReturnUser())
                //经办人
                .like(ObjectUtil.isNotNull(req.getAgent()),BusForm::getAgent,req.getAgent())
                //厂商名称
                .like(ObjectUtil.isNotNull(req.getSupplierName()),BusForm::getSupplierName,req.getSupplierName())
                //发物单位
                .like(ObjectUtil.isNotNull(req.getStartOrgName()),BusForm::getStartOrgName,req.getStartOrgName())
                //收物单位
                .like(ObjectUtil.isNotNull(req.getEndOrgName()),BusForm::getEndOrgName,req.getEndOrgName())
                //开始时间
                .ge(ObjectUtil.isNotNull(req.getStartTime()),BusForm::getCreateTime, req.getStartTime())
                //结束时间
                .le(ObjectUtil.isNotNull(req.getEndTime()),BusForm::getCreateTime, req.getEndTime())
                .last("order by " + req.getColumn() + " " + req.getOrder());

        //业务单据审核状态
        if (ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("unaudited")){

            List<String> examineStateList=new ArrayList<>();
            examineStateList.add("none");
            examineStateList.add("working");
            eq.in( BusForm::getExamineState,examineStateList);
        } else if (ObjectUtil.isNotNull(req.getExamineState()) && req.getExamineState().equals("finished")) {
            eq.eq(ObjectUtil.isNotNull(req.getExamineState() ) && !req.getExamineState().trim().isEmpty(), BusForm::getExamineState, req.getExamineState());
        }

        //报废、销毁的业务类型
        if (ObjectUtil.isNotNull(req.getBussinessType()) && req.getBussinessType().equals("both")){
            List<String> bussinessTypeList=new ArrayList<>();
            bussinessTypeList.add("remove");
            bussinessTypeList.add("destruction");
            eq.in( BusForm::getBussinessType,bussinessTypeList);
        }else {
            eq.eq(ObjectUtil.isNotNull(req.getBussinessType()) && !req.getBussinessType().trim().isEmpty(), BusForm::getBussinessType, req.getBussinessType());
        }
        //领用人
        if (ObjectUtil.isNotNull(req.getUserId()) && req.getBussinessType().equals("use")){
            //当前登录人
            eq.eq(BusForm::getReturnUserId,req.getUserId());
        }else {
            LoginUser StartUser= LoginContext.getContext().getLoginUser();
            //当前登录人
            eq.and(wrapper-> wrapper.eq(BusForm::getAgentId,StartUser.getUserId())
                    .or()
                    .like(BusForm::getHistoryAssign,StartUser.getUserId()));
        }
        if (req.getBussinessType().equals("allocate")){
            if (req.getStartOrgId()!=null){
                eq.eq(BusForm::getStartOrgId,req.getStartOrgId());
            }
            if (req.getEndOrgId()!=null){
                eq.eq(BusForm::getEndOrgId,req.getEndOrgId());
            }
            if (req.getStartOrgId()==null && req.getEndOrgId()==null){
                eq.and(wrapper-> wrapper.eq(BusForm::getStartOrgId,req.getOrgId()).or().eq(BusForm::getEndOrgId,req.getOrgId()));
            }
            eq.eq(ObjectUtil.isNotNull(req.getAllocateType()) && !req.getAllocateType().isEmpty(),BusForm::getAllocateType,req.getAllocateType());
        }
        //当前单子状态
        if (ObjectUtil.isNotNull(req.getOrderCurrentState())){
            List<String> orderCurrentStateList=new ArrayList<>();
            if (req.getOrderCurrentState().equals("incoming")){
                orderCurrentStateList.add("incoming");
                orderCurrentStateList.add("bothuseing");
                eq.in( BusForm::getOrderCurrentState,orderCurrentStateList);
            }else if (req.getOrderCurrentState().equals("outgoing")){
                orderCurrentStateList.add("outgoing");
                orderCurrentStateList.add("bothuseing");
                eq.in( BusForm::getOrderCurrentState,orderCurrentStateList);
            }
        }

        return eq;
    }
}




