package com.sqx.modules.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.constant.RedisKey;
import com.sqx.common.utils.RedisUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author fang
 * @date 2020/7/8
 */
@Service
@RequiredArgsConstructor
public class CommonInfoServiceImpl extends ServiceImpl<CommonInfoDao, CommonInfo> implements CommonInfoService {

    private final CommonInfoDao commonInfoDao;

    private final RedisUtils redisUtils;

    @Override
    public Result update(CommonInfo commonInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        commonInfo.setCreateAt(sdf.format(now));
        commonInfoDao.updateById(commonInfo);

        // 缓存失效
        redisUtils.delete(String.format(RedisKey.COMMON_INFO_CACHE_KEY, commonInfo.getType()));
        return Result.success();
    }


    @Override
    public CommonInfo findOne(int id) {
        String key = String.format(RedisKey.COMMON_INFO_CACHE_KEY, id);
        CommonInfo commonInfo = (CommonInfo) redisUtils.get(key);
        if (ObjectUtil.isNull(commonInfo)) {
            commonInfo = commonInfoDao.findOne(id);

            redisUtils.set(key, commonInfo, RedisUtils.HOUR_ONE_EXPIRE);
        }
        return commonInfo;
    }

    @Override
    public Result delete(long id) {
        commonInfoDao.deleteById(id);
        return Result.success();
    }


    @Override
    public Result updateBody(CommonInfo commonInfo) {
        commonInfoDao.updateById(commonInfo);

        // 缓存失效
        redisUtils.delete(String.format(RedisKey.COMMON_INFO_CACHE_KEY, commonInfo.getType()));
        return Result.success();
    }

    @Override
    public Result findByType(Integer type) {
        return Result.success().put("data",commonInfoDao.findOne(type));
    }

    @Override
    public Result findByTypeAndCondition(String condition) {
        return Result.success().put("data",commonInfoDao.findByCondition(condition));
    }


}