package com.ycwl.basic.pricing.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ycwl.basic.pricing.dto.BundleProductItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 一口价商品列表类型处理器
 */
@Slf4j
public class BundleProductListTypeHandler extends BaseTypeHandler<List<BundleProductItem>> {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final TypeReference<List<BundleProductItem>> typeReference = new TypeReference<List<BundleProductItem>>() {};

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<BundleProductItem> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
            log.debug("序列化商品列表: {}", json);
        } catch (JsonProcessingException e) {
            log.error("序列化商品列表失败", e);
            throw new SQLException("序列化商品列表失败", e);
        }
    }

    @Override
    public List<BundleProductItem> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJson(json, columnName);
    }

    @Override
    public List<BundleProductItem> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJson(json, "columnIndex:" + columnIndex);
    }

    @Override
    public List<BundleProductItem> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJson(json, "columnIndex:" + columnIndex);
    }

    private List<BundleProductItem> parseJson(String json, String source) {
        if (json == null || json.trim().isEmpty()) {
            log.debug("从{}获取的JSON为空，返回空列表", source);
            return new ArrayList<>();
        }

        try {
            List<BundleProductItem> result = objectMapper.readValue(json, typeReference);
            log.debug("从{}反序列化商品列表成功，数量: {}", source, result != null ? result.size() : 0);
            return result != null ? result : new ArrayList<>();
        } catch (JsonProcessingException e) {
            log.error("从{}反序列化商品列表失败，JSON: {}", source, json, e);
            return new ArrayList<>();
        }
    }
}