package com.zhongshu.card.server.core.service.config;

import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.model.config.CommonConfigModel;
import com.zhongshu.card.client.model.config.CommonConfigParam;
import com.zhongshu.card.client.model.config.CommonConfigSearch;
import com.zhongshu.card.server.core.dao.config.CommonConfigDao;
import com.zhongshu.card.server.core.domain.config.CommonConfig;
import com.zhongshu.card.server.core.service.base.SuperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author TRX
 * @date 2024/11/5
 */
@Slf4j
@Service
public class CommonConfigService extends SuperService {

    @Autowired
    private CommonConfigDao commonConfigDao;

    public ResultContent saveUserConfig(CommonConfigParam param) {
        return saveInfo(param.getProjectOid(), getCurrentUserId(), param.getKey(), param.getData());
    }

    public ResultContent getUserConfig(CommonConfigSearch param) {
        CommonConfig config = commonConfigDao.findTopByProjectOidAndAboutIdAndKey(
                param.getProjectOid(), getCurrentUserId(), param.getKey());
        return ResultContent.buildSuccess(toModel(config));
    }

    private ResultContent saveInfo(String projectOid, String userId, String key, HashMap<String, Object> data) {
        CommonConfig config = commonConfigDao.findTopByProjectOidAndAboutIdAndKey(projectOid, userId, key);
        if (ObjectUtils.isEmpty(config)) {
            config = new CommonConfig();
        }
        config.setProjectOid(projectOid);
        config.setAboutId(userId);
        config.setKey(key);
        config.setData(data);
        commonConfigDao.save(config);
        return ResultContent.buildSuccess();
    }

    private CommonConfigModel toModel(CommonConfig entity) {
        CommonConfigModel model = new CommonConfigModel();
        if (ObjectUtils.isNotEmpty(entity)) {
            BeanUtils.copyProperties(entity, model);
        }
        return model;
    }
}
