package easydo.technology.service.impl;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.ProcessRoute;
import easydo.technology.model.QualityInspectProgram;
import easydo.technology.service.FlowNoService;
import easydo.technology.service.QualityInspectProgramService;
import easydo.technology.utils.SecurityUtils;
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 QualityInspectProgramServiceImpl implements QualityInspectProgramService {

    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;
    @Resource
    FlowNoService flowNoService;

    @Override
    public Object getList(Map<String, Object> map) throws Exception {
        return jdbcClient.getJdbcList(map, QualityInspectProgram.class);
    }

    @Override
    public Object getPage(Map<String, Object> map) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            return jdbcClient.getJdbcPage(map, QualityInspectProgram.class, connection);
        } finally {
            connection.close();
        }
    }

    @Override
    public Object save(QualityInspectProgram model) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(false);
            model.setCreateId(SecurityUtils.getCurrentUserId());
            model.setCode(flowNoService.generateQualityCode(model, connection));
            jdbcClient.jdbcInsert(model, connection);
            connection.commit();
            return model;
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            connection.close();
        }
    }

    @Override
    public Object update(QualityInspectProgram model) throws Exception {
        jdbcClient.jdbcUpdateById(model);
        return model;
    }

    @Override
    public Object remove(QualityInspectProgram model) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(false);

            // 校验：工艺路线是否关联
            ProcessRoute route = new ProcessRoute();
            route.setInspectProgramId(model.getId());
            int count = jdbcClient.getJdbcCount(route, connection);
            if (count > 0) {
                throw new BizException("当前质检方案已被工艺路线引用，不允许删除");
            }

            jdbcClient.jdbcRemoveById(model, connection);
            connection.commit();
            return model;
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            connection.close();
        }
    }
}

