package com.gxwebsoft.common.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.system.mapper.SettingMapper;
import com.gxwebsoft.common.system.service.SettingService;
import com.gxwebsoft.common.system.entity.Setting;
import com.gxwebsoft.common.system.param.SettingParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.val;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

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

/**
 * 系统设置Service实现
 *
 * @author WebSoft
 * @since 2022-11-19 13:54:27
 */
@Service
public class SettingServiceImpl extends ServiceImpl<SettingMapper, Setting> implements SettingService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageResult<Setting> pageRel(SettingParam param) {
        PageParam<Setting, SettingParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<Setting> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Setting> listRel(SettingParam param) {
        List<Setting> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Setting, SettingParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Setting getByIdRel(Integer settingId) {
        SettingParam param = new SettingParam();
        param.setSettingId(settingId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public JSONObject getBySettingKey(String key) {
      Setting setting = this.getOne(new QueryWrapper<Setting>().eq("setting_key", key), false);
      return JSON.parseObject(setting.getContent());
    }

    @Override
    public Setting getData(String settingKey) {
      return query().eq("setting_key", settingKey).one();
    }

    @Override
    public JSONObject getCache(String key) {
      final String cache = stringRedisTemplate.opsForValue().get(key);
      final JSONObject jsonObject = JSONObject.parseObject(cache);
      if(jsonObject == null){
        throw new BusinessException("域名未配置");
      }
      return jsonObject;
    }

}
