package com.hz.pm.api.meeting.manage;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hz.pm.api.meeting.entity.domain.MeetingSettings;
import com.hz.pm.api.meeting.entity.enumeration.MeetingSettingsTypeEnum;
import com.hz.pm.api.meeting.entity.req.MeetingSettingsSaveReq;
import com.hz.pm.api.meeting.service.IMeetingSettingsService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * MeetingSettingSmanage
 * </p>
 *
 * @author WendyYang
 * @since 09:48 2023/12/27
 */
@Component
@AllArgsConstructor
public class MeetingSettingsManage {

    private final IMeetingSettingsService meetingSettingsService;

    private MeetingSettings getBySettingsType(MeetingSettingsTypeEnum settingsType){
        Wrapper<MeetingSettings> query = Wrappers.lambdaQuery(MeetingSettings.class)
                .eq(MeetingSettings::getSettingsType, settingsType);
        return meetingSettingsService.getOne(query);
    }

    public static  <T> T parseContent(String content,Class<T> tClass){
        return JSONUtil.toBean(content, tClass);
    }

    public MeetingSettingsSaveReq getSettings(MeetingSettingsTypeEnum settingsType){
        MeetingSettings settings = getBySettingsType(settingsType);
        if (settings == null) {
            return null;
        }
        MeetingSettingsSaveReq result = new MeetingSettingsSaveReq();
        result.setEnable(settings.getEnable());
        result.setSettingsType(settings.getSettingsType());
        result.setSettingsContent(JSONUtil.parseObj(settings.getSettingsContent()));
        return result;
    }

    public synchronized void saveSettings(MeetingSettingsSaveReq req) {
        MeetingSettings settings = getBySettingsType(req.getSettingsType());
        if (settings == null) {
            settings = new MeetingSettings();
        }
        settings.setSettingsType(req.getSettingsType());
        settings.setEnable(req.getEnable());
        settings.setSettingsContent(JSONUtil.toJsonStr(req.getSettingsContent()));
        meetingSettingsService.saveOrUpdate(settings);
    }

}
