package easydo.technology.service.impl;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.*;
import easydo.technology.service.FlowNoService;
import easydo.technology.service.OutsourcingPlanService;
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.List;
import java.util.Map;

@Service
public class OutsourcingPlanServiceImpl implements OutsourcingPlanService {

    @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, OutsourcingPlan.class, connection);
            List<OutsourcingPlan> list = (List<OutsourcingPlan>) result.get("records");
            if (list == null || list.isEmpty()) {
                if (result != null) {
                    result.put("records", new ArrayList<>());
                }
                return result;
            }

            for (OutsourcingPlan model : list) {
                // 2. 补全文件列表 (JdbcClient 会根据 @Minio 注解自动处理)
                try {
                    jdbcClient.getMinioFile(model, connection);
                } catch (Exception e) {
                    // 打印错误但继续执行
                }

                // 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. 补全明细列表及物料信息
                OutsourcingPlanDetail detailParam = new OutsourcingPlanDetail();
                detailParam.setPlanId(model.getId());
                List<OutsourcingPlanDetail> detailList = jdbcClient.getJdbcList(detailParam, connection);
                if (detailList != null) {
                    for (OutsourcingPlanDetail detail : detailList) {
                        if (detail.getMaterialCode() != null) {
                            ProductMaterial materialParam = new ProductMaterial();
                            materialParam.setCode(detail.getMaterialCode());
                            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 OutsourcingPlan save(OutsourcingPlan model) throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        try {
            // 1. 生成委外计划流水号 (支持手动编号校验与自动生成)
            String code = flowNoService.generateOutsourcingPlanCode(model, connection);
            model.setCode(code);
            
            // 2. 设置初始状态为待处理 (pending)
            model.setStatus("pending");

            // 3. 插入主表 (JdbcClient 会自动处理 model 继承自 CommonModel 的 fileList 附件)
            jdbcClient.jdbcInsert(model, connection);

            // 4. 插入委外计划明细
            List<OutsourcingPlanDetail> detailList = model.getChildrenList();
            if (detailList != null) {
                for (OutsourcingPlanDetail detail : detailList) {
                    detail.setPlanId(model.getId());
                    jdbcClient.jdbcInsert(detail, connection);
                }
            }

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

    @Override
    public OutsourcingPlan update(OutsourcingPlan model) throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        try {
            // 1. 更新主表 (JdbcClient 自动同步 fileList 附件)
            jdbcClient.jdbcUpdateById(model, connection);

            // 2. 级联更新明细：先按 planId 物理删除旧明细
            OutsourcingPlanDetail removeParam = new OutsourcingPlanDetail();
            removeParam.setPlanId(model.getId());
            jdbcClient.jdbcRemove(removeParam, connection);

            // 3. 重新插入新明细列表
            List<OutsourcingPlanDetail> detailList = model.getChildrenList();
            if (detailList != null) {
                for (OutsourcingPlanDetail detail : detailList) {
                    detail.setPlanId(model.getId());
                    jdbcClient.jdbcInsert(detail, connection);
                }
            }

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

    @Override
    public OutsourcingPlan remove(OutsourcingPlan model) throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        try {
            // 1. 删除主表 (JdbcClient 自动删除关联的 MinioFile)
            jdbcClient.jdbcRemoveById(model, connection);

            // 2. 删除关联的明细记录
            OutsourcingPlanDetail removeParam = new OutsourcingPlanDetail();
            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();
        }
    }
}
