package com.jeeplus.pubmodules.collect.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.pubmodules.collect.domain.CollectBasic;
import com.jeeplus.pubmodules.collect.domain.CollectBasicsReturn;
import com.jeeplus.pubmodules.collect.domain.CollectBasicsReturnHi;
import com.jeeplus.pubmodules.collect.domain.CollectDetailed;
import com.jeeplus.pubmodules.collect.mapper.CollectBasicMapper;
import com.jeeplus.pubmodules.collect.mapper.CollectBasicsReturnHiMapper;
import com.jeeplus.pubmodules.collect.mapper.CollectBasicsReturnMapper;
import com.jeeplus.pubmodules.collect.mapper.CollectDetailedMapper;
import com.jeeplus.pubmodules.collect.service.dto.CollectDto;
import com.jeeplus.pubmodules.collect.service.dto.WareHouseSummaryDto;
import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OssService;
import com.jeeplus.pubmodules.oss.service.dto.WorkAttachmentDto;
import com.jeeplus.pubmodules.purchase.service.MaterialService;
import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.pubmodules.wareHouse.mapper.WareHouseBasicMapper;
import com.jeeplus.pubmodules.wareHouse.mapper.WareHouseDetailedMapper;
import com.jeeplus.pubmodules.wareHouse.mapper.WareHouseSummaryMapper;
import com.jeeplus.pubmodules.wareHouse.service.dto.WareHouseDto;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jeeplus.utils.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 领用表
 * @author: 王强
 * @create: 2023-01-03 16:24
 **/
@Service
@Transactional
public class CollectService {

    @Resource
    private CollectBasicMapper basicMapper;

    @Resource
    private CollectDetailedMapper detailedMapper;

    @Resource
    private WareHouseSummaryMapper summaryMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

    @Resource
    private WareHouseDetailedMapper wareHouseDetailedMapper;

    @Resource
    private WareHouseBasicMapper wareHouseBasicMapper;

    @Resource
    private IFlowableApi flowTaskService;

    @Resource
    private CollectBasicsReturnMapper returnMapper;

    @Resource
    private CollectBasicsReturnHiMapper returnHiMapper;

//    @Resource
//    private OssService ossService;

    @Resource
    private MaterialService materialService;

    public void updateStatusById(CollectDto dto) {
        basicMapper.updateStatusById(dto.getId(), dto.getStatus());
    }

    public String remove(String id) {
        // 删除基础信息表
        basicMapper.deleteById(id);
        // 删除详情列表 及对应附件信息
        List<CollectDetailed> detailedList = detailedMapper.getByBasicId(id);
        if (null != detailedList){
            detailedList.forEach(de->{
                //附件
                List<WorkAttachmentDto> fileList = detailedMapper.getByAttachmentId(de.getId());
                if ( null != fileList ){
                    fileList.forEach(f->{
                        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(f.getId());
//                        ossServiceMapper.deleteById(f.getId());
                    });
                }
                detailedMapper.deleteById(de.getId());
            });
        }
        // 删除附件信息
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
//        LambdaQueryWrapper<WorkAttachment> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(WorkAttachment::getAttachmentId, id);
//        ossServiceMapper.delete(wrapper);
        return "操作成功";
    }

    /**
     * 发起退回流程
     * @param dto
     * @return
     */
    public String saveReturn(CollectDto dto) {

        if (CollectionUtils.isNotEmpty(dto.getDetailInfos()) && StringUtils.isNotBlank(dto.getId())) {
            for (CollectDetailed detailInfo : dto.getDetailInfos()) {
                if (StringUtils.isNotBlank(detailInfo.getId()) && StringUtils.isNotBlank(detailInfo.getIsReturn())) {
                    detailedMapper.updateReturnFlagById(detailInfo.getId(), detailInfo.getIsReturn()); // 修改退回状态
                }
            }
            String returnId = createReturnData(dto.getId());
            detailedMapper.updateByIdReturn(returnId, dto.getStatusReturn(), SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken ( )).getId(), dto.getReturnCause());
//            ossService.saveOrUpdateFileList(dto.getReturnFiles(), returnId, "collect_return"); // 修改附件信息列表
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((dto.getReturnFiles()));
            String attachmentId = returnId;
            String attachmentFlag = "collect_return";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map); // 修改附件信息列表
            return returnId;
        } else {
            return "";
        }
    }

    /**
     * 退回流程审核同意
     * @param dto
     */
    public String saveReturnAgree(CollectDto dto) {
        // 将数据存储到历史表中
        // 将未修改的数据添加到历史数据表中
        CollectDto byId = this.findById(dto.getId());
        String jsonString = JSON.toJSONString(byId);
        if (ObjectUtil.isNotEmpty(byId) && StringUtils.isNotBlank(byId.getReturnId())) {
            // 清空退回原因
            basicMapper.setCauseEmptyById(byId.getReturnId());
        }
        CollectBasicsReturnHi returnHi = new CollectBasicsReturnHi();
        returnHi.setJsonData(jsonString); // json
        returnHi.setCollectId(dto.getId()); // 领用id
        CollectBasicsReturn collectBasicsReturn = returnMapper.selectOne(new LambdaQueryWrapper<CollectBasicsReturn>().eq(CollectBasicsReturn::getBasicId, dto.getId()));
        if (ObjectUtil.isNotEmpty(collectBasicsReturn) && StringUtils.isNotBlank(collectBasicsReturn.getRequestUser())) {
            returnHi.setReturnUser(collectBasicsReturn.getRequestUser()); // 退回申请人
        }
        List<String> returnGoodsName = new ArrayList<>();
        // 将退回的明细数据删除
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {
            for (CollectDetailed detailInfo : dto.getDetailInfos()) {
                if (StringUtils.isNotBlank(detailInfo.getId()) && StringUtils.isNotBlank(detailInfo.getIsReturn())) {
                    if("1".equals(detailInfo.getIsReturn())) { // 退回状态
                        if (StringUtils.isNotBlank(detailInfo.getCollectNumber())) {
                            // 如果数量不是空的话，将小数点后的0去除
                            BigDecimal value = new BigDecimal(detailInfo.getCollectNumber());
                            BigDecimal noZeros = value.stripTrailingZeros();
                            String resultNum = noZeros.toPlainString();
                            returnGoodsName.add(detailInfo.getGoodsName() + "*" + resultNum);
                        } else {
                            returnGoodsName.add(detailInfo.getGoodsName());
                        }
                        detailedMapper.delete(new LambdaQueryWrapper<CollectDetailed>().eq(CollectDetailed::getId,detailInfo.getId()));
                    }
                }
            }
        }
        String returnGoods = String.join(",", returnGoodsName);
        if (StringUtils.isNotBlank(returnGoods)) {
            returnHi.setReturnGoods(returnGoods); // 退回的数据（字符串展示）
        }
        returnHiMapper.insert(returnHi); // 将数据存储到历史表中
        // 修改退回流程的状态
        detailedMapper.updateStatusByIdReturn(collectBasicsReturn.getId(), dto.getStatusReturn());
        // 删除退回关联附件
//        ossService.remove(new LambdaQueryWrapper<WorkAttachment>().eq(WorkAttachment::getAttachmentId, collectBasicsReturn.getId()));
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(collectBasicsReturn.getId());
        if (ObjectUtil.isNotEmpty(collectBasicsReturn)) {
            return collectBasicsReturn.getId();
        } else {
            return "";
        }
    }

    public void updateStatusByIdReturn(String id, String status) {
        CollectBasicsReturn returnData = returnMapper.selectOne(new LambdaQueryWrapper<CollectBasicsReturn>().eq(CollectBasicsReturn::getBasicId, id));
        if (ObjectUtil.isNotEmpty(returnData) && StringUtils.isNotBlank(returnData.getId())) {
            detailedMapper.updateStatusByIdReturn(returnData.getId(), status); // 修改退回的流程状态
        }
    }

    public String save(CollectDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        synchronized (this) {
            if (StringUtils.isNotEmpty(dto.getId()) && !dto.getId().equals("false")) {
                return update(dto, userDTO);
            } else {
                return add(dto, userDTO);
            }
        }

    }

    public String update(CollectDto dto, UserDTO userDTO) throws Exception {
        // 修改基础信息
        CollectBasic info = new CollectBasic();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateById(userDTO.getId());
        info.setHandledBy(dto.getHandledById());
        info.setUpdateTime(new Date());
        basicMapper.updateById(info);
        // 修改报销详情列表信息
        // 删除原有数据
//        LambdaQueryWrapper<MaterialDetailed> detailWrapper = new LambdaQueryWrapper<>();
//        detailWrapper.eq(MaterialDetailed::getBasicId, dto.getId());
//        detailedMapper.delete(detailWrapper);
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {

            List<String> idList = detailedMapper.getIdByBasicId(info.getId());
            for (CollectDetailed detailInfo : dto.getDetailInfos()) {
                //删除多余的领用详情
                //根据基础表id获取所有的详情表id
                if (null != idList) {
                    if (idList.contains(detailInfo.getId())){
                        idList.remove(detailInfo.getId());
                    }
                }
            }
            if (null != idList & idList.size()>0) {
                idList.forEach(id->{
                    detailedMapper.deleteById(id);
                });
            }

            if (StringUtils.isNotEmpty(dto.getSign())) {

            } else {
                List<String> warnInfoList = new ArrayList<>();
                for (CollectDetailed detailInfo : dto.getDetailInfos()) {

                    CollectDetailed materialDetailed = detailedMapper.selectById(detailInfo.getId());
                    if (StringUtils.isEmpty(detailInfo.getCollectNumber())){
                        detailInfo.setCollectNumber("0");
                    }
                    if ( null == materialDetailed) {
                        // 生成id
                        String detailId = UUID.randomUUID().toString().replace("-", "");
                        detailInfo.setId(detailId);
                        detailInfo.setRecipientAgent(detailInfo.getRecipientAgentId());
                        detailInfo.setCollectType(detailInfo.getCollectTypeId());
                        detailInfo.setCreateById(userDTO.getId());
                        detailInfo.setCreateTime(new Date());
                        detailInfo.setUpdateById(userDTO.getId());
                        detailInfo.setUpdateTime(new Date());
                        detailInfo.setDelFlag(0);
                        // 保存基础表信息主键值
                        detailInfo.setBasicId(dto.getId());
                        //获取该商品对应的库存数据
                        WareHouseDto wareHouseDto = wareHouseBasicMapper.getByTypeAndGoodsName(detailInfo.getGoodsName(), detailInfo.getCollectTypeId());
                        detailInfo.setSurplusNumber(wareHouseDto.getTradeNumber());
                        detailedMapper.insert(detailInfo);
                        // 修改附件信息列表
                        if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
                            materialService.saveFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
                        }
                    } else {
                        //获取该商品对应的库存数据
                        WareHouseDto wareHouseDto = wareHouseBasicMapper.getByTypeAndGoodsName(detailInfo.getGoodsName(), detailInfo.getCollectTypeId());
                        detailInfo.setSurplusNumber(wareHouseDto.getTradeNumber());
                        detailInfo.setRecipientAgent(detailInfo.getRecipientAgentId());
                        detailInfo.setCollectType(detailInfo.getCollectTypeId());
                        detailInfo.setUpdateById(userDTO.getId());
                        detailInfo.setUpdateTime(new Date());
                        detailInfo.setBasicId(dto.getId());
                        detailedMapper.updateById(detailInfo);
                        materialService.updateFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
//                        if (CollectionUtils.isNotEmpty(detailInfo.getFileInfoLost())) {
//                            materialService.updateFiles(detailInfo.getFileInfoLost(), userDTO, detailInfo.getId());
//                        }
                    }

                    //当流程结束的时候 修改入库汇总表的数量
                    if ( StringUtils.isNotEmpty(info.getStatus()) && info.getStatus().equals("5")){
                        //根据商品名称 及 领用类型查询汇总表修改改商品库存数量
                        /*WareHouseSummary summaryInfo = summaryMapper.getInfoByTradeName(detailInfo.getGoodsName(), detailInfo.getCollectType());
                        if (null != summaryInfo) {
                            String num = Double.parseDouble(summaryInfo.getTradeNumber())
                                    - Double.parseDouble(detailInfo.getCollectNumber()) + "";
                            summaryInfo.setTradeNumber(num);
                            summaryMapper.updateById(summaryInfo);
                        }*/
                        //根据商品名称 及 领用类型查询入库表的商品入库数量
                        Double wareHouseNum = summaryMapper.getInfoByTradeName(detailInfo.getGoodsName(), detailInfo.getCollectType());
                        //根据商品名称 及 领用类型查询提醒数量以及是否提醒
                        List<WareHouseDto> byTypeAndTradeName = wareHouseBasicMapper.getByTypeAndTradeName(detailInfo.getGoodsName(), detailInfo.getCollectType());
                        if (null != wareHouseNum) {
                            double num = wareHouseNum - Double.parseDouble(detailInfo.getCollectNumber());
                            detailInfo.setSurplusNumber(wareHouseNum + "");

                            detailedMapper.updateById(detailInfo);

                            // 当 提醒开启 并且 库存数量小于或等于提醒数量 时发起通知
                            // 在Java中 int类型数据的大小比较可以使用双等号， double类型则不能使用双等号来比较大小，如果使用的话得到的结果将永远是不相等，即使两者的精度是相同的也不可以
                            if (CollectionUtil.isNotEmpty(byTypeAndTradeName) && StringUtils.isNotBlank(byTypeAndTradeName.get(0).getWarnNum()) && StringUtils.isNotBlank(byTypeAndTradeName.get(0).getWarnFlag())) {
                                String wareHouseNumString = String.valueOf(wareHouseNum); // wareHouseNum转string的原因是，string转BigDecimal比double转BigDecimal精度更高
                                BigDecimal whnum = new BigDecimal(wareHouseNumString); // 当前库存量
                                BigDecimal warnNum = new BigDecimal(byTypeAndTradeName.get(0).getWarnNum()); // 提醒数量
                                if ("1".equals(byTypeAndTradeName.get(0).getWarnFlag()) && whnum.compareTo(warnNum) <= 0 ) {
                                    warnInfoList.add(detailInfo.getGoodsName());
                                }
                            }
                        }
                    }

                }
                //发起提醒操作
                if (CollectionUtil.isNotEmpty(warnInfoList)) {
                    String warnInfo = String.join("、", warnInfoList);
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String day = format.format(new Date());
                    String title = "管理员发起了 ["+ warnInfo +"] [库存提醒]";
                    //向多个用户发起通知 徐珊、黄丽、杨娟、崇祝燕
                    List<UserDTO> usersInfo = wareHouseDetailedMapper.getUsersInfo();
                    //获取目前领用流程的taskid，根据procInsId去查taskId
                    String uuid = "";
                    if (null != usersInfo) {
                        for (UserDTO userDTO1 : usersInfo) {
                            uuid = UUID.randomUUID().toString();
                            //发送通知
//                                        flowTaskService.add(uuid, title, "", "库存提醒", userDTO.getLoginName(), day,userDTO1.getLoginName(), userDTO1.getId());
                            Map<String ,String > map = new HashMap<>();
                            map.put("taskId",uuid);
                            map.put("title",title);
                            map.put("defId",dto.getId());
                            map.put("taskName","库存提醒");
                            map.put("createUser","管理员");
                            map.put("createTime",day);
                            map.put("noticeName",userDTO1.getLoginName());
                            map.put("noticeId",userDTO1.getId());
                            map.put("createById",userDTO.getId());
                            flowTaskService.add(map);
                        }
                    }
                }
            }

        }
//        basicMapper.updateById(info);
        // 修改附件信息列表
        materialService.updateFiles(dto.getFiles(), userDTO, dto.getId());
//        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
//            materialService.updateFiles(dto.getFiles(), userDTO, dto.getId());
//        }
        return dto.getId();
    }

    public String add(CollectDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE,TokenProvider.getCurrentToken());
        // 保存基础信息表信息
        CollectBasic info = new CollectBasic();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
        info.setCollectNo(no);
        info.setHandledBy(dto.getHandledById());
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        basicMapper.insert(info);
        // 保存详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {
            for (CollectDetailed detailed : dto.getDetailInfos()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                detailed.setId(detailId);
                detailed.setRecipientAgent(detailed.getRecipientAgentId());
                detailed.setCollectType(detailed.getCollectTypeId());
                detailed.setCreateById(userDTO.getId());
                detailed.setCreateTime(new Date());
                detailed.setUpdateById(userDTO.getId());
                detailed.setUpdateTime(new Date());
                detailed.setDelFlag(0);
                // 保存基础表信息主键值
                detailed.setBasicId(id);
                //获取该商品对应的库存数据
                WareHouseDto wareHouseDto = wareHouseBasicMapper.getByTypeAndGoodsName(detailed.getGoodsName(), detailed.getCollectTypeId());
                detailed.setSurplusNumber(wareHouseDto.getTradeNumber());
                //设置当前库存
                detailed.setCurrentInventory(wareHouseDto.getTradeNumber());
                detailedMapper.insert(detailed);
                //保存详情列表附件信息
                if (CollectionUtils.isNotEmpty(detailed.getFileInfoLost())){
                    materialService.saveFiles(detailed.getFileInfoLost(), userDTO, detailId);
                }

            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            materialService.saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }

    public CollectDto findById(String id) {
        CollectDto dto = new CollectDto();
        // 查询基础信息表
        CollectBasic info = basicMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(info)) {
            BeanUtils.copyProperties(info, dto);
            //将采购详情数据查出
            List<CollectDetailed> detailedList = detailedMapper.getByBasicId(id);
            if (CollectionUtils.isNotEmpty(detailedList)){
                detailedList.forEach(detailed->{
                    //附件信息
                    List<WorkAttachmentDto> acList = detailedMapper.getByAttachmentId(detailed.getId());
                    if (CollectionUtils.isNotEmpty(acList)) {
                        for (WorkAttachmentDto i : acList) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
//                            i.setCreateBy(UserUtils.get(i.getBy()));
                        }
                    }
                    detailed.setFileInfoLost(acList);
                });
            }
            dto.setDetailInfos(detailedList);
            // 领用 附件信息
            List<WorkAttachmentDto> files = detailedMapper.getByAttachmentId(info.getId());
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentDto i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            //根据经办人id查出经办人的名称
            String name = basicMapper.getUserNameByUserId(info.getHandledBy());
            //根据经办人部门id查询经办人部门名称
            String officeName = basicMapper.getOfficeNameByOfficeId(info.getHandledByOffice());
            dto.setHandledByOfficeName(officeName);
            dto.setHandledBy(name);
            dto.setHandledById(info.getHandledBy());
            dto.setFiles(files);
        }
        // 领用-退回流程信息
        CollectBasicsReturn collectBasicsReturn = basicMapper.selectReturnByBasicId(id);
        if (ObjectUtil.isNotEmpty(collectBasicsReturn)) {
            if (StringUtils.isNotBlank(collectBasicsReturn.getProcessDefinitionId())){
                dto.setProcessDefinitionIdReturn(collectBasicsReturn.getProcessDefinitionId());
            }
            if (StringUtils.isNotBlank(collectBasicsReturn.getProcInsId())){
                dto.setProcInsIdReturn(collectBasicsReturn.getProcInsId());
            }
            if (StringUtils.isNotBlank(collectBasicsReturn.getStatus())){
                dto.setStatusReturn(collectBasicsReturn.getStatus());
            }
            if (StringUtils.isNotBlank(collectBasicsReturn.getId())){
                dto.setReturnId(collectBasicsReturn.getId());
                // 领用-退回 附件信息
                List<WorkAttachmentDto> returnFiles = detailedMapper.getByAttachmentId(collectBasicsReturn.getId());
                if (CollectionUtils.isNotEmpty(returnFiles)) {
                    for (WorkAttachmentDto i : returnFiles) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                }
                dto.setReturnFiles(returnFiles);
            }
            if (StringUtils.isNotBlank(collectBasicsReturn.getRemarks())){
                dto.setReturnCause(collectBasicsReturn.getRemarks());
            }
        }
        return dto;
    }

    /**
     * 列表查询
     */
    public IPage<CollectDto> list(Page<CollectDto> page , CollectDto dto) throws Exception{
        QueryWrapper<CollectDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, CollectDto.class);

        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotEmpty(dto.getCollectNo())) {
            queryWrapper.like("a.collect_no", dto.getCollectNo());
        }
        if (StringUtils.isNotEmpty(dto.getGoodsName())) {
            queryWrapper.like("b.goods_name", dto.getGoodsName());
        }
        if (StringUtils.isNotEmpty(dto.getHandledBy())) {
            queryWrapper.eq("su.id", dto.getHandledBy());
        }
        if (StringUtils.isNotEmpty(dto.getHandledByOffice())) {
            //先根据id查出是否是父节点，是父节点则查出所有的子节点信息
            List<String> childIds = basicMapper.findChildIds(dto.getHandledByOffice());
            if ( null != childIds & childIds.size()>0){
                childIds.add(dto.getHandledByOffice());
                queryWrapper.in("a.handled_by_office",childIds);
            }else {
                queryWrapper.eq("a.handled_by_office", dto.getHandledByOffice());
            }
        }
        String[] contractDates = dto.getCollectDates();
        if (contractDates != null) {

            queryWrapper.between("a.collect_date", contractDates[0], contractDates[1]);
        }
        if (StringUtils.isNotBlank(dto.getStatusReturn())) {
            queryWrapper.eq("returna.status", dto.getStatusReturn());
        }
        IPage<CollectDto> list = basicMapper.findList(page, queryWrapper);
        list.getRecords().stream().forEach(item -> {
            // 领用申请
            if (StringUtils.isNotBlank(item.getTaskId()) && StringUtils.isNotBlank(item.getStatus())) {
                if ("2".equals(item.getStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                }
            }
            // 领用-退回申请
            if (StringUtils.isNotBlank(item.getTaskIdReturn()) && StringUtils.isNotBlank(item.getStatusReturn())) {
                if ("2".equals(item.getStatusReturn())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIdsReturn(flowTaskService.getTaskAuditUsers(item.getTaskIdReturn()));  // 获取数据审核人
                }
            }
        });
        return list;
    }

    /**
     * 列表查询
     */
    public IPage<WareHouseSummaryDto> wareHouseList(Page<WareHouseSummaryDto> page , WareHouseSummaryDto dto) throws Exception{
        QueryWrapper<WareHouseSummaryDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, WareHouseSummaryDto.class);

        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.ware_house_type", dto.getWareHouseType());
        queryWrapper.gt("a.trade_number", 0);
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }

        return basicMapper.findWareHouseList(page, queryWrapper);
    }

    public String createReturnData (String basicId) {
        CollectBasicsReturn returnData = returnMapper.selectOne(new LambdaQueryWrapper<CollectBasicsReturn>().eq(CollectBasicsReturn::getBasicId, basicId));
        if (ObjectUtil.isNotEmpty(returnData)) {
            return returnData.getId();
        } else {
            CollectBasicsReturn collectBasicsReturn = new CollectBasicsReturn();
            collectBasicsReturn.setBasicId(basicId);
            collectBasicsReturn.setStatus("0"); // 未发起状态
            returnMapper.insert(collectBasicsReturn);
            return collectBasicsReturn.getId();
        }
    }

    public CollectDto findByReturnId (String returnId) {
        CollectBasicsReturn returnData = returnMapper.selectOne(new LambdaQueryWrapper<CollectBasicsReturn>().eq(CollectBasicsReturn::getId, returnId));
        if (ObjectUtil.isNotEmpty(returnData) && StringUtils.isNotBlank(returnData.getBasicId())) {
            CollectDto byId = this.findById(returnData.getBasicId());
            return byId;
        } else {
            return new CollectDto();
        }
    }

    public void returnRequest(String id) {
        CollectBasicsReturn returnData = returnMapper.selectOne(new LambdaQueryWrapper<CollectBasicsReturn>().eq(CollectBasicsReturn::getBasicId, id));
        if (ObjectUtil.isNotEmpty(returnData) && StringUtils.isNotBlank(returnData.getId())) {
            detailedMapper.updateStatusByIdReturn(returnData.getId(), "0"); // 修改退回的流程状态
            basicMapper.setCauseEmptyById(returnData.getId()); // 清空退回原因
//            ossService.remove(new LambdaQueryWrapper<WorkAttachment>().eq(WorkAttachment::getAttachmentId, returnData.getId())); // 清除退回附件
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(returnData.getId());
        }
        // 将退回状态的数据全部撤回
        detailedMapper.updateNoReturnByBasicId(id);
    }

    // 根据领用表id查询其全部历史修改数据
    public List<CollectBasicsReturnHi> findHiById(String collectId) {
        List<CollectBasicsReturnHi> hiById = returnHiMapper.findHiById(collectId);
        return hiById;
    }

    // 根据历史表id查询历史表数据
    public CollectDto findHiByHiId(String hiId) {
        CollectDto collectDto = new CollectDto();
        CollectBasicsReturnHi hiByHiId = returnHiMapper.findHiByHiId(hiId); // 根据历史表id查询历史表数据
        if (ObjectUtil.isNotEmpty(hiByHiId) && StringUtils.isNotBlank(hiByHiId.getJsonData())) {
            collectDto = JSON.parseObject(hiByHiId.getJsonData(), CollectDto.class); // json字符串解析为java对象
            if (ObjectUtil.isNotEmpty(collectDto)) {
                // 领用详情中的附件数据获取。
                // 在这里要重新获取一下领用详情附件的原因是，json字符串中的附件createBy值存储不正确，所以重新获取一下
                if(CollectionUtil.isNotEmpty(collectDto.getDetailInfos())) {
                    collectDto.getDetailInfos().forEach(detailed->{
                        List<WorkAttachmentDto> acList = detailedMapper.getByAttachmentId(detailed.getId());
                        if (CollectionUtils.isNotEmpty(acList)) {
                            for (WorkAttachmentDto i : acList) {
                                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                            }
                        }
                        detailed.setFileInfoLost(acList);
                    });
                }
                // 领用-退回附件信息同上
                if(CollectionUtil.isNotEmpty(collectDto.getReturnFiles())) {
                    collectDto.getReturnFiles().forEach(file->{
                        file.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(file.getBy()));
                    });
                }
            }

        }
        return collectDto;
    }

    // 根据领用表id查询最近的一个修改历史
    public CollectDto findLastHiByid(String collectId) {
        CollectDto collectDto = new CollectDto();
        CollectBasicsReturnHi hiByHiId = returnHiMapper.findLastHiByid(collectId); // 根据领用表id查询最近的一个修改历史
        if (ObjectUtil.isNotEmpty(hiByHiId) && StringUtils.isNotBlank(hiByHiId.getJsonData())) {
            collectDto = JSON.parseObject(hiByHiId.getJsonData(), CollectDto.class); // json字符串解析为java对象
            if (ObjectUtil.isNotEmpty(collectDto)) {
                // 领用详情中的附件数据获取。
                // 在这里要重新获取一下领用详情附件的原因是，json字符串中的附件createBy值存储不正确，所以重新获取一下
                if(CollectionUtil.isNotEmpty(collectDto.getDetailInfos())) {
                    collectDto.getDetailInfos().forEach(detailed->{
                        List<WorkAttachmentDto> acList = detailedMapper.getByAttachmentId(detailed.getId());
                        if (CollectionUtils.isNotEmpty(acList)) {
                            for (WorkAttachmentDto i : acList) {
                                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                            }
                        }
                        detailed.setFileInfoLost(acList);
                    });
                }
                // 领用-退回附件信息同上
                if(CollectionUtil.isNotEmpty(collectDto.getReturnFiles())) {
                    collectDto.getReturnFiles().forEach(file->{
                        file.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(file.getBy()));
                    });
                }
            }

        }
        return collectDto;
    }
}
