package com.jeeplus.psimanage.psiWareHouse.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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.psimanage.collect.domain.PsiCollectDetailed;
import com.jeeplus.psimanage.collect.domain.PsiCollectDetailedRecord;
import com.jeeplus.psimanage.collect.mapper.PsiCollectDetailedMapper;
import com.jeeplus.psimanage.collect.mapper.PsiCollectDetailedRecordMapper;
import com.jeeplus.psimanage.psiWareHouse.service.dto.PsiWareSummaryExportDto;
import com.jeeplus.psimanage.purchase.domain.PsiMaterialBasic;
import com.jeeplus.psimanage.purchase.domain.PsiMaterialDetailed;
import com.jeeplus.psimanage.purchase.mapper.PsiMaterialBasicMapper;
import com.jeeplus.psimanage.purchase.mapper.PsiMaterialDetailedMapper;
import com.jeeplus.psimanage.purchase.service.PsiMaterialService;
import com.jeeplus.psimanage.supplier.domain.PsiMaterialSupplier;
import com.jeeplus.psimanage.supplier.mapper.PsiMaterialSupplierMapper;
import com.jeeplus.psimanage.psiWareHouse.domain.PsiWareHouseBasic;
import com.jeeplus.psimanage.psiWareHouse.domain.PsiWareHouseDetailed;
import com.jeeplus.psimanage.psiWareHouse.domain.PsiWarehouseUpHi;
import com.jeeplus.psimanage.psiWareHouse.mapper.PsiWareHouseBasicMapper;
import com.jeeplus.psimanage.psiWareHouse.mapper.PsiWareHouseDetailedMapper;
import com.jeeplus.psimanage.psiWareHouse.mapper.PsiWareHouseSummaryMapper;
import com.jeeplus.psimanage.psiWareHouse.mapper.PsiWarehouseUpHiMapper;
import com.jeeplus.psimanage.psiWareHouse.service.dto.PsiWareHouseDto;
import com.jeeplus.psimanage.psiWareHouse.service.dto.PsiWareHouseExportDto;
import com.jeeplus.psimanage.oss.domain.PsiWorkAttachment;
import com.jeeplus.psimanage.oss.mapper.PsiOssServiceMapper;
import com.jeeplus.psimanage.oss.service.PsiOssService;
import com.jeeplus.psimanage.oss.service.dto.WorkAttachmentDto;
import com.jeeplus.psimanage.serialNumTpl.service.PsiSerialnumTplService;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;

/**
 * @author: 王强
 * @create: 2022-12-29 14:19
 **/
@Service
@Transactional
public class PsiWareHouseBasicService {

    @Resource
    private PsiMaterialBasicMapper psiMaterialBasicMapper;

    @Resource
    private PsiWareHouseBasicMapper basicMapper;

    @Resource
    private PsiWareHouseDetailedMapper psiDetailedMapper;

    @Resource
    private PsiWareHouseSummaryMapper summaryMapper;

    @Resource
    private PsiMaterialDetailedMapper psiMaterialDetailedMapper;

    @Resource
    private PsiOssServiceMapper psiOssServiceMapper;

    @Resource
    private PsiSerialnumTplService psiSerialnumTplService;

    @Resource
    private PsiMaterialService basicService;

//    @Resource
//    private ContractInfoService infoService;

    @Resource
    private IFlowableApi flowTaskService;

    @Resource
    private PsiWarehouseUpHiMapper psiWarehouseUpHiMapper;

    @Resource
    private PsiWareHouseBasicMapper psiWareHouseBasicMapper;

    @Resource
    private PsiOssService psiOssService;

    @Resource
    private PsiMaterialSupplierMapper psiMaterialSupplierMapper;

    @Resource
    private PsiCollectDetailedRecordMapper psiCollectDetailedRecordMapper;

    @Resource
    private PsiCollectDetailedMapper psiCollectDetailedMapper;

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

        queryWrapper.eq("a.del_flag", "0");

        if (StringUtils.isNotBlank(dto.getDetailId())) {
            queryWrapper.eq("b.id", dto.getDetailId());
        }

        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.eq("b.trade_name", dto.getTradeName());
        }


        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("b.ware_house_type", dto.getWareHouseType());
        }

        if (StringUtils.isNotEmpty(dto.getWareHouseNumber())) {
            queryWrapper.eq("a.ware_house_number", dto.getWareHouseNumber());
        }

        String[] wareHouseDates = dto.getWareHouseDates();
        if (wareHouseDates != null) {

            queryWrapper.between("a.ware_house_date", wareHouseDates[0], wareHouseDates[1]);
        }

        queryWrapper.and(wq ->{
            wq.eq("a.`status`","0")
                    .or()
                    .eq("a.`status`","5");
        });

        IPage<PsiWareHouseDto> iPage = basicMapper.wareHouseHistoryList(page, queryWrapper);
        //根据时间查询当前库存
        iPage.getRecords().stream().forEach(i->{
            //根据商品名称，物品类型，时间查当前库存
            String d = basicMapper.getWareHouseInfoByTime(i.getTradeName(),i.getWareHouseType(),i.getProduceDate());
            i.setCurrentInventory(d);
        });
        //根据查询领用明细
        return iPage;
    }

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

        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.status", "5");
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.eq("b.goods_name", dto.getTradeName());
        }

        if (StringUtils.isNotEmpty(dto.getCollectNo())) {
            queryWrapper.eq("a.collect_no", dto.getCollectNo());
        }


        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("b.ware_house_type", dto.getWareHouseType());
        }

        String[] collectDates = dto.getCollectDates();
        if (collectDates != null) {

            queryWrapper.between("a.collect_date", collectDates[0], collectDates[1]);
        }
        IPage<PsiWareHouseDto> iPage = basicMapper.collectHistoryList(page, queryWrapper);
        //根据时间查询当前库存
        iPage.getRecords().stream().forEach(i->{
            //根据商品名称，物品类型，时间查当前库存
            String d = basicMapper.getCollectInfoByTime(i.getGoodsName(),i.getCollectType(),i.getDateTest2());
            i.setCurrentInventory(d);
        });
        return iPage;
    }

    public String remove(String id) {
        // 删除基础信息表
        basicMapper.deleteById(id);
        // 删除详情列表 及对应附件信息
        List<PsiWareHouseDetailed> detailedList = psiDetailedMapper.getByBasicId(id);
        if (null != detailedList){
            detailedList.forEach(de->{
                //附件
                List<WorkAttachmentDto> fileList = psiDetailedMapper.getByAttachmentId(de.getId());
                if ( null != fileList ){
                    fileList.forEach(f->{
                        psiOssServiceMapper.deleteById(f.getId());
                    });
                }
                psiDetailedMapper.deleteById(de.getId());
            });
        }
        // 删除附件信息
        LambdaQueryWrapper<PsiWorkAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PsiWorkAttachment::getAttachmentId, id);
        psiOssServiceMapper.delete(wrapper);
        //删除入库汇总表信息
//        List<WareHouseSummary> summaryList = summaryMapper.getInfoByBasicId(id);
//        summaryList.forEach(sum->{
//            summaryMapper.deleteById(sum.getId());
//        });
        return "操作成功";
    }

    public PsiWareHouseDto findById(String id, String status) {
        PsiWareHouseDto dto = new PsiWareHouseDto();
        // 查询基础信息表
        PsiWareHouseBasic info = basicMapper.selectById(id);
        BeanUtils.copyProperties(info, dto);
        dto.setCreateBy(info.getCreateById());
        // 查询入库详情数据，只包含没有被修改过的数据以及修改后的数据
        List<PsiWareHouseDetailed> wareHouseList = psiDetailedMapper.getByBasicId(id);
        // 审核页面或者查看详情页面要进这个判断，这里面会将被修改掉的数据也查出来
        if ("audit".equals(status) || "taskFormDetail".equals(status)) {
            List<PsiWareHouseDetailed> wareList = new ArrayList<>();
            List<PsiWareHouseDetailed> finalWareHouseList = psiDetailedMapper.getByBasicIdAll(id);
            List<PsiWareHouseDetailed> detailedList = wareHouseList; // 这里不copy一下会报错
            detailedList.stream().forEach(item2 -> {
                if (StringUtils.isBlank(item2.getSourceId())) {
                    wareList.add(item2); // 获取一直没有被修改过的数据
                }
            });
            finalWareHouseList.stream().forEach(item -> {
                if("2".equals(item.getUpFlag())) {
                    wareList.add(item); // 获取被删除的数据
                } else if ("1".equals(item.getUpFlag())) {
                    wareList.add(item); // 获取被修改的数据
                    detailedList.stream().forEach(item2 -> {
                        if (StringUtils.isNotBlank(item2.getSourceId())) {
                            if (item2.getSourceId().equals(item.getId())) {
                                wareList.add(item2); // 获取修改后的数据
                            }
                        }
                    });
                }
            });
            wareHouseList = new ArrayList<>(wareList); // 给 wareHouseList重新赋值
        }
        if (CollectionUtils.isNotEmpty(wareHouseList)){
            wareHouseList.forEach(detailed->{
                // 供应商查询
                if (StringUtils.isNotBlank(detailed.getIsSupplier()) && "2".equals(detailed.getIsSupplier()) &&
                        StringUtils.isNotBlank(detailed.getSupplierId())) {
                    PsiMaterialSupplier materialSupplier = psiMaterialSupplierMapper.selectById(detailed.getSupplierId()); // 供应商信息
                    if (ObjectUtil.isNotEmpty(materialSupplier)) {
                        detailed.setSupplierName(materialSupplier.getName());
                    }
                }
                // 附件信息
                List<WorkAttachmentDto> acList = psiDetailedMapper.getByAttachmentId(detailed.getId());
                if (CollectionUtils.isNotEmpty(acList)) {
                    for (WorkAttachmentDto i : acList) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                }
                detailed.setFileInfoLost(acList);
            });
        }
        //将采购详情数据查出
        List<PsiMaterialDetailed> detailedList = new ArrayList<>();
        if (StringUtils.isNotEmpty(info.getPurchaseNo())) {
            PsiMaterialBasic basic = psiMaterialBasicMapper.getInfoByPurchaseNo(info.getPurchaseNo());
            if (null != basic) {
                detailedList = psiMaterialDetailedMapper.getByBasicId(basic.getId());
            }
        }

        if (CollectionUtils.isNotEmpty(detailedList)){
            detailedList.forEach(detailed->{
                //附件信息
                List<WorkAttachmentDto> acList = psiMaterialDetailedMapper.getByAttachmentId(detailed.getId());
                if (CollectionUtils.isNotEmpty(acList)) {
                    for (WorkAttachmentDto i : acList) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                }
                detailed.setFileInfoLost(acList);
            });
        }
        dto.setDetailInfos(detailedList);
        dto.setWareHouse(wareHouseList);
        //附件信息
        List<WorkAttachmentDto> files = psiDetailedMapper.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());
        dto.setHandledBy(name);
        dto.setHandledById(info.getHandledBy());
        dto.setFiles(files);
        return dto;
    }

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

    public String update(PsiWareHouseDto dto, UserDTO userDTO) {
        if (StringUtils.isNotBlank(dto.getFunctionFlag())) {
            if ("start".equals(dto.getFunctionFlag())) { // 送审时执行
                // 添加当前修改申请人
                basicMapper.saveUpdateUser(dto.getId(),SpringUtil.getBean ( IUserApi.class ).getByToken (TokenProvider.getCurrentToken ( )).getId());
//                basicMapper.saveUpdateUser(dto.getId(),UserUtils.getCurrentUserDTO().getId());
                // 判断是否为第一次送审（目的是排除撤回后送审或者驳回后送审）
                List<PsiWarehouseUpHi> warehouseUpHis = psiWarehouseUpHiMapper.selectList(new LambdaQueryWrapper<PsiWarehouseUpHi>()
                        .eq(PsiWarehouseUpHi::getWarehouseId, dto.getId()).eq(PsiWarehouseUpHi::getEndflag, "0"));
                if (CollectionUtil.isEmpty(warehouseUpHis)) { // 当前送审操作为第一次送审
                    // 将未修改的数据添加到历史数据表中
                    PsiWareHouseDto byId = this.findById(dto.getId(),"false");
                    String jsonString = JSON.toJSONString(byId);
                    PsiWarehouseUpHi warehouseUpHi = new PsiWarehouseUpHi();
                    warehouseUpHi.setEndflag("0"); // endflag = 0 代表此数据为原数据，在回退数据的时候使用
                    warehouseUpHi.setJsonData(jsonString);
                    warehouseUpHi.setWarehouseId(dto.getId());
                    psiWarehouseUpHiMapper.insert(warehouseUpHi);
                }
            }
            if ("agree".equals(dto.getFunctionFlag())) { // 审核通过时执行
                // 将历史数据表中的原始数据删除（end_flag = 0并且warehouse_id = 当前数据id）
                psiWarehouseUpHiMapper.delete(new LambdaQueryWrapper<PsiWarehouseUpHi>().eq(PsiWarehouseUpHi::getEndflag,"0").eq(PsiWarehouseUpHi::getWarehouseId,dto.getId()));
                PsiWarehouseUpHi warehouseUpHi = new PsiWarehouseUpHi();
                // 获取到当前审核页面的数据并存储到历史修改表中
                PsiWareHouseDto byId = this.findById(dto.getId(),"audit");
                if (ObjectUtil.isNotEmpty(byId)) {
                    // 获取修改数据的商品名称、商品类型
                    if (CollectionUtil.isNotEmpty(byId.getWareHouse())){
                        List<PsiWareHouseDetailed> updateData = byId.getWareHouse().stream().filter(i -> {
                            if ("1".equals(i.getUpFlag()) || "2".equals(i.getUpFlag())) {
                                return true;
                            }
                            return false;
                        }).collect(Collectors.toList());
                        List<String> updateTradeNameList = updateData.stream().map(PsiWareHouseDetailed::getTradeName).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(updateTradeNameList)) {
                            //获取修改数据的商品名称
                            warehouseUpHi.setUpdateTradeName(String.join(",",updateTradeNameList));
                        }
                        List<String> updateTradeTypeList = updateData.stream().map(PsiWareHouseDetailed::getWareHouseType).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(updateTradeTypeList)) {
                            //获取修改数据的商品类型
                            warehouseUpHi.setUpdateTradeType(String.join(",",updateTradeTypeList));
                        }
                    }
                    // 保存当前审核页面的数据到历史修改表
                    String jsonString = JSON.toJSONString(byId);
                    warehouseUpHi.setJsonData(jsonString);
                }
                // 获取数据修改申请人
                String updateUser = basicMapper.getUpdateUser(dto.getId());
                if (StringUtils.isNotBlank(updateUser)) {
                    warehouseUpHi.setUpdateUser(updateUser); // 历史修改表保存修改人
                    basicMapper.deleteUpdateUser(dto.getId()); // 删除数据修改申请人
                }
                warehouseUpHi.setEndflag("1"); // endflag = 1 代表当前数据为历史修改数据
                warehouseUpHi.setWarehouseId(dto.getId());
                psiWarehouseUpHiMapper.insert(warehouseUpHi);
                // 修改基础信息
                PsiWareHouseBasic info = new PsiWareHouseBasic();
                BeanUtils.copyProperties(dto, info);
                info.setHandledBy(dto.getHandledById());
                basicMapper.updateById(info);
                // 把修改原因清空
                basicMapper.clearUpdateCause(dto.getId());
                // 入库详情修改
                List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>()
                        .eq(PsiWareHouseDetailed::getBasicId,info.getId()));
                wareHouseDetaileds.forEach(item -> {
                    if ("1".equals(item.getUpFlag()) || "2".equals(item.getUpFlag())) { // 将修改前的数据以及删除标记的数据删除
                        psiDetailedMapper.deleteById(item.getId());
                    } else if ("0".equals(item.getUpFlag())) {
                        if (StringUtils.isNotBlank(item.getSourceId())) { // 将修改后数据的sourceId置空
                            psiDetailedMapper.upSourceIdEmpty(item.getId()); // 根据入库详情id置空sourceId
                        }
                    }
                    //调整库存对应的入库类型
                    List<PsiCollectDetailedRecord> recordList = psiCollectDetailedRecordMapper.selectList(
                            new LambdaQueryWrapper<PsiCollectDetailedRecord>()
                                    .eq(PsiCollectDetailedRecord::getInventoryId, item.getId())
                                    .eq(PsiCollectDetailedRecord::getDelFlag,"0")
                    );
                    for (PsiCollectDetailedRecord psiCollectDetailedRecord : recordList) {
                        if(!psiCollectDetailedRecord.getCollectType().equals(item.getWareHouseType())){
                            psiCollectDetailedRecordMapper.update(
                                    null,
                                    new LambdaUpdateWrapper<PsiCollectDetailedRecord>()
                                            .eq(PsiCollectDetailedRecord::getId, psiCollectDetailedRecord.getId())
                                            .set(PsiCollectDetailedRecord::getCollectType, item.getWareHouseType()));
                            psiCollectDetailedMapper.update( null,
                                    new LambdaUpdateWrapper<PsiCollectDetailed>()
                                            .eq(PsiCollectDetailed::getId, psiCollectDetailedRecord.getDetailId())
                                            .set(PsiCollectDetailed::getCollectType, item.getWareHouseType()));

                        }
                    }
                });
                //通知发起人
                List<UserDTO> notifiedPartyUsers = new ArrayList<>();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String day = format.format(new Date());
                String title = "[入库修改："+dto.getPurchaseNo()+"]-入库修改申请审批通过";
                UserDTO initiator = SpringUtil.getBean(IUserApi.class).getById(dto.getHandledById());
                notifiedPartyUsers.add(initiator);
                //向用户发起通知
                if (null != notifiedPartyUsers) {
                    for (UserDTO userDTO1 : notifiedPartyUsers) {
                        //发送通知
                        Map<String ,String > map = new HashMap<>();
                        map.put("taskId",dto.getProcInsId());
                        map.put("title",title);
                        map.put("defId",dto.getProcessDefinitionId());
                        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);
                    }
                }
                return dto.getId();
            }
            if ("back".equals(dto.getFunctionFlag())) { // 撤回后取消修改、流程终止
                // 修改基础信息
                PsiWareHouseBasic info = new PsiWareHouseBasic();
                BeanUtils.copyProperties(dto, info);
                info.setHandledBy(dto.getHandledById());
                basicMapper.updateById(info);
                basicMapper.deleteUpdateUser(dto.getId()); // 删除数据修改申请人
                // 修改附件信息列表
                psiOssService.saveOrUpdateFileList(dto.getFiles(), dto.getId(),"ware_house_basic",TokenProvider.getCurrentToken ( ));
                // 入库详情修改
                // 物理删除此入库的全部入库关联的附件表数据，然后再新增附件。因为如果不物理删除，新增时会有主键冲突
                List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new QueryWrapper<PsiWareHouseDetailed>().lambda().eq(PsiWareHouseDetailed::getBasicId, dto.getId()));
                List<String> detailedIdList = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
                psiDetailedMapper.deleteFilesByIdList(detailedIdList);
                // 物理删除此入库的全部入库详情，然后再新增。因为如果不物理删除，新增时会有主键冲突
                psiDetailedMapper.deleteByBasicId(dto.getId());
                if (CollectionUtils.isNotEmpty(dto.getWareHouse())) {
                    dto.getWareHouse().stream().forEach(item -> {
                        item.setWareHouseMan(item.getWareHouseManId());
                        item.setWareHouseType(item.getWareHouseTypeId());
                        psiDetailedMapper.insert(item);
                        // 保存附件信息列表
                        psiOssService.saveOrUpdateFileList(item.getFileInfoLost(), item.getId(),"ware_house_detail",TokenProvider.getCurrentToken ( ));
                    });
                }
                // 删除送审时在历史修改表添加的数据
                psiWarehouseUpHiMapper.delete(new QueryWrapper<PsiWarehouseUpHi>().lambda()
                        .eq(PsiWarehouseUpHi::getWarehouseId,dto.getId()).eq(PsiWarehouseUpHi::getEndflag,"0"));
            }
        }

        // 修改基础信息
        PsiWareHouseBasic info = new PsiWareHouseBasic();
        BeanUtils.copyProperties(dto, info);
        info.setHandledBy(dto.getHandledById());
        basicMapper.updateById(info);

        // 入库详情修改
        if (CollectionUtils.isNotEmpty(dto.getWareHouse())) {
            // 获取前端删除的入库详情
            List<String> liveIds = dto.getWareHouse().stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>()
                    .eq(PsiWareHouseDetailed::getBasicId,info.getId()).notIn(PsiWareHouseDetailed::getId, liveIds));
            wareHouseDetaileds.stream().forEach(d -> {
                if ("0".equals(d.getUpFlag())) {
                    d.setUpFlag("2"); // 已删除标记
                    dto.getWareHouse().add(d);
                }
            });
            dto.getWareHouse().stream().forEach(detailInfo -> {
                detailInfo.setWareHouseMan(detailInfo.getWareHouseManId());
                detailInfo.setWareHouseType(detailInfo.getWareHouseTypeId());
                detailInfo.setBasicId(dto.getId()); // 保存基础表信息主键值
                detailInfo.setTradeTotalPrice(dto.getWareHouseTotalPrice());
                if ("1".equals(detailInfo.getUpFlag())) { // ‘修改’标记数据
                    if(StringUtils.isBlank(detailInfo.getSourceId())) {
                        PsiWareHouseDetailed ware = psiDetailedMapper.selectById(detailInfo.getId());
                        boolean is = false;
                        // 判断是否有修改入库详情
                        if (judgmentEquals(detailInfo.getWareHouseMan(),ware.getWareHouseMan())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getWareHouseType(),ware.getWareHouseType())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getTradeName(),ware.getTradeName())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getTradeNumber(),ware.getTradeNumber())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getCompany(),ware.getCompany())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getTradePrice(),ware.getTradePrice())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getActualPrice(),ware.getActualPrice())) {
                            is = true;
                        } else if (judgmentEquals(detailInfo.getRemarks(),ware.getRemarks())) {
                            is = true;
                        } else if (checkSupplierIsChange(ware, detailInfo)) { // 判断供应商是否改变
                            is = true;
                        }
                        if (is) {
                            ware.setUpFlag("1");
                            psiDetailedMapper.updateById(ware);
                            detailInfo.setSourceId(ware.getId());
                            detailInfo.setId(new String());
                            detailInfo.setUpFlag("0");
                            psiDetailedMapper.insert(detailInfo);
                        }
                    }else{
                        detailInfo.setUpFlag("0");
                        psiDetailedMapper.updateById(detailInfo);
                    }
                } else if ("2".equals(detailInfo.getUpFlag())) { // ‘删除’标记数据
                    if(StringUtils.isBlank(detailInfo.getSourceId())) {
                        psiDetailedMapper.updateById(detailInfo);
                    }else{
                        PsiWareHouseDetailed wareHouseDetailed = psiDetailedMapper.selectById(detailInfo.getSourceId());
                        wareHouseDetailed.setUpFlag("2");
                        psiDetailedMapper.updateById(wareHouseDetailed);
                        psiDetailedMapper.deleteById(detailInfo.getId());
                    }
                }
                detailInfo.setCurrentInventory(detailInfo.getTradeNumber());
                psiDetailedMapper.updateById(detailInfo);
                // 修改附件信息列表
                psiOssService.saveOrUpdateFileList(detailInfo.getFileInfoLost(), detailInfo.getId(),"ware_house_detail",TokenProvider.getCurrentToken ( ));

            });
        } else {
            // 当入库详情列表为空时，所有数据打删除标记
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getBasicId,info.getId()));
            wareHouseDetaileds.stream().forEach(d -> {
                d.setUpFlag("2"); // 已删除标记
                if(StringUtils.isBlank(d.getSourceId())) {
                    psiDetailedMapper.updateById(d); // 据修改为 删除标记
                }else{
                    PsiWareHouseDetailed wareHouseDetailed = psiDetailedMapper.selectById(d.getSourceId());
                    wareHouseDetailed.setUpFlag("2");
                    psiDetailedMapper.updateById(wareHouseDetailed); // 原数据修改为 删除标记
                    psiDetailedMapper.deleteById(d.getId());
                }
            });
        }
        // 修改附件信息列表
        psiOssService.saveOrUpdateFileList(dto.getFiles(), dto.getId(),"ware_house_basic",TokenProvider.getCurrentToken ( ));

        return dto.getId();
    }

    // 判断两个字符串是否不相等  true不相等 false相等
    public boolean judgmentEquals(String a,String b) {
        if (StringUtils.isNotBlank(a) && StringUtils.isBlank(b)) { // a非空  b空
            return true;
        }
        if (StringUtils.isBlank(a) && StringUtils.isNotBlank(b)) { // a空  b非空
            return true;
        }
        if (StringUtils.isNotBlank(a) && StringUtils.isNotBlank(b) && !a.equals(b)) { // a非空  b非空  a、b不相等
            return true;
        }
        return false;
    }

    // 判断供应商是否改变
    public boolean checkSupplierIsChange(PsiWareHouseDetailed oldData, PsiWareHouseDetailed newData) {
        if (judgmentEquals(oldData.getSupplierId(),newData.getSupplierId())) {
            return true;
        }
        if (judgmentEquals(oldData.getSupplierName(),newData.getSupplierName())) {
            return true;
        }
        if (judgmentEquals(oldData.getIsSupplier(),newData.getIsSupplier())) {
            return true;
        }
        return false;
    }

    // 流程结束将全部修改的数据撤回到未修改
    public Map<String,String> backSourceData(String id){

        Map<String,String> map = new HashMap<>();
        map.put("result","error");
        String sourceData = psiWarehouseUpHiMapper.getSourceData(id);
        if (StringUtils.isNotBlank(sourceData)) {
            PsiWareHouseDto wareHouseDto = JSON.parseObject(sourceData, PsiWareHouseDto.class);
            if (ObjectUtil.isNotEmpty(wareHouseDto)){
                wareHouseDto.setFunctionFlag("back");
                this.update(wareHouseDto,SpringUtil.getBean ( IUserApi.class ).getByToken (TokenProvider.getCurrentToken ( )));
//                this.update(wareHouseDto,UserUtils.getCurrentUserDTO());
                map.replace("result","success");
            }
        }
        return map;
    }

    public String add(PsiWareHouseDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = psiSerialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE,TokenProvider.getCurrentToken());
        // 保存基础信息表信息
        PsiWareHouseBasic info = new PsiWareHouseBasic();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
//        info.setNo(no);
        info.setWareHouseNumber(no);
        info.setHandledBy(dto.getHandledById());
        info.setPurchaseNo(dto.getPurchaseNo());
        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.getWareHouse())) {
            for (PsiWareHouseDetailed detailed : dto.getWareHouse()) {
                // 生成id
                String detailId = UUID.randomUUID().toString().replace("-", "");
                detailed.setWareHouseMan(detailed.getWareHouseManId());
                detailed.setId(detailId);
                detailed.setCreateById(userDTO.getId());
                detailed.setCreateTime(new Date());
                detailed.setUpdateById(userDTO.getId());
                detailed.setUpdateTime(new Date());
                detailed.setDelFlag(0);
                detailed.setWareHouseType(detailed.getWareHouseTypeId());
                // 保存基础表信息主键值
                detailed.setBasicId(id);
                detailed.setTradeTotalPrice(dto.getWareHouseTotalPrice());
                detailed.setUpFlag("0");
                if(detailed.getSpec().equals("0")){
                    detailed.setSpec("1");
                }
                if (StringUtils.isNotBlank(detailed.getWareHouseType()) && StringUtils.isNotBlank(detailed.getTradeName())) {
                    // 根据商品名称和入库类型查询 警告数量、警告标记
                    List<PsiWareHouseDto> byTypeAndTradeName = psiWareHouseBasicMapper.getByTypeAndTradeName(detailed.getTradeName(), detailed.getWareHouseType());
                    // 如果存在，则将当前新增数据的 警告数量、警告标记 赋值为查询到的值
                    if (CollectionUtil.isNotEmpty(byTypeAndTradeName)) {
                        detailed.setWarnNum(byTypeAndTradeName.get(0).getWarnNum()); // 提醒数量
                        detailed.setWarnFlag(byTypeAndTradeName.get(0).getWarnFlag()); // 提醒标记
                    }
                }
                //获取该商品对应的库存数据
                PsiWareHouseDto wareHouseDto = psiWareHouseBasicMapper.getByTypeAndGoodsNameByProduceDate(detailed.getTradeName(), detailed.getWareHouseTypeId(),detailed.getProduceDate());
                //设置当前库存
//                if (null == wareHouseDto){
//                    detailed.setCurrentInventory(detailed.getTradeNumber());
//                } else {
////                        Double num1 = Double.parseDouble(detailInfo.getTradeNumber());
////                        Double num2 = Double.parseDouble(wareHouseDto.getTradeNumber());
////                        String sum = num1 + num2 + "";
//                    detailed.setCurrentInventory(wareHouseDto.getTradeNumber());
//                }
                    detailed.setCurrentInventory(detailed.getTradeNumber());

                psiDetailedMapper.insert(detailed);
                //保存详情列表附件信息
                if (CollectionUtils.isNotEmpty(detailed.getFileInfoLost())){
                    basicService.saveFiles(detailed.getFileInfoLost(), userDTO, detailId);
                }
                //将入库详情商品信息汇总处理
                //根据商品名称及入库类型查是否有相关数据
//                WareHouseSummary summary = summaryMapper.getInfoByTradeName(detailed.getTradeName(),detailed.getWareHouseType());;
//                if (null != summary) {
//                    String num = Double.valueOf(detailed.getTradeNumber())
//                            + Double.valueOf(summary.getTradeNumber()) + "";
//                    summary.setTradeNumber(num);
//                    summaryMapper.updateById(summary);
//                } else {
//                    summary = new WareHouseSummary();
//                    // 生成id
//                    String summaryId = UUID.randomUUID().toString().replace("-", "");
//                    summary.setDetailedId(detailed.getId());
//                    summary.setId(summaryId);
//                    summary.setCreateBy(userDTO.getId());
//                    summary.setCreateDate(new Date());
//                    summary.setUpdateBy(userDTO.getId());
//                    summary.setUpdateDate(new Date());
//                    summary.setDelFlag(0);
//                    summary.setWareHouseType(detailed.getWareHouseType());
//                    summary.setTradeName(detailed.getTradeName());
//                    summary.setTradeNumber(detailed.getTradeNumber());
//                    summaryMapper.insert(summary);
//                }
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            basicService.saveFiles(dto.getFiles(), userDTO, id);

        }

        // 将新增的数据保存到历史数据表中
        PsiWareHouseDto byId = this.findById(info.getId(),"false");
        String jsonString = JSON.toJSONString(byId);
        PsiWarehouseUpHi warehouseUpHi = new PsiWarehouseUpHi();
        warehouseUpHi.setUpdateUser(byId.getCreateBy());
        warehouseUpHi.setWarehouseId(byId.getId());
        warehouseUpHi.setEndflag("2");
        warehouseUpHi.setJsonData(jsonString);
        psiWarehouseUpHiMapper.insert(warehouseUpHi);

        return id;
    }

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

        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotEmpty(dto.getWareHouseNumber())) {
            queryWrapper.like("a.ware_house_number", dto.getWareHouseNumber());
        }
        if (StringUtils.isNotEmpty(dto.getWareHouseName())) {
            queryWrapper.like("a.ware_house_name", dto.getWareHouseName());
        }
        if (StringUtils.isNotEmpty(dto.getHandledBy())) {
            queryWrapper.like("sy.id", dto.getHandledBy());
        }
        if (StringUtils.isNotEmpty(dto.getHandledByOffice())) {
            queryWrapper.like("a.handled_by_office", dto.getHandledByOffice());
        }
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.like("a.status", dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getPurchaseId())) {
            queryWrapper.eq("b.id", dto.getPurchaseId());
        }
        if (StringUtils.isNotEmpty(dto.getSupplierId())) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getSupplierId, dto.getSupplierId()));
            if (CollectionUtil.isNotEmpty(wareHouseDetaileds)) {
                List<String> containsIds = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getBasicId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(containsIds)) {
                    queryWrapper.in("a.id", containsIds);
                } else {
                    return new Page<>();
                }
            } else {
                return new Page<>();
            }
        }
        // 入库时间
        String[] contractDates = dto.getWareHouseDates();
        if (contractDates != null) {
            queryWrapper.between("a.ware_house_date", contractDates[0], contractDates[1]);
        }
        if (dto.getStatusTwo() != null) {
            queryWrapper.and(wq ->{
                wq.eq("a.`status`",dto.getStatusTwo()[0])
                        .or()
                        .eq("a.`status`",dto.getStatusTwo()[1]);
            });
        }
        IPage<PsiWareHouseDto> list = basicMapper.findList(page, queryWrapper);
        list.getRecords().forEach(item -> {
            // 入库 修改申请
            if (StringUtils.isNotBlank(item.getTaskId()) && StringUtils.isNotBlank(item.getStatus())) {
                if ("2".equals(item.getStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                }
            }
        });
        return list;
    }

    /**
     * 列表查询
     */
    public List<PsiWareHouseExportDto> exportList(Page<PsiWareHouseDto> page , PsiWareHouseDto dto) throws Exception{
        List<PsiWareHouseDto> basicList = this.list(page, dto).getRecords();
        List<PsiWareHouseExportDto> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(basicList)) {
            return result;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        basicList.forEach(item -> {
            List<PsiWareHouseDetailed> detailList = psiDetailedMapper.getByBasicId(item.getId());
            if (CollectionUtils.isEmpty(detailList)) {
                return;
            }
            detailList.forEach(detail -> {
                PsiWareHouseExportDto exportDto = new PsiWareHouseExportDto();
                exportDto.setId(item.getId());
                exportDto.setWareHouseNumber(item.getWareHouseNumber());
                exportDto.setWareHouseMan(detail.getWareHouseMan());
                exportDto.setWareHouseManOffice(detail.getWareHouseManOffice());
                exportDto.setWareHouseType(detail.getWareHouseType());
                exportDto.setTradeName(detail.getTradeName());
                exportDto.setSupplierName(detail.getSupplierName());
                exportDto.setTradeNumber(formatExportNumber(detail.getTradeNumber()));
                exportDto.setCompany(detail.getCompany());
                exportDto.setSpec(detail.getSpec());
                exportDto.setTradePrice(formatExportNumber(detail.getTradePrice()));
                exportDto.setPriceSum(calculatePriceSum(detail.getTradePrice(), detail.getTradeNumber()));
                exportDto.setProduceDate(detail.getProduceDate() == null ? "" : dateFormat.format(detail.getProduceDate()));
                exportDto.setShelfLife(formatShelfLife(detail.getShelfLife(), detail.getShelfLifeUnit()));
                exportDto.setActualPrice(formatExportNumber(detail.getActualPrice()));
                exportDto.setRemarks(detail.getRemarks());
                result.add(exportDto);
            });
        });
        return result;
    }

    private String formatExportNumber(String value) {
        if (StringUtils.isBlank(value)) {
            return "";
        }
        try {
            return new BigDecimal(value).stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            return value;
        }
    }

    private String calculatePriceSum(String tradePrice, String tradeNumber) {
        if (StringUtils.isBlank(tradePrice) || StringUtils.isBlank(tradeNumber)) {
            return "";
        }
        try {
            BigDecimal price = new BigDecimal(tradePrice);
            BigDecimal number = new BigDecimal(tradeNumber);
            return price.multiply(number).stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            return "";
        }
    }

    private String formatShelfLife(String shelfLife, String shelfLifeUnit) {
        if (StringUtils.isBlank(shelfLife)) {
            return "";
        }
        if (StringUtils.isBlank(shelfLifeUnit)) {
            return shelfLife;
        }
        return shelfLife + " " + shelfLifeUnit;
    }

    public IPage<PsiWareHouseDto> summaryList2(Page<PsiWareHouseDto> page , PsiWareHouseDto dto) throws Exception{
        QueryWrapper<PsiWareHouseDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, PsiWareHouseDto.class);

        queryWrapper.eq("a.del_flag", "0");
        // 库存数量小于等于0的不展示
//        queryWrapper.gt("a.trade_number - b.collect_number", "0");
//        if (StringUtils.isNotEmpty(dto.getWareHouseNumber())) {
//            queryWrapper.like("c.ware_house_number", dto.getWareHouseNumber());
//        }
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }
        if (StringUtils.isNotEmpty(dto.getBasicId())) {
            queryWrapper.eq("b.mmcId", dto.getBasicId());
        }
//        queryWrapper.and(wq ->{
//            wq.eq("bas.`status`","0")
//                    .or()
//                    .eq("bas.`status`","5");
//        });

        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("c.id", dto.getWareHouseType());
        }
        IPage<PsiWareHouseDto> iPage = basicMapper.summaryList2(page, queryWrapper);
        iPage.getRecords().stream().forEach(i->{
            //根据领用类型及领用物品名称查领用数量
            String collectNum = basicMapper.getCollectNumByType(i.getWareHouseType(),i.getTradeName());
            i.setBorrowNumber(collectNum);
            BigDecimal decimal1 = new BigDecimal(i.getAllNumber());
            BigDecimal decimal2 = new BigDecimal(i.getBorrowNumber());

            i.setTradeNumber(decimal1.subtract(decimal2).toString());
        });


        return basicMapper.summaryList2(page, queryWrapper);
    }

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

        queryWrapper.eq("a.del_flag", "0");
        // 库存数量小于等于0的不展示
//        queryWrapper.gt("a.trade_number - b.collect_number", "0");
//        if (StringUtils.isNotEmpty(dto.getWareHouseNumber())) {
//            queryWrapper.like("c.ware_house_number", dto.getWareHouseNumber());
//        }
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }
        queryWrapper.and(wq ->{
            wq.eq("bas.`status`","0")
                    .or()
                    .eq("bas.`status`","5");
        });
//        if (StringUtils.isNotEmpty(dto.getWareHouseMan())) {
//            queryWrapper.like("a.ware_house_man", dto.getWareHouseMan());
//        }
//        if (StringUtils.isNotEmpty(dto.getWareHouseManOffice())) {
//            queryWrapper.like("so.id", dto.getWareHouseManOffice());
//        }

        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("c.id", dto.getWareHouseType());
        }

        //生产日期
        if (dto.getProduceDate() != null) {
            queryWrapper.eq("a.produce_date", dto.getProduceDate());
        }

        // 入库时间
//        String[] contractDates = dto.getWareHouseDates();
//        if (contractDates != null) {
//
//            queryWrapper.between("c.ware_house_date", contractDates[0], contractDates[1]);
//        }
        if (StringUtils.isNotEmpty(dto.getSupplierId())) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getSupplierId, dto.getSupplierId()));
            if (CollectionUtil.isNotEmpty(wareHouseDetaileds)) {
                List<String> containsIds = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(containsIds)) {
                    queryWrapper.in("a.id", containsIds);
                } else {
                    return new Page<>();
                }
            } else {
                return new Page<>();
            }
        }
        IPage<PsiWareHouseDto> wareHouseDtoIPage = basicMapper.summaryList(page, queryWrapper);
        wareHouseDtoIPage.getRecords().forEach(item -> {
            // 将小数点后无效的0删除
            // 总量  格式化
            if (StringUtils.isNotBlank(item.getAllNumber())) {
                String s = convertByBigDecimal(item.getAllNumber());
                item.setAllNumber(s);
            }
            //领用量  格式化
            if (StringUtils.isNotBlank(item.getBorrowNumber())) {
                String s = convertByBigDecimal(item.getBorrowNumber());
                item.setBorrowNumber(s);
            }
            //剩余量  格式化
            if (StringUtils.isNotBlank(item.getTradeNumber())) {
                String s = convertByBigDecimal(item.getTradeNumber());
                item.setTradeNumber(s);
            }
            //提醒数量  格式化
            if (StringUtils.isNotBlank(item.getWarnNum())) {
                String s = convertByBigDecimal(item.getWarnNum());
                item.setWarnNum(s);
            }
        });
        return wareHouseDtoIPage;
    }


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

        queryWrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }
        queryWrapper.and(wq ->{
            wq.eq("bas.`status`","0")
                    .or()
                    .eq("bas.`status`","5");
        });
        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("c.id", dto.getWareHouseType());
        }

        //生产日期
        if (dto.getProduceDate() != null) {
            queryWrapper.eq("a.produce_date", dto.getProduceDate());
        }

        //日期范围
        String[] dateRange = dto.getDateRange();
        //if (dateRange != null) {
        //    queryWrapper.between("bas.ware_house_date", dateRange[0], dateRange[1]);
        //}

        if (StringUtils.isNotEmpty(dto.getSupplierId())) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getSupplierId, dto.getSupplierId()));
            if (CollectionUtil.isNotEmpty(wareHouseDetaileds)) {
                List<String> containsIds = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(containsIds)) {
                    queryWrapper.in("a.id", containsIds);
                } else {
                    return new Page<>();
                }
            } else {
                return new Page<>();
            }
        }
        IPage<PsiWareSummaryExportDto> wareHouseDtoIPage = basicMapper.exportSummaryList(page, queryWrapper,dto);
        wareHouseDtoIPage.getRecords().forEach(item -> {
            // 将小数点后无效的0删除
            //剩余量  格式化
            if (StringUtils.isNotBlank(item.getTradeNumber())) {
                String s = convertByBigDecimal(item.getTradeNumber());
                item.setTradeNumber(s);
            }
            //提醒数量  格式化
            if (StringUtils.isNotBlank(item.getWarnNum())) {
                String s = convertByBigDecimal(item.getWarnNum());
                item.setWarnNum(s);
            }

            if(item.getWarnFlag().equals("1")){
                item.setWarnFlag("是");
            }else{
                item.setWarnFlag("否");
            }

            if(StringUtils.isBlank(item.getLossNumber())){
                item.setLossNumber("0");
            }

            /*if (StringUtils.isNotBlank(item.getNotSurplusStock())) {
                String notSurplusStockStr = item.getNotSurplusStock();
                String specStr = item.getSpec();

                if (StringUtils.isBlank(notSurplusStockStr) || StringUtils.isBlank(specStr)) {
                    item.setNotSurplusStock(item.getNotSurplusStock());
                }else{
                    BigDecimal notSurplusStockBD = new BigDecimal(notSurplusStockStr);
                    BigDecimal specBD = new BigDecimal(specStr);

                    if (specBD.compareTo(BigDecimal.ZERO) == 0) {
                        item.setNotSurplusStock(item.getNotSurplusStock());
                    }else{
                        BigDecimal totalBD = notSurplusStockBD.divide(specBD, 4, RoundingMode.HALF_UP).stripTrailingZeros();
                        item.setNotSurplusStock(totalBD.toPlainString());
                    }
                }
            }*/

            if (StringUtils.isNotBlank(item.getBorrowNumber())) {
                String notSurplusStockStr = item.getBorrowNumber();
                String specStr = item.getSpec();

                if (StringUtils.isBlank(notSurplusStockStr) || StringUtils.isBlank(specStr)) {
                    item.setBorrowNumber(item.getBorrowNumber());
                }else{
                    BigDecimal notSurplusStockBD = new BigDecimal(notSurplusStockStr);
                    BigDecimal specBD = new BigDecimal(specStr);

                    if (specBD.compareTo(BigDecimal.ZERO) == 0) {
                        item.setBorrowNumber(item.getBorrowNumber());
                    }else{
                        BigDecimal totalBD = notSurplusStockBD.divide(specBD, 4, RoundingMode.HALF_UP).stripTrailingZeros();
                        item.setBorrowNumber(totalBD.toPlainString());
                    }
                }
            }

            if (StringUtils.isNotBlank(item.getLossNumber())) {
                String specStr = item.getSpec();
                String lossNumberStr = item.getLossNumber();

                if (StringUtils.isBlank(specStr)) {
                    item.setLossNumber(item.getLossNumber());
                }else{
                    BigDecimal specBD = new BigDecimal(specStr);
                    BigDecimal lossNumberBD = new BigDecimal(lossNumberStr);
                    if (specBD.compareTo(BigDecimal.ZERO) == 0) {
                        item.setLossNumber(item.getLossNumber());
                    }else{
                        BigDecimal totalBD = lossNumberBD.divide(specBD, 4, RoundingMode.HALF_UP).stripTrailingZeros();
                        item.setLossNumber(totalBD.toPlainString());
                    }
                }
            }

            // 历史库存
            if(StringUtils.isNotBlank(item.getTradeNumber()) && dateRange != null && dateRange.length == 2){
                //计算历史库存时，需要对时间范围之后的入库，领用，报损进行处理
                //当前库存
                BigDecimal bdCurrentInv = new BigDecimal(item.getAllCurrentInventory() != null ? item.getAllCurrentInventory() : "0");
                //当月入库
                BigDecimal bdTradeNum = new BigDecimal(item.getAllNumber() != null ? item.getAllNumber() : "0");
                //当月领取
                //BigDecimal bdNotSurplus = new BigDecimal(item.getNotSurplusStock() != null ? item.getNotSurplusStock() : "0");
                //当月领取
                BigDecimal borrowNumber = new BigDecimal(item.getBorrowNumber() != null ? item.getBorrowNumber() : "0");
                //当月报损
                BigDecimal bdLoss = new BigDecimal(item.getLossNumber() != null ? item.getLossNumber() : "0");
                //日期范围之后的入库数据
                BigDecimal bdAfterTrade = new BigDecimal(item.getAfterTradeNumber() != null ? item.getAfterTradeNumber() : "0");
                //日期范围之后的无剩余库存
                BigDecimal bdAfterNotSurplus = new BigDecimal(item.getAfterNotSurplusStock() != null ? item.getAfterNotSurplusStock() : "0");
                //日期范围之后的报损数据
                BigDecimal bdAfterLoss = new BigDecimal(item.getAfterLossNumber() != null ? item.getAfterLossNumber() : "0");
                //规格
                BigDecimal bdSpec = new BigDecimal(item.getSpec() != null && !item.getSpec().isEmpty() ? item.getSpec() : "0");
                //历史库存 = 当前库存 - 入库 + 领取 + 报损 - 日期范围之后的入库数据 + 日期范围之后无剩余库存 + 日期范围之后的报损数据
                BigDecimal historyInventoryBD;
                if (bdSpec.compareTo(BigDecimal.ZERO) == 0) {
                    historyInventoryBD = bdCurrentInv.subtract(bdTradeNum).add(borrowNumber).add(bdLoss).subtract(bdAfterTrade);
                } else {
                    historyInventoryBD = bdCurrentInv.subtract(bdTradeNum).add(borrowNumber).add(bdLoss).subtract(bdAfterTrade)
                            .add(bdAfterNotSurplus.divide(bdSpec, 4, RoundingMode.HALF_UP))
                            .add(bdAfterLoss.divide(bdSpec, 4, RoundingMode.HALF_UP));
                }
                historyInventoryBD = historyInventoryBD.setScale(4, RoundingMode.HALF_UP).stripTrailingZeros();
                if(historyInventoryBD.compareTo(BigDecimal.ZERO) < 0){
                    historyInventoryBD = BigDecimal.ZERO;
                }
                item.setHisTradeNumber(historyInventoryBD.toPlainString());
                item.setDateRange(dateRange[0] + "至" + dateRange[1]);
            }else{
                item.setHisTradeNumber("0");
                item.setDateRange("全部");
            }

        });
        return wareHouseDtoIPage;
    }


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

        queryWrapper.eq("a.del_flag", "0");

        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }
        queryWrapper.and(wq ->{
            wq.eq("bas.`status`","0")
                    .or()
                    .eq("bas.`status`","5");
        });

        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("c.id", dto.getWareHouseType());
        }

        //生产日期
        if (dto.getProduceDate() != null) {
            queryWrapper.eq("a.produce_date", dto.getProduceDate());
        }

        if (StringUtils.isNotEmpty(dto.getSupplierId())) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getSupplierId, dto.getSupplierId()));
            if (CollectionUtil.isNotEmpty(wareHouseDetaileds)) {
                List<String> containsIds = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(containsIds)) {
                    queryWrapper.in("a.id", containsIds);
                } else {
                    return new Page<>();
                }
            } else {
                return new Page<>();
            }
        }
        IPage<PsiWareHouseDto> wareHouseDtoIPage = basicMapper.getByProduceDateAndName(page, queryWrapper);
        wareHouseDtoIPage.getRecords().forEach(item -> {
            // 将小数点后无效的0删除
            // 总量  格式化
            if (StringUtils.isNotBlank(item.getAllNumber())) {
                String s = convertByBigDecimal(item.getAllNumber());
                item.setAllNumber(s);
            }
            //领用量  格式化
            if (StringUtils.isNotBlank(item.getBorrowNumber())) {
                String s = convertByBigDecimal(item.getBorrowNumber());
                item.setBorrowNumber(s);
            }
            //剩余量  格式化
            if (StringUtils.isNotBlank(item.getTradeNumber())) {
                String s = convertByBigDecimal(item.getTradeNumber());
                item.setTradeNumber(s);
            }
            //提醒数量  格式化
            if (StringUtils.isNotBlank(item.getWarnNum())) {
                String s = convertByBigDecimal(item.getWarnNum());
                item.setWarnNum(s);
            }
        });
        return wareHouseDtoIPage;
    }

    /**
     * 根据库存的保质期和生产日期，进行临期规则筛选
     * @param page
     * @param dto
     */
    public void nearExpiryList(Page<PsiWareHouseDto> page, PsiWareHouseDto dto) {
        Page<PsiWareHouseDto> queryPage = new Page<>();
        queryPage.setCurrent(1);
        queryPage.setSize(-1);
        IPage<PsiWareHouseDto> iPage = basicMapper.nearExpiryList(queryPage, dto);
        List<PsiWareHouseDto> list = new ArrayList<>();
        LocalDate today = LocalDate.now(ZoneId.systemDefault());
        iPage.getRecords().forEach(item -> {
            if (!canCheckNearExpiry(item)) {
                return;
            }
            Integer shelfLifeValue = parseShelfLifeValue(item.getShelfLife());
            if (shelfLifeValue == null) {
                return;
            }
            LocalDate produceDate = toLocalDate(item.getProduceDate());
            LocalDate expiryDate = calculateExpiryDate(produceDate, shelfLifeValue, item.getShelfLifeUnit());
            if (expiryDate == null) {
                return;
            }
            long totalDays = ChronoUnit.DAYS.between(produceDate, expiryDate);
            long remainingDays = ChronoUnit.DAYS.between(today, expiryDate);
            if (!shouldIncludeNearExpiry(totalDays, remainingDays)) {
                return;
            }
            item.setExpiryDate(Date.from(expiryDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            item.setRemainingDays((int) remainingDays);
            list.add(item);
        });
        if(CollectionUtil.isNotEmpty(list)){
            String warnInfo = list.stream()
                    .map(item -> item.getTradeName())
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining("、"));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String day = format.format(new Date());
            String title = "管理员发起了 ["+ warnInfo +"] [物资临期提醒]";
            //向多个用户发起通知
            List<UserDTO> usersInfo = psiDetailedMapper.getUsersInfo();
            //获取目前领用流程的taskid，根据procInsId去查taskId
            String uuid = "";
            if (null != usersInfo) {
                for (UserDTO userDTO1 : usersInfo) {
                    uuid = UUID.randomUUID().toString();
                    //发送通知
                    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","1");
                    flowTaskService.add(map);
                }
            }
        }
    }

    /**
     * 列表查询
     */
    private boolean canCheckNearExpiry(PsiWareHouseDto item) {
        return item != null
                && item.getProduceDate() != null
                && StringUtils.isNotBlank(item.getShelfLife())
                && StringUtils.isNotBlank(item.getShelfLifeUnit());
    }

    private Integer parseShelfLifeValue(String shelfLife) {
        try {
            BigDecimal value = new BigDecimal(shelfLife.trim()).stripTrailingZeros();
            if (value.scale() > 0 || value.compareTo(BigDecimal.ZERO) <= 0) {
                return null;
            }
            return value.intValueExact();
        } catch (Exception e) {
            return null;
        }
    }

    private LocalDate toLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    private LocalDate calculateExpiryDate(LocalDate produceDate, Integer shelfLife, String shelfLifeUnit) {
        String unit = shelfLifeUnit == null ? "" : shelfLifeUnit.trim();
        if (unit.contains("年")) {
            return produceDate.plusYears(shelfLife);
        }
        if (unit.contains("月")) {
            return produceDate.plusMonths(shelfLife);
        }
        if (unit.contains("天") || unit.contains("日")) {
            return produceDate.plusDays(shelfLife);
        }
        return null;
    }

    private boolean shouldIncludeNearExpiry(long totalDays, long remainingDays) {
        if (totalDays <= 0 || remainingDays < 0) {
            return false;
        }
        if (totalDays <= 30) {
            return remainingDays * 3 <= totalDays;
        }
        return remainingDays * 4 <= totalDays
                || remainingDays == 30
                || remainingDays == 60
                || remainingDays == 90;
    }

    private List<PsiWareHouseDto> buildNearExpiryPageRecords(List<PsiWareHouseDto> list, long current, long size) {
        if (size <= 0) {
            return list;
        }
        long start = (current - 1) * size;
        if (start >= list.size()) {
            return new ArrayList<>();
        }
        long end = Math.min(start + size, list.size());
        return new ArrayList<>(list.subList((int) start, (int) end));
    }

    public IPage<PsiWareHouseDto> getByProduceDateNotMerge(Page<PsiWareHouseDto> page , PsiWareHouseDto dto) throws Exception{
        QueryWrapper<PsiWareHouseDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, PsiWareHouseDto.class);

        queryWrapper.eq("a.del_flag", "0");

        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }
        queryWrapper.and(wq ->{
            wq.eq("bas.`status`","0")
                    .or()
                    .eq("bas.`status`","5");
        });

        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("c.id", dto.getWareHouseType());
        }

        //生产日期
        if (dto.getProduceDate() != null) {
            queryWrapper.eq("a.produce_date", dto.getProduceDate());
        }

        if (StringUtils.isNotEmpty(dto.getSupplierId())) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getSupplierId, dto.getSupplierId()));
            if (CollectionUtil.isNotEmpty(wareHouseDetaileds)) {
                List<String> containsIds = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(containsIds)) {
                    queryWrapper.in("a.id", containsIds);
                } else {
                    return new Page<>();
                }
            } else {
                return new Page<>();
            }
        }
        IPage<PsiWareHouseDto> wareHouseDtoIPage = basicMapper.getByProduceDateNotMerge(page, queryWrapper);
        wareHouseDtoIPage.getRecords().forEach(item -> {
            // 将小数点后无效的0删除
            // 总量  格式化
            if (StringUtils.isNotBlank(item.getAllNumber())) {
                String s = convertByBigDecimal(item.getAllNumber());
                item.setAllNumber(s);
            }
            //领用量  格式化
            if (StringUtils.isNotBlank(item.getBorrowNumber())) {
                String s = convertByBigDecimal(item.getBorrowNumber());
                item.setBorrowNumber(s);
            }
            //剩余量  格式化
            if (StringUtils.isNotBlank(item.getTradeNumber())) {
                String s = convertByBigDecimal(item.getTradeNumber());
                item.setTradeNumber(s);
            }
            //提醒数量  格式化
            if (StringUtils.isNotBlank(item.getWarnNum())) {
                String s = convertByBigDecimal(item.getWarnNum());
                item.setWarnNum(s);
            }
        });
        return wareHouseDtoIPage;
    }


    public IPage<PsiWareHouseDto> getAllData(Page<PsiWareHouseDto> page , PsiWareHouseDto dto) throws Exception{
        QueryWrapper<PsiWareHouseDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, PsiWareHouseDto.class);

        queryWrapper.eq("a.del_flag", "0");

        if (StringUtils.isNotEmpty(dto.getTradeName())) {
            queryWrapper.like("a.trade_name", dto.getTradeName());
        }
        queryWrapper.and(wq ->{
            wq.eq("bas.`status`","0")
                    .or()
                    .eq("bas.`status`","5");
        });

        //入库类型
        if (StringUtils.isNotEmpty(dto.getWareHouseType())) {
            queryWrapper.eq("c.id", dto.getWareHouseType());
        }

        //生产日期
        if (dto.getProduceDate() != null) {
            queryWrapper.eq("a.produce_date", dto.getProduceDate());
        }

        if (StringUtils.isNotEmpty(dto.getSupplierId())) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.selectList(new LambdaQueryWrapper<PsiWareHouseDetailed>().eq(PsiWareHouseDetailed::getSupplierId, dto.getSupplierId()));
            if (CollectionUtil.isNotEmpty(wareHouseDetaileds)) {
                List<String> containsIds = wareHouseDetaileds.stream().map(PsiWareHouseDetailed::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(containsIds)) {
                    queryWrapper.in("a.id", containsIds);
                } else {
                    return new Page<>();
                }
            } else {
                return new Page<>();
            }
        }
        LocalDate today = LocalDate.now(ZoneId.systemDefault());
        IPage<PsiWareHouseDto> wareHouseDtoIPage = basicMapper.getAllData(page, queryWrapper);
        wareHouseDtoIPage.getRecords().forEach(item -> {
            // 将小数点后无效的0删除
            // 总量  格式化
            if (StringUtils.isNotBlank(item.getAllNumber())) {
                String s = convertByBigDecimal(item.getAllNumber());
                item.setAllNumber(s);
            }
            //领用量  格式化
            if (StringUtils.isNotBlank(item.getBorrowNumber())) {
                String s = convertByBigDecimal(item.getBorrowNumber());
                item.setBorrowNumber(s);
            }
            //剩余量  格式化
            if (StringUtils.isNotBlank(item.getTradeNumber())) {
                String s = convertByBigDecimal(item.getTradeNumber());
                item.setTradeNumber(s);
            }
            //提醒数量  格式化
            if (StringUtils.isNotBlank(item.getWarnNum())) {
                String s = convertByBigDecimal(item.getWarnNum());
                item.setWarnNum(s);
            }

            if (!canCheckNearExpiry(item)) {
                return;
            }
            Integer shelfLifeValue = parseShelfLifeValue(item.getShelfLife());
            if (shelfLifeValue == null) {
                return;
            }
            LocalDate produceDate = toLocalDate(item.getProduceDate());
            LocalDate expiryDate = calculateExpiryDate(produceDate, shelfLifeValue, item.getShelfLifeUnit());
            if (expiryDate == null) {
                return;
            }
            long totalDays = ChronoUnit.DAYS.between(produceDate, expiryDate);
            long remainingDays = ChronoUnit.DAYS.between(today, expiryDate);
            item.setExpiryDate(Date.from(expiryDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            item.setRemainingDays((int) remainingDays);
        });
        return wareHouseDtoIPage;
    }


    // 四舍五入最多保留小数点后四位，并去除末尾无效的0
    public String convertByBigDecimal(String value) {
        BigDecimal bigDecimal = new BigDecimal(value);
        BigDecimal res = bigDecimal.setScale(4, RoundingMode.HALF_UP).stripTrailingZeros();
        return res.toPlainString();
    }

    public String findRequestId(String purchaseNo) {
        return basicMapper.findRequestId(purchaseNo);
    }

    public String updateStatusById(PsiWareHouseDto dto) {
        PsiWareHouseBasic wareHouseBasic = new PsiWareHouseBasic();
        BeanUtils.copyProperties(dto,wareHouseBasic);
        basicMapper.update(wareHouseBasic, new QueryWrapper<PsiWareHouseBasic>().lambda().eq(PsiWareHouseBasic::getId, wareHouseBasic.getId()));
        return "操作成功";
    }

    // 根据入库表id查询其全部历史修改数据
    public List<PsiWarehouseUpHi> findHiById(String warehouseId) {
        return psiWarehouseUpHiMapper.findHiById(warehouseId);
    }

    // 根据历史表id查询历史表数据
    public PsiWareHouseDto findHiByHiId(String hiId) {
        PsiWareHouseDto wareHouseDto = new PsiWareHouseDto();
        PsiWarehouseUpHi hiByHiId = psiWarehouseUpHiMapper.findHiByHiId(hiId); // 根据历史表id查询历史表数据
        if (ObjectUtil.isNotEmpty(hiByHiId) && StringUtils.isNotBlank(hiByHiId.getJsonData())) {
            wareHouseDto = JSON.parseObject(hiByHiId.getJsonData(), PsiWareHouseDto.class); // json字符串解析为java对象
            if (ObjectUtil.isNotEmpty(wareHouseDto)) {
                // 入库详情中的附件数据获取。
                // 在这里要重新获取一下入库详情附件的原因是，json字符串中的附件createBy值存储不正确，所以重新获取一下
                if(CollectionUtil.isNotEmpty(wareHouseDto.getWareHouse())) {
                    wareHouseDto.getWareHouse().forEach(detailed->{
                        List<WorkAttachmentDto> acList = psiDetailedMapper.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(wareHouseDto.getFiles())) {
                    wareHouseDto.getFiles().forEach(file->{
                        file.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(file.getBy()));
                    });
                }
            }

        }
        return wareHouseDto;
    }

    // 根据入库表id查询最近的一个修改历史
    public PsiWareHouseDto findLastHiByid(String warehouseId) {
        PsiWareHouseDto wareHouseDto = new PsiWareHouseDto();
        PsiWarehouseUpHi hiByHiId = psiWarehouseUpHiMapper.findLastHiByid(warehouseId); // 根据入库表id查询最近的一个修改历史
        if (ObjectUtil.isNotEmpty(hiByHiId) && StringUtils.isNotBlank(hiByHiId.getJsonData())) {
            wareHouseDto = JSON.parseObject(hiByHiId.getJsonData(), PsiWareHouseDto.class); // json字符串解析为java对象
            if (ObjectUtil.isNotEmpty(wareHouseDto)) {
                // 入库详情中的附件数据获取。
                // 在这里要重新获取一下入库详情附件的原因是，json字符串中的附件createBy值存储不正确，所以重新获取一下
                if(CollectionUtil.isNotEmpty(wareHouseDto.getWareHouse())) {
                    wareHouseDto.getWareHouse().forEach(detailed->{
                        List<WorkAttachmentDto> acList = psiDetailedMapper.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(wareHouseDto.getFiles())) {
                    wareHouseDto.getFiles().forEach(file->{
                        file.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(file.getBy()));
                    });
                }
            }
        }
        return wareHouseDto;
    }

    // 根据商品名称和入库类型修改提醒状态
    public ResponseEntity updateWarnFlagByTradeNameAndType(PsiWareHouseDto wareHouseDto) {
        if (ObjectUtil.isNotEmpty(wareHouseDto.getTradeName()) && StringUtils.isNotBlank(wareHouseDto.getWareHouseType())) {
            // 查询此数据的状态
            List<PsiWareHouseDto> wareHouseDtoList = basicMapper.getByTypeAndTradeName(wareHouseDto.getTradeName(),wareHouseDto.getWareHouseType());
            if (CollectionUtil.isNotEmpty(wareHouseDtoList)) {
                if ("1".equals(wareHouseDtoList.get(0).getWarnFlag())) { // 当前状态为启用
                    basicMapper.updateWarnFlagByTradeNameAndType("0", wareHouseDto.getTradeName(), wareHouseDto.getWareHouseType()); // 设置为停用
                    return ResponseEntity.ok("修改提醒状态成功");
                } else if ("0".equals(wareHouseDtoList.get(0).getWarnFlag())) { // 当前状态为停用
                    basicMapper.updateWarnFlagByTradeNameAndType("1", wareHouseDto.getTradeName(), wareHouseDto.getWareHouseType()); // 设置为启用
                    return ResponseEntity.ok("修改提醒状态成功");
                }
            }
        }
        return ResponseEntity.badRequest().body("修改提醒状态失败");
    }


    // 根据商品名称和入库类型修改提醒数量
    public ResponseEntity updateWarnNumByTradeNameAndType(PsiWareHouseDto wareHouseDto) {
        if (ObjectUtil.isNotEmpty(wareHouseDto.getTradeName()) && StringUtils.isNotBlank(wareHouseDto.getWareHouseType())) {
            if (StringUtils.isNotBlank(wareHouseDto.getWarnNum())) {
                // 查询此数据的状态
                List<PsiWareHouseDto> wareHouseDtoList = basicMapper.getByTypeAndTradeName(wareHouseDto.getTradeName(),wareHouseDto.getWareHouseType());
                if (CollectionUtil.isNotEmpty(wareHouseDtoList)) {
                    if (wareHouseDto.getWarnNum().equals(wareHouseDtoList.get(0).getWarnNum())) { // 如果查询到的提醒数量与修改的提醒数量相同则直接返回修改成功
                        return ResponseEntity.ok("修改提醒数量成功");
                    } else { // 如果查询到的提醒数量与修改的提醒数量不相同则修改提醒数量
                        basicMapper.updateWarnNumByTradeNameAndType(wareHouseDto.getWarnNum(), wareHouseDto.getTradeName(), wareHouseDto.getWareHouseType()); // 修改提醒数量
                        return ResponseEntity.ok("修改提醒数量成功");
                    }
                }
            }
        }
        return ResponseEntity.badRequest().body("修改提醒数量失败");
    }

    public void saveTradeName (PsiWareHouseDto wareHouseDto) {
        if (ObjectUtil.isNotEmpty(wareHouseDto)) {
            if (StringUtils.isNotBlank(wareHouseDto.getOldTradeName()) && StringUtils.isNotBlank(wareHouseDto.getTradeName()) && StringUtils.isNotBlank(wareHouseDto.getWareHouseType())) {
                // 修改入库详情 商品名称
                psiDetailedMapper.saveTradeName(wareHouseDto.getOldTradeName(), wareHouseDto.getTradeName(), wareHouseDto.getWareHouseType());
                // 修改领用详情 商品名称
                psiDetailedMapper.saveGoodsName(wareHouseDto.getOldTradeName(), wareHouseDto.getTradeName(), wareHouseDto.getWareHouseType());
            }
        }
    }

    public List<PsiWareHouseDetailed> findTradeByTypeId (String typeId) {
        if (StringUtils.isNotBlank(typeId)) {
            List<PsiWareHouseDetailed> wareHouseDetaileds = psiDetailedMapper.getByTypeId(typeId);
            return wareHouseDetaileds;
        } else {
            return new ArrayList<>();
        }
    }
}
