package easydo.technology.service.impl;

import easydo.technology.components.JdbcClient;
import easydo.technology.enums.MESEnum;
import easydo.technology.exception.BizException;
import easydo.technology.model.*;
import easydo.technology.service.ProductPrePlanService;
import easydo.technology.system.model.SysUser;
import easydo.technology.utils.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

@Service
public class ProductPrePlanServiceImpl implements ProductPrePlanService {

    @Resource
    private JdbcClient jdbcClient;
    @Resource
    private DataSource dataSource;

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> getPage(Map<String, Object> map) throws Exception {
        // 说明：该接口同步自 Go 端的 productPrePlanGetPage 逻辑，基于销售订单（SaleOrder）维度进行深度级联查询和组装。
        // 注意：这种 1:1 对齐方式涉及多层嵌套循环查询（N+1），在数据量较大时需关注性能。
        Connection connection = dataSource.getConnection();
        try {
            // 1) 查询销售订单分页数据
            Map<String, Object> result = jdbcClient.getJdbcPage(map, SaleOrder.class, connection);
            List<SaleOrder> list = (List<SaleOrder>) result.get("records");
            if (list == null || list.isEmpty()) {
                return result;
            }

            for (SaleOrder model : list) {
                // 2) 查询并回填销售订单附件（Minio 文件）
                jdbcClient.getMinioFile(model, connection);

                // 3) 查询并回填订单明细列表（SaleOrderDetail）
                SaleOrderDetail detailParam = new SaleOrderDetail();
                detailParam.setOrderId(model.getId());
                List<SaleOrderDetail> detailList = jdbcClient.getJdbcList(detailParam, connection);

                if (detailList != null) {
                    for (SaleOrderDetail detail : detailList) {
                        // 3.1) 查询并回填明细对应的物料基础信息（ProductMaterial）
                        ProductMaterial materialParam = new ProductMaterial();
                        materialParam.setCode(detail.getMaterialCode());
                        materialParam.setTenantId(model.getTenantId());
                        ProductMaterial material = jdbcClient.getJdbcModel(materialParam, connection);
                        detail.setMaterial(material);

                        // 3.2) 查询该物料是否存在启用的顶级 BOM（parentId = 0）
                        ProductBom bomParam = new ProductBom();
                        bomParam.setParentId("0");
                        bomParam.setMaterialCode(material.getCode());
                        bomParam.setTenantId(model.getTenantId());
                        bomParam.setStatus(MESEnum.PROCESS_OF_STATUS_ENABLE.getValue());
                        ProductBom topBom = null;
                        try {
                            topBom = jdbcClient.getJdbcModel(bomParam, connection);
                        } catch (Exception ex) {
                            // 若未找到对应的 BOM，则 topBom 保持为 null
                        }

                        if (topBom != null && StringUtil.isNotEmpty(topBom.getId())) {
                            // 3.3) 分支 A：存在 BOM，则按 bomCode 查询出该 BOM 下的所有组成项
                            ProductBom bomListParam = new ProductBom();
                            bomListParam.setBomCode(topBom.getBomCode());
                            bomListParam.setTenantId(model.getTenantId());
                            List<ProductBom> bomList = jdbcClient.getJdbcList(bomListParam, connection);

                            if (bomList != null) {
                                for (ProductBom bomModel : bomList) {
                                    // 3.3.1) 查询并回填 BOM 组成项的物料信息
                                    ProductMaterial bmMaterialParam = new ProductMaterial();
                                    bmMaterialParam.setCode(bomModel.getMaterialCode());
                                    bmMaterialParam.setTenantId(model.getTenantId());
                                    ProductMaterial bmMaterial = jdbcClient.getJdbcModel(bmMaterialParam, connection);
                                    bomModel.setMaterial(bmMaterial);

                                    // 3.3.2) 查询并回填该物料在所有仓库中的可用库存（WarehouseMaterial）
                                    WarehouseMaterial wmParam = new WarehouseMaterial();
                                    wmParam.setMaterialCode(bmMaterial.getCode());
                                    wmParam.setTenantId(model.getTenantId());
                                    wmParam.setStatus(MESEnum.PROCESS_OF_STATUS_ENABLE.getValue());
                                    List<WarehouseMaterial> wmList = jdbcClient.getJdbcList(wmParam, connection);
                                    if (wmList != null) {
                                        for (WarehouseMaterial wm : wmList) {
                                            // 同时回填仓库的基础信息（Warehouse）
                                            Warehouse wParam = new Warehouse();
                                            wParam.setId(wm.getWarehouseId());
                                            wm.setWarehouse(jdbcClient.getJdbcModelById(wParam, connection));
                                        }
                                    }
                                    bomModel.setWarehouseMaterialList(wmList);
                                }
                            }
                            detail.setBomList(bomList);
                        } else {
                            // 3.4) 分支 B：不存在 BOM，则直接查询该明细物料的可用库存信息
                            WarehouseMaterial wmParam = new WarehouseMaterial();
                            wmParam.setMaterialCode(material.getCode());
                            wmParam.setTenantId(model.getTenantId());
                            wmParam.setStatus(MESEnum.PROCESS_OF_STATUS_ENABLE.getValue());
                            List<WarehouseMaterial> wmList = jdbcClient.getJdbcList(wmParam, connection);
                            if (wmList != null) {
                                for (WarehouseMaterial wm : wmList) {
                                    Warehouse wParam = new Warehouse();
                                    wParam.setId(wm.getWarehouseId());
                                    wm.setWarehouse(jdbcClient.getJdbcModelById(wParam, connection));
                                }
                            }
                            detail.setWarehouseMaterialList(wmList);
                        }
                    }
                }

                // 4) 将组装好的明细列表回填给订单
                model.setChildrenList(detailList);

                // 5) 查询并回填负责人姓名（来自 sys_user）
                if (model.getManagerId() != null && model.getManagerId() != 0) {
                    SysUser managerParam = new SysUser();
                    managerParam.setId(model.getManagerId());
                    SysUser manager = jdbcClient.getJdbcModelById(managerParam, connection);
                    if (manager != null) {
                        model.setManagerName(manager.getNickName());
                    }
                }

                // 6) 查询并回填客户名称（来自 customer 表）
                if (StringUtil.isNotEmpty(model.getCustomerId())) {
                    Customer customerParam = new Customer();
                    customerParam.setId(model.getCustomerId());
                    Customer customer = jdbcClient.getJdbcModelById(customerParam, connection);
                    if (customer != null) {
                        model.setCustomerName(customer.getName());
                    }
                }
            }

            return result;
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        } finally {
            connection.close();
        }
    }
}

