package cn.ezhizao.project.business.controller;

import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.PdfUtil;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.redis.RedisCache;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

/**
 * 生产入库Controller
 *
 * @author ezhizao
 * @date 2025-05-20
 */
@RestController
@RequestMapping("/business/inboundOrder")
public class BizInboundOrderController extends BaseController {
    @Resource
    private IBizInboundOrderService bizInboundOrderService;
    @Resource
    private IBizCertificateLotService bizCertificateLotService;
    @Resource
    private IBizCertificateService bizCertificateService;
    @Resource
    private IBizPackageResourceGroupService bizPackageResourceGroupService;
    @Resource
    private IBizPackageResourceGroupDetailService bizPackageResourceGroupDetailService;
    @Resource
    private IBizCompanyProductPackageService bizCompanyProductPackageService;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizInboundOrderDetailService bizInboundOrderDetailService;
    @Resource
    private IBizProductService bizProductService;
    @Resource
    private ISysDeptService iSysDeptService;
    @Resource
    private IBizCompanyService bizCompanyService;
    @Resource
    private IBizTransferCodeService bizTransferCodeService;
    @Resource
    private IBizDayworkItemService  bizDayworkItemService;
    @Resource
    private IBizTakeStockPeriodService bizTakeStockPeriodService;
    @Resource
    private RedisCache redisCache;
    /**
     * 生成pdf
     */
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    final private String inboundOrderCodeKey = "inboundOrderCode";

    /**
     * 查询生产入库列表
     */
    @PreAuthorize("@ss.hasPermi('business:inboundOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizInboundOrder bizInboundOrder) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizInboundOrder);
        startPage();
        List<BizInboundOrder> list = bizInboundOrderService.getList(bizInboundOrder);
        return getDataTable(list);
    }

    /**
     * 导出生产入库列表
     */
    @PreAuthorize("@ss.hasPermi('business:inboundOrder:export')")
    @Log(title = "生产入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizInboundOrder bizInboundOrder) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizInboundOrder);
        List<BizInboundOrder> list = bizInboundOrderService.getList(bizInboundOrder);
        ExcelUtil<BizInboundOrder> util = new ExcelUtil<>(BizInboundOrder.class);
        util.exportExcel(response, list, "生产入库数据");
    }

    /**
     * 获取生产入库详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:inboundOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BizInboundOrder bizInboundOrder = bizInboundOrderService.getById(id);
        List<BizInboundOrderDetail> details = bizInboundOrderDetailService.query().eq("inbound_order_id", id).list();
        details.forEach(l -> {
            l.setDeptName(bizInboundOrder.getDeptName());
            l.setPackageResourceGroupName(bizInboundOrder.getPackageResourceGroupName());
            l.setDeptId(bizInboundOrder.getDeptId());
            l.setProductType(bizInboundOrder.getProductType());
            l.setIsSubclass(bizInboundOrder.getIsSubclass());
            l.setPackageResourceGroupId(bizInboundOrder.getPackageResourceGroupId());
            l.setBgyno(bizInboundOrder.getStorageUserName());
            l.setBgyna(bizInboundOrder.getStorageNickName());
            l.setBgyId(bizInboundOrder.getStorageUserId());
            l.setStandard(bizInboundOrder.getStandard());
            l.setDrawingNo(bizInboundOrder.getDrawingNo());
            l.setCompanyId(bizInboundOrder.getCompanyId());
            l.setCompanyAlias(bizInboundOrder.getCompanyAlias());
            l.setCompanyCode(bizInboundOrder.getCompanyCode());
            l.setLabelNumber(bizInboundOrder.getLabelNumber());
            l.setPackageTypeCode(bizInboundOrder.getPackageType());
            l.setProductDescription(bizInboundOrder.getProductDescription());
            l.setProductCode(bizInboundOrder.getProductCode());
            l.setDeptCode(bizInboundOrder.getDeptCode());
            l.setPackageResourceGroupLineNo(bizInboundOrder.getPackageResourceGroupLineNo());
            l.setProductId(bizInboundOrder.getProductId());
        });
        bizInboundOrder.setDetails(details);
        return success(bizInboundOrder);
    }

    /**
     * 新增生产入库
     */
    @PreAuthorize("@ss.hasPermi('business:inboundOrder:add')")
    @Log(title = "生产入库", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody BizInboundOrder bizInboundOrder) throws NoSuchFieldException, IllegalAccessException {
        // 判断盘点状态下不能新增入库
        Long count = bizTakeStockPeriodService.query().eq("status", 1).count();
        if (count > 0) {
            return error("盘点状态下不能新增入库");
        }
        setTenantId(bizInboundOrder);
        // 判断当前托盘是否与当前部门绑定
        BizTransferCode transferCode = bizTransferCodeService.query().eq("code", bizInboundOrder.getTransferCode()).eq("dept_id", bizInboundOrder.getDeptId()).one();
        if (transferCode == null) {
            return error("该托盘不存在或未绑定当前工段");
        }
        bizInboundOrder.setTransferId(transferCode.getId());
        // 判断转运托盘是否绑定5个以上的产品
        List<BizInboundOrder> bizInboundOrders = bizInboundOrderService.query().ne("status", 2).eq("transfer_code", bizInboundOrder.getTransferCode()).list();
        List<String> productCodes = bizInboundOrders.stream().map(BizInboundOrder::getProductCode).distinct().collect(Collectors.toList());
        if (productCodes.stream().noneMatch(t -> t.equals(bizInboundOrder.getProductCode()))) {
            productCodes.add(bizInboundOrder.getProductCode());
        }
        if (productCodes.stream().distinct().count() > 4) {
            return error("转运托盘绑定的产品不能超过4个");
        }
        // 入库单号生成
        SysDept dept = iSysDeptService.selectDeptById(bizInboundOrder.getDeptId());
        String beginCode = dept.getDeptKey() + DateTime.now().toString("yy");
        String previous = redisCache.hasKey(inboundOrderCodeKey + "-" + dept.getDeptKey()) ? redisCache.getCacheObject(inboundOrderCodeKey + "-" + dept.getDeptKey()) : "";
        String codeValue = "";
        // 固定部分的位数为 x位 的部门助记码 + 2位年份
        int beginIndex = dept.getDeptKey().length() + 2;
        if (previous.isEmpty()) {
            BizInboundOrder maxCode = bizInboundOrderService.query().like("inbound_number", beginCode + "%").orderByDesc("inbound_number").last("limit 1").one();

            if (maxCode != null) {
                codeValue = maxCode.getInboundNumber();
                // 获取4位尾数部分
                int lastFourDigits = Integer.parseInt(codeValue.substring(beginIndex, beginIndex + 5));
                lastFourDigits++; // 加1
                codeValue = codeValue.substring(0, beginIndex) + String.format("%05d", lastFourDigits);
                previous = codeValue;
            } else {
                previous = (beginCode + "00001");
            }
        } else {
            codeValue = previous.startsWith(beginCode) ? previous : beginCode + "00000";
            int lastFourDigits = Integer.parseInt(codeValue.substring(beginIndex, beginIndex + 5));
            lastFourDigits++; // 加1
            codeValue = codeValue.substring(0, beginIndex) + String.format("%05d", lastFourDigits);
            previous = codeValue;
        }

        bizInboundOrder.setInboundNumber(previous);
        redisCache.setCacheObject(inboundOrderCodeKey + "-" + dept.getDeptKey(), previous);
        bizInboundOrderService.save(bizInboundOrder);
        List<BizInboundOrderDetail> details = bizInboundOrder.getDetails();
        details.forEach(l -> {
            l.setInboundOrderId(bizInboundOrder.getId());
        });
        bizInboundOrderDetailService.saveBatch(details);
        return success(bizInboundOrder);
    }

    /**
     * 修改生产入库
     */
    @PreAuthorize("@ss.hasPermi('business:inboundOrder:edit')")
    @Log(title = "生产入库", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody BizInboundOrder bizInboundOrder) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizInboundOrder);
        // 判断当前托盘是否与当前部门绑定
        BizTransferCode transferCode = bizTransferCodeService.query().eq("code", bizInboundOrder.getTransferCode()).eq("dept_id", bizInboundOrder.getDeptId()).one();
        if (transferCode == null) {
            return error("该托盘不存在或未绑定当前工段");
        }
        bizInboundOrder.setTransferId(transferCode.getId());
        // 判断转运托盘是否绑定5个以上的产品
        List<BizInboundOrder> bizInboundOrders = bizInboundOrderService.query().ne("status", 2).eq("transfer_code", bizInboundOrder.getTransferCode()).list();
        List<String> productCodes = bizInboundOrders.stream().map(BizInboundOrder::getProductCode).distinct().collect(Collectors.toList());
        if (productCodes.stream().noneMatch(t -> t.equals(bizInboundOrder.getProductCode()))) {
            productCodes.add(bizInboundOrder.getProductCode());
        }
        if (productCodes.stream().distinct().count() > 4) {
            return error("转运托盘绑定的产品不能超过4个");
        }
        List<BizInboundOrderDetail> oldDetails = bizInboundOrderDetailService.query().eq("inbound_order_id", bizInboundOrder.getId()).list();
        BizInboundOrder old = bizInboundOrderService.getById(bizInboundOrder.getId());
        // 判断转运托盘是否变更
        if (!old.getTransferCode().equals(bizInboundOrder.getTransferCode())) {
            bizInboundOrder.setOriginalTransferCode(old.getTransferCode());
        }
        bizInboundOrderService.updateById(bizInboundOrder);
        List<BizInboundOrderDetail> details = bizInboundOrder.getDetails();
        details.forEach(l -> {
            l.setInboundOrderId(bizInboundOrder.getId());
        });
        bizInboundOrderDetailService.saveOrUpdateBatch(details);
        bizInboundOrderDetailService.removeBatchByIds(oldDetails.stream().filter(t -> details.stream().noneMatch(v -> v.getId().equals(t.getId()))).collect(Collectors.toList()));
        return success(bizInboundOrder);
    }

    /**
     * 删除生产入库
     */
    @PreAuthorize("@ss.hasPermi('business:inboundOrder:remove')")
    @Log(title = "生产入库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable List<Long> ids) {
        bizInboundOrderService.removeBatchByIds(ids);
        // 删除明细
        QueryWrapper<BizInboundOrderDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.in("inbound_order_id", ids);
        bizInboundOrderDetailService.remove(detailQueryWrapper);
        return success();
    }

    @PostMapping("/getCertificateListByCodes")
    public AjaxResult getCertificateListByCodes(@RequestBody List<BizInboundOrderDetail> inputDetails) {
        List<String> codes = inputDetails.stream().filter(v -> v.getIsFirst() == null || !v.getIsFirst()).map(BizInboundOrderDetail::getCertificateCode).collect(Collectors.toList());
        BizInboundOrderDetail first = inputDetails.stream().filter(v -> v.getIsFirst() != null && v.getIsFirst()).findFirst().orElse(null);
        // 根据合格证编码获取合格证信息
        List<BizCertificateLot> bizCertificateLotList = bizCertificateLotService.query().in("barcode", codes).list();
        if (bizCertificateLotList.isEmpty()) {
            return error("未找到相关合格证");
        }
        List<BizCertificate> bizCertificates = bizCertificateService.query().in("id", bizCertificateLotList.isEmpty() ? Collections.singleton(0L) : bizCertificateLotList.stream().map(BizCertificateLot::getCertificateId).collect(Collectors.toList())).list();
        List<BizCompany> bizCompanies = bizCompanyService.query().in("id", bizCertificates.isEmpty() ? Collections.singletonList(0L) : bizCertificates.stream().map(BizCertificate::getCompanyId).collect(Collectors.toList())).list();
        List<BizPackageResourceGroup> bizPackageResourceGroups = bizPackageResourceGroupService.query().in("id", bizCertificates.isEmpty() ? Collections.singletonList(0L) : bizCertificates.stream().map(BizCertificate::getPackageResourceGroupId).collect(Collectors.toList())).list();
        List<SysDept> depts = bizPackageResourceGroups.isEmpty() ? new ArrayList<>() : iSysDeptService.getDeptOptions(bizPackageResourceGroups.stream().map(BizPackageResourceGroup::getDeptId).collect(Collectors.toList()));
        List<BizPackageResourceGroupDetail> bizPackageResourceGroupDetails = bizPackageResourceGroupDetailService.query().in("package_resource_group_id", bizPackageResourceGroups.isEmpty() ? Collections.singletonList(0L) : bizPackageResourceGroups.stream().map(BizPackageResourceGroup::getId).collect(Collectors.toList())).list();
        List<BizProduct> products = bizProductService.query().in("product_code", bizCertificates.isEmpty() ? Collections.singletonList("") : bizCertificates.stream().map(BizCertificate::getProductCode).collect(Collectors.toList())).list();
        List<BizProductionPlanDetail> bizProductionPlanDetails = bizCertificates.isEmpty() ? new ArrayList<>() : bizProductionPlanDetailService.query().in("id", bizCertificates.stream().map(BizCertificate::getProductionPlanDetailId).collect(Collectors.toList())).list();
        List<BizInboundOrderDetail> checkDetails = bizInboundOrderDetailService.query().in("certificate_code", codes).ne("inbound_order_id", inputDetails.get(0).getInboundOrderId() == null ? 0L : inputDetails.get(0).getInboundOrderId()).list();
        List<BizCompanyProductPackage> packages = bizCertificates.isEmpty() ? new ArrayList<>() : bizCompanyProductPackageService.query().in("concat(product_code, package_code)", bizCertificates.stream().map(t -> t.getProductCode() + t.getPackageCode()).collect(Collectors.toList())).list();
        List<BizInboundOrderDetail> details = new ArrayList<>();
        codes.forEach(l -> {
            BizCertificateLot item = bizCertificateLotList.stream().filter(x -> x.getBarcode().equals(l)).findFirst().orElse(null);
            BizCertificate certificate = item != null ? bizCertificates.stream().filter(x -> x.getId().equals(item.getCertificateId())).findFirst().orElse(null) : null;
            BizCompany company = certificate != null ? bizCompanies.stream().filter(x -> x.getId().equals(certificate.getCompanyId())).findFirst().orElse(null) : null;
            BizCompanyProductPackage packageItem = certificate != null ? packages.stream().filter(x -> x.getProductCode().equals(certificate.getProductCode()) && x.getPackageCode().equals(certificate.getPackageCode())).findFirst().orElse(null) : null;
            BizProduct product = certificate != null ? products.stream().filter(x -> x.getProductCode().equals(certificate.getProductCode())).findFirst().orElse(null) : null;
            BizPackageResourceGroup group = certificate != null ? bizPackageResourceGroups.stream().filter(x -> x.getId().equals(certificate.getPackageResourceGroupId())).findFirst().orElse(null) : null;
            List<BizPackageResourceGroupDetail> packageResourceGroupDetails = group != null ? bizPackageResourceGroupDetails.stream().filter(x -> x.getPackageResourceGroupId().equals(group.getId())).collect(Collectors.toList()) : new ArrayList<>();
            BizProductionPlanDetail productionPlanDetail = certificate == null ? null : bizProductionPlanDetails.stream().filter(x -> x.getId().equals(certificate.getProductionPlanDetailId())).findFirst().orElse(null);
            SysDept dept = group != null ? depts.stream().filter(x -> x.getValue().equals(group.getDeptId())).findFirst().orElse(null) : null;
            BizInboundOrderDetail detail = new BizInboundOrderDetail();
            detail.setCertificateCode(l);
            if (checkDetails.stream().noneMatch(x -> x.getCertificateCode().equals(l))) {
                detail.setCertificateId(item != null ? item.getCertificateId() : null);
                detail.setCertificateLotId(item != null ? item.getId() : null);
                detail.setInboundNum(certificate != null ? Long.valueOf(certificate.getPackageNumber()) : null);
                // 第一个操作人
                detail.setFirstOperatorUserId(!packageResourceGroupDetails.isEmpty() ? packageResourceGroupDetails.get(0).getUserId() : null);
                detail.setFirstOperatorUserName(!packageResourceGroupDetails.isEmpty() ? packageResourceGroupDetails.get(0).getUserName() : null);
                detail.setFirstOperatorNickName(!packageResourceGroupDetails.isEmpty() ? packageResourceGroupDetails.get(0).getNickName() : null);
                // 第二个操作人
                detail.setSecondOperatorUserId(packageResourceGroupDetails.size() >= 2 ? packageResourceGroupDetails.get(1).getUserId() : null);
                detail.setSecondOperatorUserName(packageResourceGroupDetails.size() >= 2 ? packageResourceGroupDetails.get(1).getUserName() : null);
                detail.setSecondOperatorNickName(packageResourceGroupDetails.size() >= 2 ? packageResourceGroupDetails.get(1).getNickName() : null);
                // 第三个操作人
                detail.setThirdOperatorUserId(packageResourceGroupDetails.size() >= 3 ? packageResourceGroupDetails.get(2).getUserId() : null);
                detail.setThirdOperatorUserName(packageResourceGroupDetails.size() >= 3 ? packageResourceGroupDetails.get(2).getUserName() : null);
                detail.setThirdOperatorNickName(packageResourceGroupDetails.size() >= 3 ? packageResourceGroupDetails.get(2).getNickName() : null);

                detail.setPackageTypeCode(certificate != null ? certificate.getPackageTypeCode() : null);
                detail.setUnit("支");
                detail.setProductId(certificate != null ? certificate.getProductId() : null);
                detail.setCompanyId(certificate != null ? certificate.getCompanyId() : null);
                detail.setCustomerName(certificate != null ? certificate.getCustomerName() : null);
                detail.setDeptName(certificate != null ? certificate.getDeptName() : null);
                detail.setPackageResourceGroupName(group != null ? group.getName() : null);
                detail.setPackageResourceGroupLineNo(group != null ? group.getPackageLineNo() : null);
                detail.setProductDescription(certificate != null ? certificate.getProductDescription() : null);
                detail.setProductType(productionPlanDetail != null ? productionPlanDetail.getProductionTypeCode() : null);
                detail.setProductCode(product != null ? product.getProductCode() : null);
                detail.setIsSubclass(product != null ? product.getIsSubclass() : null);
                detail.setLotCode(certificate != null ? certificate.getLotCode() : null);
                detail.setLotId(certificate != null ? certificate.getLotId() : null);
                detail.setDeptId(group != null ? group.getDeptId() : null);
                detail.setDeptName(dept != null ? dept.getLabel() : null);
                detail.setPackageResourceGroupId(group != null ? group.getId() : null);
                detail.setStandard(product != null ? product.getSpecification() : null);
                detail.setDrawingNo(product != null ? product.getDrawingNumber() : null);
                detail.setCompanyCode(company != null ? company.getCompanyCode() : null);
                detail.setCompanyAlias(company != null ? company.getCompanyAlias() : null);
                detail.setLabelNumber(packageItem != null ? packageItem.getSingleNumber() : null);
                detail.setDeptCode(dept != null ? dept.getDeptCode() : null);
                detail.setInboundOrderId(inputDetails.get(0).getInboundOrderId());
                detail.setBgyna(packageItem != null ? packageItem.getBgyna() : null);
                detail.setBgyno(packageItem != null ? packageItem.getBgyno() : null);
                detail.setBgyId(packageItem != null ? packageItem.getBgyId() : null);
            }
            details.add(detail);
        });
        // 获取第一个可使用合格证号
        if (first == null) {
            first = details.stream().filter(v -> v.getCertificateId() != null).findFirst().orElse(null);
        }
        if (first == null) {
            return error("没有可用的合格证号");
        }
        if (first != null) {
            // 判断和第一个合格证是否是同一产品同一部门，同一包装线，同一包装形式，假设不同 设置 checked false 否则设置 true
            BizInboundOrderDetail finalFirst = first;
            details.forEach(l -> {
                l.setChecked(finalFirst.getProductCode().equals(l.getProductCode()) && finalFirst.getDeptId().equals(l.getDeptId()) && finalFirst.getPackageResourceGroupId().equals(l.getPackageResourceGroupId()) && finalFirst.getPackageTypeCode().equals(l.getPackageTypeCode()) && details.stream().filter(t -> t.getCertificateCode().equals(l.getCertificateCode())).count() <= 1);
            });
        }
        AjaxResult result = success(details);
        result.put("checked", details.stream().allMatch(BizInboundOrderDetail::getChecked));
        return result;
    }

    @PostMapping("/exportPdfForOrder")
    public void exportPdfForOrder(BizInboundOrder bizInboundOrder, HttpServletResponse response) throws Exception {

        bizInboundOrder = bizInboundOrderService.getList(bizInboundOrder).get(0);
        List<BizInboundOrderDetail> details = bizInboundOrderDetailService.query().eq("inbound_order_id", bizInboundOrder.getId()).list();
        // 根据批次汇总明细表
        Map<String, List<BizInboundOrderDetail>> groupedByProductDescription =
                details.stream()
                        .collect(Collectors.groupingBy(
                                BizInboundOrderDetail::getLotCode, // 分组依据的函数
                                Collectors.toList() // 指定分组内的元素收集为 List
                        ));
        List<List<BizInboundOrderDetail>> list = new ArrayList<>();
        List<BizInboundOrderDetail> group = new ArrayList<>();
        for (Map.Entry<String, List<BizInboundOrderDetail>> entry : groupedByProductDescription.entrySet()) {
            List<BizInboundOrderDetail> item = entry.getValue(); // 获取对应的 List，即 Map 的值
//            // 用于临时存储每组数据的列表
            // 遍历 outsourcedOrderDetails 列表
//            for (BizInboundOrderDetail detail : item) {
            BizInboundOrderDetail detail = item.get(0);
            detail.setInboundNum(item.stream().mapToLong(BizInboundOrderDetail::getInboundNum).sum());
            group.add(detail);
            // 每添加 14 个元素后，将其添加到 list 中，并重置 group
            if (group.size() == 10) {
                list.add(new ArrayList<>(group));
                group = new ArrayList<>();
            }
//            }

        }
        // 如果最后一组不足 10 个元素，也将其添加到 list 中
        if (!group.isEmpty()) {
            BizInboundOrderDetail orderDetail = new BizInboundOrderDetail();
            while (group.size() < 10) {
                group.add(orderDetail); // 添加默认元素直到总数为14
            }
            list.add(group);
        }
        for (List<BizInboundOrderDetail> listItem : list) {
            // 使用流过滤出 productNum 不为空的元素，并对其 productNum 值求和
            Long sum = listItem.stream()
                    .filter(item -> item.getInboundNum() != null) // 过滤出 productNum 不为空的元素
                    .mapToLong(BizInboundOrderDetail::getInboundNum) // 映射到 productNum 属性
                    .sum(); // 计算总和
            // 然后，给每个对象的 sum 属性赋值
            for (BizInboundOrderDetail item : listItem) {
                item.setSum(sum);
            }
        }
        bizInboundOrder.setDetailLists(list);
//        bizInboundOrder.setTenantName("德迈仕");
        bizInboundOrder.setInboundDateStr(DateUtil.format(bizInboundOrder.getInboundTime(), "yyyy-MM-dd"));
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("inboundOrder", bizInboundOrder);
        Writer out = new StringWriter();
        //获取模板地址
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("inboundOrderPdf.html");
        template.process(paramMap, out);
        out.flush();
        out.close();
        String templateContent = out.toString();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        String fileName = "产品入库单";
        response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes()));
        byte[] resources = PdfUtil.html3Pdf(templateContent);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(resources);
        outputStream.close();

    }

    @PostMapping("/setPrint")
    public void setPrint(@RequestBody BizInboundOrder bizInboundOrder) throws Exception {
        bizInboundOrder.setIsPrint(1);
        bizInboundOrderService.updateById(bizInboundOrder);
    }

    @PostMapping("/exportCertificateLots")
    public void exportCertificateLots(HttpServletResponse response, BizCertificateLot bizCertificateLot) {
        List<BizCertificateLot> lots = bizCertificateLotService.query().in("id", bizCertificateLot.getIds()).list();
        if (lots.isEmpty()) {
            throw new RuntimeException("请选择导出合格证");
        }
        List<BizCertificate> items = bizCertificateService.query().in("id", lots.stream().map(BizCertificateLot::getCertificateId).collect(Collectors.toList())).list();
        List<Long> dayworkIds = items.stream().map(BizCertificate::getDayworkId).collect(Collectors.toList());
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.query().in("daywork_id", dayworkIds).list();
        //包装详情
        List<Long> packageIds = items.stream().map(v -> v.getPackageId()).distinct().collect(Collectors.toList());
        List<BizCompanyProductPackage> packageList = bizCompanyProductPackageService.query().in("id", packageIds).list();
        List<BizCertificateExport> list = new ArrayList<>();

        for(BizCertificate certificate : items){
            BizDayworkItem bizDayworkItem = dayworkItemList.stream().filter(v -> v.getDayworkId().equals(certificate.getDayworkId())).max(Comparator.comparing(BizDayworkItem::getCreateTime)).orElse(null);
            List<BizCertificateLot> certificateLots = lots.stream().filter(v -> v.getCertificateId().equals(certificate.getId())).collect(Collectors.toList());
            for(BizCertificateLot item : certificateLots){
                BizCertificateExport bizCertificateExport = new BizCertificateExport();
                bizCertificateExport.setLotCode(certificate.getLotCode());
                bizCertificateExport.setProductDescription(certificate.getProductDescription());
                bizCertificateExport.setDeptName(certificate.getDeptName());
                bizCertificateExport.setLabelNumber(certificate.getLabelNumber());
                bizCertificateExport.setPackageLineNo(certificate.getPackageLineNo());
                bizCertificateExport.setPackageNo(certificate.getPackageNo());
                bizCertificateExport.setNumber(certificate.getNumber());
                bizCertificateExport.setPrintPages(certificate.getPrintPages());
                bizCertificateExport.setPrintDate(certificate.getPrintDate());
                bizCertificateExport.setCompanyName(certificate.getCompanyName());
                bizCertificateExport.setPurchaseOrderNo(certificate.getPurchaseOrderNo());
                bizCertificateExport.setFurnaceNumber(certificate.getFurnaceNumber());
                bizCertificateExport.setPackageStandard(certificate.getPackageStandard());
                bizCertificateExport.setPackageTypeCode(certificate.getPackageTypeCode());
                bizCertificateExport.setSpecification(certificate.getSpecification());
                bizCertificateExport.setDrawingNumber(certificate.getDrawingNumber());
                bizCertificateExport.setMaterialNum(certificate.getMaterialNum());
                bizCertificateExport.setSubmitTime(bizDayworkItem.getEndTime());
                bizCertificateExport.setBarCode(item.getBarcode());
                bizCertificateExport.setFirst_1(certificate.getFirst_1());
                bizCertificateExport.setFirst_2(certificate.getFirst_2());
                bizCertificateExport.setFirst_3(certificate.getFirst_3());
                bizCertificateExport.setFirst_4(certificate.getFirst_4());
                bizCertificateExport.setFirst_5(certificate.getFirst_5());
                bizCertificateExport.setFirst_6(certificate.getFirst_6());
                bizCertificateExport.setFirst_7(certificate.getFirst_7());
                bizCertificateExport.setFirst_8(certificate.getFirst_8());
                bizCertificateExport.setFirst_9(certificate.getFirst_9());
                bizCertificateExport.setFirst_10(certificate.getFirst_10());
                //包装
                BizCompanyProductPackage packageItem = packageList.stream().filter(v -> v.getId().equals(certificate.getPackageId())).findFirst().orElse(null);
                bizCertificateExport.setRecipientName(packageItem.getRecipientName());
                bizCertificateExport.setPackingOrder(packageItem.getPackingOrder());
                bizCertificateExport.setCustomerPartNo(packageItem.getCustomerPartNo());
                bizCertificateExport.setCustomerPartName(packageItem.getCustomerPartName());
                bizCertificateExport.setProductCode(packageItem.getProductCode());
                bizCertificateExport.setNetWeight(packageItem.getNetWeight());
                bizCertificateExport.setSingleGrossWeight(packageItem.getSingleGrossWeight());
                bizCertificateExport.setEngineerChangeNumber(packageItem.getEngineerChangeNumber());
                bizCertificateExport.setSupplierCode(packageItem.getSupplierCode());
                list.add(bizCertificateExport);
            }
        }
        ExcelUtil<BizCertificateExport> util = new ExcelUtil<BizCertificateExport>(BizCertificateExport.class);
        util.exportExcel(response, list, "合格证打印");
    }

    @PostMapping("/inboundAllLot")
    @Transactional
    public AjaxResult inboundAllLot(@RequestBody BizInboundOrder bizInboundOrder) throws Exception {
        bizInboundOrder.setStatus("2");
        bizInboundOrder.setIsAllInbound(1);
        List<BizInboundOrderDetail> detailList = bizInboundOrderDetailService.query().eq("inbound_order_id", bizInboundOrder.getId()).list();
        detailList.forEach(l -> {
            l.setIsInbound(1);
        });
        bizInboundOrderService.updateById(bizInboundOrder);
        bizInboundOrderDetailService.updateBatchById(detailList);
        return success();
    }
}
