package com.jwipc.sys.logic.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.constant.SequenceConfigConst;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.sys.convert.SequenceConvert;
import com.jwipc.sys.dto.SequenceEditDTO;
import com.jwipc.sys.dto.SequenceListDTO;
import com.jwipc.sys.entity.Sequence;
import com.jwipc.sys.logic.SequenceLogic;
import com.jwipc.sys.model.query.SequenceListQuery;
import com.jwipc.sys.service.ISequenceService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import static com.jwipc.constant.SequenceConfigConst.REDIS_TYPE;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class SequenceLogicImpl implements SequenceLogic {
    private final ISequenceService sequenceService;
    private final SequenceConvert sequenceConvert;
    private final StringRedisTemplate redisTemplate;

    @Override
    public PageView getPageList(SequenceListQuery query) {
        final Page<Sequence> page = PageUtil.toPage(query);
        final LambdaQueryWrapper<Sequence> sequenceLambdaQueryWrapper = new LambdaQueryWrapper<Sequence>().like(
                        StrUtil.isNotEmpty(query.getName()), Sequence::getName, query.getName())
                .eq(Objects.nonNull(query.getInfixRule()), Sequence::getInfixRule, query.getInfixRule())
                .orderByDesc(Sequence::getCreateTime);
        final List<Sequence> list = sequenceService.list(page, sequenceLambdaQueryWrapper);
        List<SequenceListDTO> sequenceListDTOS = sequenceConvert.entities2ListDTOs(list);

        //需要把redis中的valu取出来
        for (SequenceListDTO sequenceListDTO : sequenceListDTOS) {
            if (Objects.equals(sequenceListDTO.getType(), REDIS_TYPE)) {
                final String code = sequenceListDTO.getCode();
                String value = redisTemplate.opsForValue().get(SequenceConfigConst.REDIS_KEY_PREFIX + code);
                if (StrUtil.isNotEmpty(value)) {
                    sequenceListDTO.setValue(Integer.valueOf(value));
                }
            }
        }
        return PageUtil.getPV(sequenceListDTOS, page.getTotal());
    }

    @Override
    public SequenceEditDTO getForEdit(Long id) {
        final Sequence sequence = sequenceService.getById(id);
        return sequenceConvert.entity2EditDTO(sequence);
    }

    @Override
    public void update(SequenceEditDTO sequenceEditDTO) {
        Sequence sequence = sequenceConvert.editDTO2Entity(sequenceEditDTO);
        sequenceService.updateById(sequence);
    }
}