package com.shinsoft.sto.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinsoft.frameworkapi.model.SysDepartment;
import com.shinsoft.frameworkapi.model.SysUser;
import com.shinsoft.frameworkapi.service.FrameworkService;
import com.shinsoft.sto.mapper.OnhandMapper;
import com.shinsoft.sto.mapper.TransRecordMapper;
import com.shinsoft.sto.model.*;
import com.shinsoft.sto.service.TransRecordService;
import com.shinsoft.tools.JSONTools;
import com.shinsoft.tools.model.common.ResultJSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 库存变更记录表 服务实现类
 * </p>
 *
 * @author system
 * @since 2024-09-30
 */
@Service
public class TransRecordServiceImp extends ServiceImpl<TransRecordMapper, TransRecord> implements TransRecordService {

    private static final List<String> transactionTypeList = new ArrayList<>();

    static {
        Collections.addAll(transactionTypeList, "A1", "A2", "A3", "A4", "A5", "A6", "A7", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "C1", "C2" , "B8");
    }

    ResultJSON resultJSON;

    @Autowired
    TransRecordMapper transRecordMapper;
    @Autowired
    private OnhandMapper onhandMapper;

    @Autowired
    FrameworkService frameworkService;
//    @Autowired
//    SalService salService;


    @Override
    public ResultJSON query(int page, int rows, String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        String transactionDate = jsonObject.getString("transactionDate");
        String storeNm = jsonObject.getString("storeNm");
        String itemNm = jsonObject.getString("itemNm");
        String itemType = jsonObject.getString("itemType");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(transactionDate)) {
            // 将字符串解析为 List
            List<String> dateList = JSON.parseArray(transactionDate, String.class);
            if (dateList != null && dateList.size() == 2) {
                try {
                    startTime = dateFormat.parse(dateList.get(0)); // 开始时间
                    endTime = dateFormat.parse(dateList.get(1));   // 结束时间
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        Page<TransRecord> page1 = new Page<>(page, rows);
//        QueryWrapper<TransRecord> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("cancel_flag", "0");
//        queryWrapper.eq(StringUtils.isNotBlank(storeNm),"store_nm", storeNm);
//        queryWrapper.eq(StringUtils.isNotBlank(itemNm),"item_nm", storeNm);
//        queryWrapper.eq(StringUtils.isNotBlank(itemType),"store_type", storeNm);

//        Page<TransRecord> list = transRecordMapper.selectPage(onhandPage, queryWrapper);
        Page<TransRecord> list = transRecordMapper.selectList(page1, storeNm, itemNm, itemType, startTime, endTime);
        resultJSON = JSONTools.toResultJSON(list);
        return resultJSON;
    }

    @Override
    public ResultJSON queryByPK(String id) {
        TransRecord transRecord = transRecordMapper.selectByPK(id);
        resultJSON = JSONTools.toResultJSON(transRecord);
        return resultJSON;
    }


    /**
     * 修改 库存现有量，并添加库存变更记录
     * 根据  不同的业务类型
     *
     * @param json
     * @return
     */
    @Override
    @Transactional
    public ResultJSON add(String userId, String json) {
        // todo
        // A1 采购入库
        // A2 采购出库  (采购退库）
        // A3 生产完工 (生产入库)
        // A4 生产完工退回
        // A5 副产品完工
        // A6 副产品完工退回
        // A7 盘盈


        // todo
        // B1 销售发货 (销售出库)
        // B2 销售退回 (销售出库退回)
        // B3 生产投料
        // B4 生产退料
        // B5 库房 入 料  (倒库 增加)
        // B6 库房 退 料 (倒库 减少)
        // B7 盘亏
        // B8 领用（ - ）

        // todo
        // C1 调拨入
        // C2 调拨出


        // 先 入记录，STO_TRANS_RECORD
        // 再修改 库存 STO_ONHAND
        Date date = new Date();
        TransRecord transRecord = JSON.parseObject(json, new TypeReference<TransRecord>() {
        });
        //此处判断必传参数是否为空
        if (!ifNUllRequired(transRecord)) {
            throw new RuntimeException("必填参数不能为空");
        }
        if (ObjectUtils.isEmpty(transRecord.getUom())){
            transRecord.setUom("ton");
        }
        if (StringUtils.isEmpty(userId)) {
            userId = transRecord.getUserId();
        }
        // 传userId
        ResultJSON userInfoRes = frameworkService.queryUserInfoById(userId, "");
        SysUser user = null;
        List<SysDepartment> deptTreeList = null;
        List<SysDepartment> deptsList = null;
        if (userInfoRes.getCode() == 0) {
            Map<String, Object> mapInfo = JSON.parseObject(userInfoRes.getData().toString(), new TypeReference<Map<String, Object>>() {
            });
            if (!ObjectUtils.isEmpty(mapInfo.get("user"))) {
                user = JSON.parseObject(mapInfo.get("user").toString(), new TypeReference<SysUser>() {
                });
            }

            deptTreeList = JSON.parseArray(mapInfo.get("deptTree").toString(), SysDepartment.class);
            deptsList = JSON.parseArray(mapInfo.get("depts").toString(), SysDepartment.class);
        }

        if (!CollectionUtils.isEmpty(deptTreeList)) {
            transRecord.setCompCd(deptTreeList.get(0).getDeptCode());
        }

        if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
            transRecord.setAddCode(user.getUserCode());
            transRecord.setAddName(user.getUserDesc());
        }
        if (!CollectionUtils.isEmpty(deptsList)) {
            transRecord.setDeptCd(deptsList.get(0).getDeptCode());
//            transRecord.setDeptNm(deptsList.get(0).getDeptName());
            transRecord.setAddDeptId(deptsList.get(0).getId());
            transRecord.setAddDeptName(deptsList.get(0).getDeptName());
            transRecord.setAddDeptCode(deptsList.get(0).getDeptCode());
        }

        transRecord.setCancelFlag("0");
        transRecord.setAddId(userId);
        transRecord.setAddTime(date);

        String type = transRecord.getTransactionType();

        //判断业务类型是否存在
        if (!transactionTypeList.contains(type)) {
            resultJSON = JSONTools.toResultJSON(500, "业务类型:" + type + "不存在");
            return resultJSON;
        }


        boolean flag = true;
        //判断特有参数是否存在
        switch (type) {
            case "A2":
                break;
            case "A1":
                flag = (transRecord.getPurOrdLn() != null && transRecord.getPurOrdNo() != null && transRecord.getTradePartnerName() != null);
                break;
            case "A3":
                break;
            case "A4":
                break;
            case "A5":
                break;
            case "A6":
                flag = (transRecord.getTradePartnerId() != null && transRecord.getTradePartnerCode() != null);
                break;
            case "B3":
                break;
            case "B4":
                flag = (transRecord.getPrdPlanNo() != null);
                break;
            case "B1":
                break;
            case "B2":
                flag = ((transRecord.getTradePartnerId() != null || transRecord.getTradePartnerCode() != null) && transRecord.getTradePartnerName() != null);
                break;
            default:
                break;
        }

        if (!flag) {
            resultJSON = JSONTools.toResultJSON(500, "业务类型:" + type + "，的专用参数不存在。比如，A1采购入库，那purOrdLn、purOrdNo、tradepartnerName是必须有参数传递的！");
            return resultJSON;
        }
        if (transRecord.getQty().compareTo(BigDecimal.valueOf(0)) == 0) {
            resultJSON = JSONTools.toResultJSON(500, "qty库存现有量不能为0，请调整。");

            return resultJSON;

        }


        //  库存修改 STO_ONHAND
        QueryWrapper<Onhand> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("CANCEL_FLAG", "0");
        objectQueryWrapper.eq("ITEM_CD", transRecord.getItemCd());
//        objectQueryWrapper.eq("ITEM_NM", transRecord.getItemNm());
        objectQueryWrapper.eq("STORE_CD", transRecord.getStoreCd());
//        objectQueryWrapper.eq("STORE_NM", transRecord.getStoreNm());
        if (!ObjectUtils.isEmpty(transRecord.getAreaCd())) {
            objectQueryWrapper.eq("AREA_CD", transRecord.getAreaCd());
        }
//        else {
//            objectQueryWrapper.isNull("AREA_CD");
//        }
        if (!ObjectUtils.isEmpty(transRecord.getStackCd())) {
            objectQueryWrapper.eq("STACK_CD", transRecord.getStackCd());
        }
//        else {
//            objectQueryWrapper.isNull("STACK_CD");
//        }

        String[] add = new String[]{"A1", "A3", "A5", "A7", "B2", "B4", "B5", "C1"};
        String[] subtract = new String[]{"A2", "A4", "A6", "B1", "B3", "B6", "B7", "C2" , "B8"};

        List<Onhand> onhand1 = onhandMapper.selectList(objectQueryWrapper);
        boolean typeAdd = Arrays.asList(add).contains(type);

        if (typeAdd) {
            // 此操作为， 入， 进行库存现有量的 增加
            if (!CollectionUtils.isEmpty(onhand1)) {
                // 库存现有量不为空， 进行  增加 操作
                BigDecimal qty = onhand1.get(0).getQty();
                BigDecimal qtyWet = onhand1.get(0).getQtyWet();
                if (ObjectUtils.isEmpty(qtyWet)) {
                    qtyWet = BigDecimal.valueOf(0);
                }

                BigDecimal transRecordQty = transRecord.getQty();
                BigDecimal transRecordQtyWet = transRecord.getQtyWet();
                if (ObjectUtils.isEmpty(transRecordQtyWet)) {
                    transRecordQtyWet = BigDecimal.valueOf(0);
                }

//                BigDecimal qtyBig = qty;
//                BigDecimal recordqtyBig = transRecordQty;


                onhand1.get(0).setQty(qty.add(transRecordQty));
                if (ObjectUtils.isEmpty(transRecordQtyWet)) {
                    transRecordQtyWet = BigDecimal.valueOf(0);
                }

                onhand1.get(0).setQtyWet(qtyWet.add((transRecordQtyWet)));

                onhand1.get(0).setModifyId(userId);
                onhand1.get(0).setModifyTime(date);
                if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
                    onhand1.get(0).setModifyCode(user.getUserCode());
                    onhand1.get(0).setLastName(user.getUserDesc());
                    onhand1.get(0).setModifyName(user.getUserDesc());
                }
                onhand1.get(0).setLastTime(date);
                if (!StringUtils.isEmpty(transRecord.getRemarksOnhand())) {
                    onhand1.get(0).setRemarks(transRecord.getRemarksOnhand());
                }
                onhandMapper.updateById(onhand1.get(0));
            } else {
                // 库存现有量 不存在， 进行 新增操作
                Onhand onhand = new Onhand();

                onhand.setCancelFlag("0");
                onhand.setAddId(userId);
                onhand.setAddTime(date);

                onhand.setItemCd(transRecord.getItemCd());
                onhand.setItemNm(transRecord.getItemNm());
                onhand.setStoreCd(transRecord.getStoreCd());
                onhand.setStoreNm(transRecord.getStoreNm());
                onhand.setAreaCd(transRecord.getAreaCd());
                onhand.setStackCd(transRecord.getStackCd());
                onhand.setQty(transRecord.getQty());
                onhand.setQtyWet(transRecord.getQtyWet());
                onhand.setUom(transRecord.getUom());
                onhand.setRemarks(transRecord.getRemarks());

                if (!CollectionUtils.isEmpty(deptTreeList)) {
                    onhand.setCompCd(deptTreeList.get(0).getDeptCode());
                }

                if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
                    onhand.setAddCode(user.getUserCode());
                    onhand.setAddName(user.getUserDesc());
                }
                if (!CollectionUtils.isEmpty(deptsList)) {
                    onhand.setDeptCd(deptsList.get(0).getDeptCode());
                    onhand.setAddDeptId(deptsList.get(0).getId());
                    onhand.setAddDeptName(deptsList.get(0).getDeptName());
                    onhand.setAddDeptCode(deptsList.get(0).getDeptCode());
                }
                if (!StringUtils.isEmpty(transRecord.getRemarksOnhand())) {
                    onhand.setRemarks(transRecord.getRemarksOnhand());
                }
                onhandMapper.insert(onhand);

            }

        } else {
            // 此操作为， 出， 进行库存现有量的 减少
            if (!CollectionUtils.isEmpty(onhand1)) {
                // 库存现有量不为空， 进行  减少 操作
                BigDecimal qty = onhand1.get(0).getQty();
                BigDecimal qtyWet = onhand1.get(0).getQtyWet();
                if (ObjectUtils.isEmpty(qtyWet)) {
                    qtyWet = BigDecimal.valueOf(0);
                }

                BigDecimal transRecordQty = transRecord.getQty();
                BigDecimal transRecordQtyWet = transRecord.getQtyWet();
                if (ObjectUtils.isEmpty(transRecordQtyWet)) {
                    transRecordQtyWet = BigDecimal.valueOf(0);
                }
                if (transRecordQty.compareTo(qty) > 0) {
                    throw new RuntimeException("超过当前库存现有量，操作失败！");
//                    resultJSON = JSONTools.toResultJSON(500,"超过当前库存现有量，操作失败！");
//                    return resultJSON;
                }

                onhand1.get(0).setQty(qty.subtract(transRecordQty));
                onhand1.get(0).setQtyWet(qtyWet.subtract(transRecordQtyWet));

                onhand1.get(0).setModifyId(userId);
                onhand1.get(0).setModifyTime(date);
                if (!org.apache.commons.lang3.ObjectUtils.isEmpty(user)) {
                    onhand1.get(0).setModifyCode(user.getUserCode());
                    onhand1.get(0).setLastName(user.getUserDesc());
                    onhand1.get(0).setModifyName(user.getUserDesc());
                }
                onhand1.get(0).setLastTime(date);
                if (!StringUtils.isEmpty(transRecord.getRemarksOnhand())) {
                    onhand1.get(0).setRemarks(transRecord.getRemarksOnhand());
                }
                onhandMapper.updateById(onhand1.get(0));
                transRecord.setQty(transRecordQty.negate());
                transRecord.setQtyWet(transRecordQtyWet.negate());
            } else {
                // 库存现有量 不存在，无法进行 减少操作
                throw new RuntimeException("库存现有量不存在，无法进行减少操作！");
//                resultJSON = JSONTools.toResultJSON(500,"库存现有量不存在，无法进行减少操作！");
//                return resultJSON;
            }

        }
        //  库存变更记录 STO_TRANS_RECORD
        transRecordMapper.insert(transRecord);

        resultJSON = JSONTools.toResultJSON(transRecord);
        return resultJSON;
    }

    /**
     * 查询库存现有量表
     *
     * @param havingMap
     * @return
     */
    private boolean ifHaving(Map<String, Object> havingMap) {
        OnHandVO onHandVO = transRecordMapper.queryOne(havingMap);
        return onHandVO != null;
    }

    /**
     * 判断必选参数是否为空
     *
     * @param transRecord
     * @return
     */
    private static boolean ifNUllRequired(TransRecord transRecord) {

        return transRecord.getCompCd() != null &&
                transRecord.getDeptCd() != null &&
                transRecord.getItemCd() != null &&
                transRecord.getItemNm() != null &&
//                transRecord.getItemType() != null &&
                transRecord.getQty() != null &&
//                transRecord.getUom() != null &&
                transRecord.getStoreCd() != null &&
                transRecord.getTransactionType() != null &&
                transRecord.getTransactionDate() != null &&
                transRecord.getTransactionTable() != null &&
                transRecord.getTransactionId() != null;
    }

    /**
     * 获取添加信息
     *
     * @param tName 表名
     * @param tId   表里面的id
     * @return
     */
    public TransRecordAddInfo getAddInfo(String tName, String tId) {
        TransRecordAddInfo transRecordAddInfo = new TransRecordAddInfo();

        Map<String, String> map = new HashMap<>();
        map.put("tName", tName);
        map.put("tId", tId);
        transRecordAddInfo = transRecordMapper.selectAddInfoByTId(map);
        return transRecordAddInfo;
    }


    @Override
    public ResultJSON remove(String userId, String id) {
        Date date = new Date();
        TransRecord transRecord = transRecordMapper.selectById(id);
        transRecord.setCancelFlag("1");
        transRecord.setCancelId(userId);
        transRecord.setCancelTime(date);
        transRecordMapper.updateById(transRecord);
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }


    @Override
    public ResultJSON removeBatch(String userId, String ids) {
        Date date = new Date();
        List<String> list = JSON.parseObject(ids, new TypeReference<List<String>>() {
        });
        TransRecord transRecord;
        for (String id : list) {
            transRecord = transRecordMapper.selectById(id);
            transRecord.setCancelFlag("1");
            transRecord.setCancelId(userId);
            transRecord.setCancelTime(date);
            transRecordMapper.updateById(transRecord);
        }
        resultJSON = JSONTools.toResultJSON("");
        return resultJSON;
    }

    @Override
    public ResultJSON queryWlsfc(int page, int rows, String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        Page<TransRecordWlsfc> transRecordWlsfcPage = new Page<>(page, rows);
        String itemNm = "";
        String storeNm = "";
        String startDate = null;
        String endDate = null;
        LocalDate tomorrow = LocalDate.now().plusDays(1);

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 格式化日期
        String todayDate = tomorrow.format(formatter);
//        String todayDate =new SimpleDateFormat("yyyy-MM-dd").format( new Date());
        if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(jsonObject.get("date"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("date");
            if (!CollectionUtils.isEmpty(jsonArray)) {
                startDate = jsonArray.getString(0);
                endDate = jsonArray.getString(1);
            }
        }
        if (startDate == null || endDate == null) {
            resultJSON = JSONTools.toResultJSON(500, "日期为空，查询失败！");
            return resultJSON;
        }

        // 时间开始 到  时间结束
        Map<String, Object> map = new HashMap<>();
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("itemNm", itemNm);
        map.put("storeNm", storeNm);

        IPage<TransRecordWlsfc> trsList = transRecordMapper.queryWlsfc(transRecordWlsfcPage, map);
        List<TransRecordWlsfc> records = trsList.getRecords();
        long total = trsList.getTotal();
        if (CollectionUtils.isEmpty(records)) {
            resultJSON = JSONTools.toResultJSON(trsList);
            return resultJSON;
        }


        // 时间开始 到 今天
        Map<String, Object> mapStart = new HashMap<>();
        mapStart.put("startDate", startDate);
        mapStart.put("endDate", todayDate);
        mapStart.put("itemNm", itemNm);
        mapStart.put("storeNm", storeNm);
        IPage<TransRecordWlsfc> qcList = transRecordMapper.queryWlsfc(transRecordWlsfcPage, mapStart);
        List<TransRecordWlsfc> records2 = qcList.getRecords();

        // 时间结束 到 今天
        Map<String, Object> mapEnd = new HashMap<>();
        mapEnd.put("startDate", endDate);
        mapEnd.put("endDate", todayDate);
        mapEnd.put("itemNm", itemNm);
        mapEnd.put("storeNm", storeNm);
        IPage<TransRecordWlsfc> qmList = transRecordMapper.queryWlsfc(transRecordWlsfcPage, mapEnd);
        List<TransRecordWlsfc> records3 = qmList.getRecords();

        // 库房
        List<String> list = new ArrayList<>();
        List<String> itemlist = new ArrayList<>();
        for (TransRecordWlsfc record : records) {
            list.add(record.getStoreCd());

            itemlist.add(record.getItemCd());
        }

        List<Onhand> onhands = onhandMapper.getSumList(list, itemlist);

        // 期初
        for (TransRecordWlsfc record : records2) {
            for (Onhand onhand : onhands) {
                if (record.getStoreCd().equals(onhand.getStoreCd()) && record.getItemCd().equals(onhand.getItemCd())) {
                    // 收
                    BigDecimal addQty = record.getAddQty();
                    // 出
                    BigDecimal subtractQty = record.getSubtractQty();
                    BigDecimal add = addQty.add(subtractQty);
                    BigDecimal qty = onhand.getQty();
                    BigDecimal subtract = qty.subtract(add);
                    record.setQcQty(subtract);
                    break;
                }
            }
        }

        // 期末
        for (TransRecordWlsfc record : records3) {
            for (Onhand onhand : onhands) {
                if (record.getStoreCd().equals(onhand.getStoreCd()) && record.getItemCd().equals(onhand.getItemCd())) {
                    // 收
                    BigDecimal addQty = record.getSubtractQty();
                    // 出
                    BigDecimal subtractQty = record.getSubtractQty();
                    BigDecimal add = addQty.add(subtractQty);
                    record.setQmQty(add);
                    break;
                }
            }
        }

        for (TransRecordWlsfc record : records) {
            for (TransRecordWlsfc reco : records2) {
                if (record.getStoreCd().equals(reco.getStoreCd()) && record.getItemCd().equals(reco.getItemCd())) {
                    record.setQcQty(reco.getQcQty());
                    break;
                }
            }
        }
        long endtime = 0l;
        long todaytime = 0l;
        try {
            endtime = new SimpleDateFormat("yyyy-MM-dd").parse(endDate).getTime();
            todaytime = new SimpleDateFormat("yyyy-MM-dd").parse(todayDate).getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if (endtime >= todaytime) {
            for (TransRecordWlsfc record : records) {
                for (Onhand onhand : onhands) {
                    if (record.getStoreCd().equals(onhand.getStoreCd()) && record.getItemCd().equals(onhand.getItemCd())) {
                        record.setQmQty(onhand.getQty());
                    }
                }
            }
        } else {
            for (TransRecordWlsfc record : records) {
                for (TransRecordWlsfc reco : records3) {
                    if (record.getStoreCd().equals(reco.getStoreCd()) && record.getItemCd().equals(reco.getItemCd())) {
                        record.setQmQty(reco.getQmQty());
                        break;
                    }
                }
            }
        }

        trsList.setRecords(records);
        trsList.setTotal(total);
        resultJSON = JSONTools.toResultJSON(trsList);

        return resultJSON;
    }

    @Override
    public ResultJSON queryHistory(int page, int rows, String params) {
        JSONObject jsonObject = JSON.parseObject(params);
        String transactionDate = jsonObject.getString("transactionDate");
        String storeNm = jsonObject.getString("storeNm");
        String itemType = jsonObject.getString("itemType");
        String areaCd = jsonObject.getString("areaCd");
        String stackCd = jsonObject.getString("stackCd");
        String itemNm = jsonObject.getString("itemNm");
        Page<TransRecord> page1 = new Page<>(page, rows);
        Date transacation_date = null;
        Date todayDate = new Date();

        LocalDate today = LocalDate.now();
        // 获取本周周一的日期
        LocalDate monday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDateTime localDateTime = monday.atStartOfDay();
        Date mondayDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(mondayDate);

        if (StringUtils.isEmpty(transactionDate)) {
            transactionDate = format;
        }
        try {
            transacation_date = dateFormat.parse(transactionDate);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 变化数据
        Page<HashMap<String, Object>> list = transRecordMapper.selectSum(page1, transacation_date, todayDate,storeNm, itemType, areaCd, stackCd,itemNm);
        Page<Onhand> page2 = new Page<>(page, rows);
        Page<Onhand> onhands = onhandMapper.selectOnhand(page2,storeNm, itemType, areaCd, stackCd,itemNm);
//        List<Onhand> onhands = onhandMapper.selectList(queryWrapper1);
        List<HashMap<String, Object>> list1 = new ArrayList<>();

        // 打印重复项以供调试
        onhands.getRecords().stream()
                .collect(Collectors.groupingBy(onhand -> onhand.getStoreCd() + "_" + onhand.getAreaCd() + "_" + onhand.getStackCd()))
                .forEach((key, value) -> {
                    if (value.size() > 1) {
                        System.out.println("重复键: " + key + ", 对应的值: " + value);
                    }
                });

        // 转换为 Map，保留后一个对象
        Map<String, Onhand> onhandMap = onhands.getRecords().stream().collect(Collectors.toMap(
                onhand -> onhand.getStoreCd() + "_" + onhand.getAreaCd() + "_" + onhand.getStackCd() + "_" + onhand.getItemCd(),
                onhand -> onhand,
                (existing, replacement) -> replacement // 合并策略: 保留后一个
        ));

        for (HashMap<String, Object> map : list.getRecords()) {
            String key = map.get("STORE_CD") + "_" + map.get("AREA_CD") + "_" + map.get("STACK_CD") + "_" + map.get("ITEM_CD");
            Onhand onhand = onhandMap.get(key);
            if (onhand != null) {
                HashMap<String, Object> map1 = new HashMap<>();
                BigDecimal totalqty = map.get("TOTALQTY") instanceof BigDecimal
                        ? (BigDecimal) map.get("TOTALQTY")
                        : new BigDecimal(map.get("TOTALQTY").toString());
                BigDecimal qty = onhand.getQty();
                BigDecimal kucun = qty.subtract(totalqty);

                map1.put("ITEM_NM", map.get("ITEM_NM"));
                map1.put("STORE_NM", map.get("STORE_NM"));
                map1.put("KUCUN", kucun);
                map1.put("STACK_CD", map.get("STACK_CD"));
                map1.put("AREA_CD", map.get("AREA_CD"));
                list1.add(map1);
            }
            onhandMap.remove(key);
        }
        // 添加剩余的记录
        for (Onhand onhand : onhandMap.values()) {
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("ITEM_NM", onhand.getItemNm());
            map1.put("STORE_NM", onhand.getStoreNm());
            map1.put("KUCUN", onhand.getQty());
            map1.put("STACK_CD", onhand.getStackCd());
            map1.put("AREA_CD", onhand.getAreaCd());
            list1.add(map1);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("data", list1);
        result.put("totalRows", onhands.getTotal());
        resultJSON = JSONTools.toResultJSON(result);
        return resultJSON;
    }

    @Override
    public ResultJSON test(String userId,String params) {
        Date date = new Date();
        JSONObject map = new JSONObject();
        map.put("compCd", "D01");  // 公司
        map.put("deptCd", "D012301");  // 公司
        map.put("itemCd", "20201000004");  // 物料编码
        map.put("itemNm", "50%粉矿"); // 物料名称
//        map.put("itemType", "固体");
        map.put("qty", "100");// 重量
        map.put("uom", "wet ton");// 单位
        map.put("storeCd", "D0100001"); // 库房编码
        map.put("storeNm", "原料北库");// 库房名称
        map.put("areaCd", "");// 区号
        map.put("stackCd", "");// 垛位
        map.put("qtyWet", "");// 湿基量
        map.put("transactionId", "1111111111111");// 操作的表Id
        map.put("transactionTable", "SAL_DELV;JHY"); // 操作的表名称
        map.put("transactionDate", date);// 时间
        map.put("transactionType", "B1");// 业务类型
        map.put("userId", userId); // 用户id
        map.put("contrNo", "HT1000001");// 合同编号
        map.put("khContrNo", "HT1000001");// 对方合同编号
        map.put("drodNo", "");// 出货指示号
        map.put("tradePartnerId", "");// 客户ID
        map.put("tradePartnerCode", "");// 客户编码
        map.put("tradePartnerName", "");// 客户名称
        map.put("specType", "");// 规格型号
        map.put("carNo", "");// 车号
        map.put("stoOutDt", date);// 出库时间
        map.put("outFacYn", "1");// 是否出厂   1是  0 否
        map.put("transSci", "1");// 是否有检化验出厂检验结果   1是  0 否
        map.put("transDtSci", "2024-12-30 11:19:20");// 检化验出厂检验结果系统时间
        map.put("transIdSci", "");// 检化验唯一键ID
        map.put("transWaterSci", "10");// 水分
        map.put("transTasteSci", "64");// 品位
//        ResultJSON resultJSON1 = salService.saveOutZd(map.toString());

        JSONObject jsonObject  = new JSONObject();
        map.put("compCd", "D01");  // 公司
        map.put("deptCd", "D012301");  // 部门
        map.put("itemCd", "20201000004");  // 物料编码
        map.put("itemNm", "50%粉矿"); // 物料名称
        map.put("qty", "100");// 重量
        map.put("storeCd", "D0100001"); // 库房编码
        map.put("storeNm", "原料北库");// 库房名称
        map.put("areaCd", "");// 区号
        map.put("stackCd", "");// 垛位
        map.put("tradePartnerId", "");// 客户ID
        map.put("tradePartnerCode", "");// 客户编码
        map.put("tradePartnerName", "");// 客户名称
        map.put("transactionId", "1111111111111");// 操作的表Id
        map.put("transactionTable", "STO_ONHAND"); // 操作的表名称
        map.put("transactionDate", date);// 时间
        map.put("transactionType", "B3");// 业务类型 B3生产投料

        resultJSON = JSONTools.toResultJSON(map);
        return resultJSON;
    }

}
