package com.fzm.mall.server.admin.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.config.Redis;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.order.entity.dto.ConfigDTO;
import com.fzm.mall.server.admin.order.entity.dto.ConfigUpdateDTO;
import com.fzm.mall.server.admin.order.mapper.ConfigMapper;
import com.fzm.mall.server.admin.order.model.Config;
import com.fzm.mall.server.admin.order.service.IConfigService;
import com.fzm.mall.server.admin.util.CopyUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 订单中心-订单设置 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-03-17
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {

    private final ConfigMapper configMapper;
    private final Redis redis;

    @Override
    public void update(ConfigUpdateDTO configUpdateDTO) {
        Config config = CopyUtil.to(configUpdateDTO, Config.class);

        UpdateWrapper<Config> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", config.getId())
                .eq("update_time", config.getUpdateTime());
        int update = configMapper.update(config, wrapper);
        if (update == 0) {
            throw new MyException(MallResponseError.UPDATE_FAIL);
        }

        flushConfig(config);
    }

    /**
     * 刷新缓存中的配置
     *
     * @param config
     */
    private void flushConfig(Config config) {
        redis.del(Config.ORDER_CONFIG_REDIS_KEY);

        redis.setKey(Config.ORDER_CONFIG_REDIS_KEY, JSON.toJSONString(config));
    }

    @Override
    public ConfigDTO read(String id) {
        QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Config config = configMapper.selectOne(queryWrapper);

        return CopyUtil.to(config, ConfigDTO.class);
    }

    @Override
    public List<ConfigDTO> listAll() {
        QueryWrapper<Config> queryWrapper = new QueryWrapper<>();

        List<Config> list = configMapper.selectList(queryWrapper);
        return CopyUtil.toList(list, ConfigDTO.class);
    }
}
