package com.liquidnet.service.sweet.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.sweet.entity.SweetManual;
import com.liquidnet.service.sweet.entity.SweetManualSort;
import com.liquidnet.service.sweet.mapper.SweetManualSortMapper;
import com.liquidnet.service.sweet.service.ISweetManualSortService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.service.sweet.utils.RedisDataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 电子宣传手册显示内容表 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-07-23
 */
@Service
public class SweetManualSortServiceImpl extends ServiceImpl<SweetManualSortMapper, SweetManualSort> implements ISweetManualSortService {

    @Autowired
    private SweetManualSortMapper sweetManualSortMapper;
    @Autowired
    private RedisDataUtils redisDataUtils;

    @Override
    public ResponseDto<SweetManualSort> get(String manualId) {
        try {
            return ResponseDto.success(sweetManualSortMapper.selectOne(Wrappers.lambdaQuery(SweetManualSort.class).eq(SweetManualSort::getManualId, manualId)));
        } catch (Exception e) {
            return ResponseDto.failure();
        }
    }

    @Override
    public ResponseDto<Boolean> add(String manualId, String content) {
        try {
            int count = sweetManualSortMapper.selectCount(Wrappers.lambdaUpdate(SweetManualSort.class).eq(SweetManualSort::getManualId, manualId));
            if (count > 0) {
                SweetManualSort sweetManualSort = new SweetManualSort();
                sweetManualSort.setManualId(manualId);
                sweetManualSort.setShowPosition(content);
                sweetManualSort.setUpdatedAt(LocalDateTime.now());
                sweetManualSortMapper.update(sweetManualSort, Wrappers.lambdaUpdate(SweetManualSort.class).eq(SweetManualSort::getManualId, manualId));
            } else {
                SweetManualSort sweetManualSort = new SweetManualSort();
                sweetManualSort.setManualId(manualId);
                sweetManualSort.setShowPosition(content);
                sweetManualSort.setCreatedAt(LocalDateTime.now());
                sweetManualSortMapper.insert(sweetManualSort);
            }
            redisDataUtils.deleteSortRedisData(manualId);
        } catch (Exception e) {
            return ResponseDto.failure();
        }
        return ResponseDto.success();
    }
}
