package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.HomeTemplateDAO;
import com.cool.store.dto.HomeTemplateDTO;
import com.cool.store.entity.HomeTemplateDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.response.HomeTemplateResponse;
import com.cool.store.service.HomeTemplateService;
import com.cool.store.utils.HomeTemplateTypeEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author: WangShuo
 * @Date: 2025/04/08/09:41
 * @Version 1.0
 * @注释:
 */
@Service
@Slf4j
public class HomeTemplateServiceImpl implements HomeTemplateService {

    @Resource
    private HomeTemplateDAO homeTemplateDAO;
    @Override
    public HomeTemplateResponse getHomeTemplateById(Long id) {
        HomeTemplateDO homeTemplateById = homeTemplateDAO.getHomeTemplateById(id);
        if (homeTemplateById != null){
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 HomeTemplateResponse 对象
            try {
                HomeTemplateResponse componentsJson = new HomeTemplateResponse();
                HomeTemplateDTO miniOpenComponentsJson = objectMapper.readValue(homeTemplateById.getMiniOpenComponentsJson(), HomeTemplateDTO.class);
                componentsJson.setMiniOpenSourceHomeTemplate(miniOpenComponentsJson);
                return componentsJson;
            } catch (JsonProcessingException e) {
                log.info("JSON解析失败:{}", JSONObject.toJSONString(e.getMessage()));
                throw new ServiceException(ErrorCodeEnum.GET_HOME_TEMPLATE_ERROR);
            }
        }
        return null;
    }
}
