package easydo.technology.service.impl;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.model.Device;
import easydo.technology.service.DeviceService;
import org.springframework.stereotype.Service;

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

@Service
public class DeviceServiceImpl implements DeviceService {

    @Resource
    private JdbcClient jdbcClient;

    @Resource
    private DataSource dataSource;

    @Override
    public Object getPage(Map<String, Object> map) throws Exception {
        return jdbcClient.getJdbcPage(map, Device.class);
    }

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

    @Override
    public Object save(Device model) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(false);
            jdbcClient.jdbcInsert(model, connection);
            connection.commit();
            return model;
        } catch (Exception e) {
            if (connection != null) connection.rollback();
            throw e;
        } finally {
            if (connection != null) connection.close();
        }
    }

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

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

            // 校验：工艺路线明细是否关联此设备 (device_list 存储为 ["id1", "id2"])
            // 利用 ResultSetUtil 的 _like 后缀实现包含查询: device_list like '%"ID"%'
            Map<String, Object> checkMap = new HashMap<>();
            checkMap.put("deviceList_like", "\"" + model.getId() + "\"");
            
            // 注意：这里需要指定表名或通过已有模型 ProcessRouteDetail 统计
            // 由于 JdbcClient.getJdbcCountByMap 接收 Class，我们直接查 ProcessRouteDetail.class
            int count = jdbcClient.getJdbcCountByMap(checkMap, easydo.technology.model.ProcessRouteDetail.class, connection);
            
            if (count > 0) {
                throw new BizException("当前设备已被工艺路线引用，不允许删除");
            }

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

