package nccloud.api.uapbd;


// import com.alibaba.fastjson.JSONObject; // 可能不再需要，取决于IJsonForAPI的实现和ResultMessageUtil
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.lang.UFDate;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.*;
// import java.util.StringJoiner; // 不再需要


@Path("/uapbd/querySync")
public class QuerySync extends AbstractNCCRestResource {

    public static final BaseDAO BASE_DAO = new BaseDAO();

    /**
     * 处理类似TS的特殊字段
     */
    private static void processTsParams(Map<String, Object> data) {
        // 处理ts参数
        if (data.containsKey("ts")) {
            Object tsObj = data.get("ts");
            String tsCondition = null;

            if (tsObj instanceof String) {
                String ts = (String) tsObj;
                UFDate ufdate = new UFDate(ts);
                Date date = ufdate.toDate();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.HOUR_OF_DAY, -3); // 减去 3 小时
                //提前三小时，防止ts与现实时间差别
                UFDate adjustedUfDate = new UFDate(calendar.getTimeInMillis());
                if (!ts.contains(",")) {  // 单个时间戳
                    tsCondition = "ts >= '" + adjustedUfDate + "' AND ts <= '" + new UFDate(new Date()) + "'";
                }
            }

            // 将构建好的条件放入extraCondition
            if (tsCondition != null) {
                // 检查是否已有其他extraCondition
                String existingExtraCondition = data.containsKey("extraCondition") ?
                        (String) data.get("extraCondition") : "";

                if (existingExtraCondition.isEmpty()) {
                    data.put("extraCondition", tsCondition);
                } else {
                    data.put("extraCondition", existingExtraCondition + " AND " + tsCondition);
                }
            }

            // 从参数中移除ts，避免它被直接用于查询条件
            data.remove("ts");
        }
    }

    @Override
    public String getModule() {
        return "uapbd";
    }

    private JSONString baseQuery(Map<String, Object> originalData, String viewName) throws DAOException {
        // 创建参数副本进行操作，避免修改传入的原始Map
        Map<String, Object> queryParams = new HashMap<>(originalData);

        // 处理ts
        processTsParams(queryParams); // queryParams 会被修改
        queryParams.remove("type"); // 移除类型参数，因为它仅用于路由

        // 获取额外条件
        String extraCondition = null;
        if (queryParams.containsKey("extraCondition")) {
            extraCondition = (String) queryParams.get("extraCondition");
            queryParams.remove("extraCondition"); // 移除额外条件参数，防止影响 buildUniversalCondition
        }

        String baseGeneratedCondition = QuerySyncSqlUtils.buildUniversalCondition(queryParams);

        String finalCondition = "";
        if (baseGeneratedCondition != null && !baseGeneratedCondition.trim().isEmpty()) {
            finalCondition = baseGeneratedCondition.trim();
        }

        if (extraCondition != null && !extraCondition.trim().isEmpty()) {
            if (finalCondition.isEmpty()) {
                finalCondition = extraCondition.trim();
            } else {
                finalCondition = finalCondition + " AND " + extraCondition.trim();
            }
        }

        String dataSql;
        if (finalCondition.isEmpty()) {
            dataSql = "SELECT * FROM " + viewName;
        } else {
            dataSql = "SELECT * FROM " + viewName + " WHERE " + finalCondition;
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> rows = (List<Map<String, Object>>) BASE_DAO.executeQuery(dataSql, new MapListProcessor());

        return ResultMessageUtil.toJSON(rows);
    }

    @POST
    @Path("query")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString query(Map<String, Object> data) { // 直接接收Map作为参数
        // IJsonForAPI iJsonForAPI = JsonFactoryForAPI.create(); // 不再需要解析复杂JSON
        // ApiQueryParam apiQueryParam = iJsonForAPI.fromJson(json.toJSONString(), ApiQueryParam.class); //移除
        // ApiUfinterface ufinterface = apiQueryParam.getUfinterface(); //移除

        if (data.containsKey("type")) { // 直接从data Map获取type
            String type = (String) data.get("type");
            try {
                // 将data Map传递给具体的查询方法
                return switch (type) {
                    case "queryStordoc" -> queryStordoc(data);
                    case "queryDept" -> queryDept(data);
                    case "queryCustomer" -> queryCustomer(data);
                    case "querySupplier" -> querySupplier(data);
                    case "queryMaterial" -> queryMaterial(data);
                    case "queryPsndoc" -> queryPsndoc(data);
//                    case "queryBom" -> queryBom(data);
                    case "queryMaterialClass" -> queryMaterialClass(data);
                    default -> ResultMessageUtil.exceptionToJSON(new Exception("不支持的查询类型: " + type));
                };
            } catch (Exception e) {
                // 捕获并返回异常信息
                return ResultMessageUtil.exceptionToJSON(e);
            }
        } else {
            return ResultMessageUtil.exceptionToJSON(new Exception("缺失接口类型,请检查参数"));
        }
    }

    /**
     * 查询BOM维护信息
     */
    private JSONString queryBom(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_BOM");
    }

    private JSONString queryCustomer(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_CUSTOMER");
    }

    private JSONString queryDept(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_DEPT");
    }

    /**
     * 查询物料信息
     */
    private JSONString queryMaterial(Map<String, Object> data) throws DAOException {
        // Map<String, Object> data = ufinterface.getData().getParamdata(); // 此行不再需要
        return baseQuery(data, "V_UAPBD_QUERYSYNC_MATERIAL");
    }

    /**
     * 查询物料分类
     */
    private JSONString queryMaterialClass(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_MATCLASS");
    }

    /**
     * 查询人员信息
     */
    private JSONString queryPsndoc(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_PSNDOC");
    }

    private JSONString queryStordoc(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_STORDOC");
    }

    private JSONString querySupplier(Map<String, Object> data) throws DAOException {
        return baseQuery(data, "V_UAPBD_QUERYSYNC_SUPPLIER");
    }

}