package easydo.technology.service.impl;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.Customer;
import easydo.technology.model.ProductMaterial;
import easydo.technology.model.PurchasePlan;
import easydo.technology.model.PurchasePlanDetail;
import easydo.technology.model.SaleOrder;
import easydo.technology.model.SaleOrderDetail;
import easydo.technology.service.FlowNoService;
import easydo.technology.service.PurchasePlanService;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PurchasePlanServiceImpl implements PurchasePlanService {

    @Resource
    private JdbcClient jdbcClient;

    @Resource
    private DataSource dataSource;

    @Resource
    private FlowNoService flowNoService;

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> getPage(Map<String, Object> map) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            // 1. 获取主表分页数据
            Map<String, Object> result = jdbcClient.getJdbcPage(map, PurchasePlan.class, connection);
            List<PurchasePlan> list = (List<PurchasePlan>) result.get("records");
            if (list == null || list.isEmpty()) {
                if (result != null) {
                    result.put("records", new ArrayList<>());
                }
                return result;
            }

            for (PurchasePlan model : list) {
                // 2. 补全文件列表 FileList
                try {
                    jdbcClient.getMinioFile(model, connection);
                } catch (Exception e) {
                    // 打印错误但继续执行，参考 Go 版 utils.PrintSearchFileErr
                }

                // 3. 补全销售订单 SaleOrder 及其明细
                if (model.getSaleOrderId() != null) {
                    SaleOrder saleOrderParam = new SaleOrder();
                    saleOrderParam.setId(model.getSaleOrderId());
                    SaleOrder saleOrder = jdbcClient.getJdbcModelById(saleOrderParam, connection);
                    
                    if (saleOrder != null) {
                        // 3.1 获取销售订单明细列表
                        SaleOrderDetail saleOrderDetailParam = new SaleOrderDetail();
                        saleOrderDetailParam.setOrderId(saleOrder.getId());
                        List<SaleOrderDetail> saleOrderDetailList = jdbcClient.getJdbcList(saleOrderDetailParam, connection);
                        
                        if (saleOrderDetailList != null) {
                            for (SaleOrderDetail detail : saleOrderDetailList) {
                                // 3.2 补全销售订单明细中的物料信息
                                if (detail.getMaterialCode() != null) {
                                    ProductMaterial materialParam = new ProductMaterial();
                                    materialParam.setCode(detail.getMaterialCode());
                                    detail.setMaterial(jdbcClient.getJdbcModel(materialParam, connection));
                                }
                            }
                            saleOrder.setChildrenList(saleOrderDetailList);
                        }
                        
                        // 3.3 补全销售订单的负责人姓名 ManagerName
                        if (StringUtil.isNotEmpty(saleOrder.getManagerId())) {
                            SysUser managerParam = new SysUser();
                            managerParam.setId(saleOrder.getManagerId());
                            SysUser manager = jdbcClient.getJdbcModelById(managerParam, connection);
                            if (manager != null) {
                                saleOrder.setManagerName(manager.getNickName());
                            }
                        }
                        
                        // 3.4 补全销售订单的客户名称 CustomerName
                        if (StringUtil.isNotEmpty(saleOrder.getCustomerId())) {
                            Customer customerParam = new Customer();
                            customerParam.setId(saleOrder.getCustomerId());
                            Customer customer = jdbcClient.getJdbcModelById(customerParam, connection);
                            if (customer != null) {
                                saleOrder.setCustomerName(customer.getName());
                            }
                        }
                        
                        model.setSaleOrder(saleOrder);
                    }
                }

                // 4. 补全采购员姓名 PurchaseUserName (从 SysUser 获取 NickName)
                if (model.getPurchaseUserId() != null) {
                    SysUser userParam = new SysUser();
                    userParam.setId(model.getPurchaseUserId());
                    SysUser user = jdbcClient.getJdbcModelById(userParam, connection);
                    if (user != null) {
                        model.setPurchaseUserName(user.getNickName());
                    }
                }

                // 5. 补全明细列表 ChildrenList
                Map<String, Object> detailQuery = new HashMap<>();
                detailQuery.put("planId", model.getId());
                detailQuery.put("orderBy", "sortOrder_asc");
                List<PurchasePlanDetail> detailList = jdbcClient.getJdbcList(detailQuery, PurchasePlanDetail.class, connection);
                if (detailList != null) {
                    for (PurchasePlanDetail detail : detailList) {
                        // 5.1 补全明细中的物料信息 ProductMaterial
                        if (detail.getMaterialCode() != null) {
                            ProductMaterial materialParam = new ProductMaterial();
                            materialParam.setCode(detail.getMaterialCode());
                            // 参考 Go 版 services.JdbcClient.GetJdbcModel(material)
                            detail.setMaterial(jdbcClient.getJdbcModel(materialParam, connection));
                        }
                    }
                    model.setChildrenList(detailList);
                } else {
                    model.setChildrenList(new ArrayList<>());
                }
            }

            result.put("records", list);
            return result;
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public PurchasePlan save(PurchasePlan model) throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        try {
            // 1) 生成编码（支持手填校验 + 自动生成）
            String code = flowNoService.generatePurchasePlanCode(model, connection);
            model.setCode(code);

            // 2) 初始状态 pending
            model.setStatus("pending");

            // 3) 插入主表（会自动保存附件 fileList）
            jdbcClient.jdbcInsert(model, connection);

            // 4) 插入明细
            List<PurchasePlanDetail> detailList = model.getChildrenList();
            if (detailList != null) {
                int sortOrder = 0;
                for (PurchasePlanDetail detail : detailList) {
                    detail.setPlanId(model.getId());
                    detail.setSortOrder(sortOrder++);
                    jdbcClient.jdbcInsert(detail, connection);
                }
            }

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

    @Override
    public PurchasePlan update(PurchasePlan model) throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        try {
            // 1) 更新主表（会自动保存附件 fileList）
            jdbcClient.jdbcUpdateById(model, connection);

            // 2) 删除旧明细
            PurchasePlanDetail removeParam = new PurchasePlanDetail();
            removeParam.setPlanId(model.getId());
            jdbcClient.jdbcRemove(removeParam, connection);

            // 3) 插入新明细
            List<PurchasePlanDetail> detailList = model.getChildrenList();
            if (detailList != null) {
                int sortOrder = 0;
                for (PurchasePlanDetail detail : detailList) {
                    detail.setPlanId(model.getId());
                    detail.setSortOrder(sortOrder++);
                    jdbcClient.jdbcInsert(detail, connection);
                }
            }

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

    @Override
    public PurchasePlan remove(PurchasePlan model) throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        try {
            // 1) 删除主表（JdbcClient 会自动删除附件）
            jdbcClient.jdbcRemoveById(model, connection);

            // 2) 删除明细
            PurchasePlanDetail removeParam = new PurchasePlanDetail();
            removeParam.setPlanId(model.getId());
            jdbcClient.jdbcRemove(removeParam, connection);

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