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.SweetManualSort;
import com.liquidnet.service.sweet.entity.SweetManualSortMdsk;
import com.liquidnet.service.sweet.mapper.SweetManualSortMdskMapper;
import com.liquidnet.service.sweet.service.ISweetManualSortMdskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.service.sweet.utils.RedisDataUtils;
import com.liquidnet.service.sweet.utils.RedisMDSKDataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 电子宣传手册显示内容表 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-08-09
 */
@Service
public class SweetManualSortMdskServiceImpl extends ServiceImpl<SweetManualSortMdskMapper, SweetManualSortMdsk> implements ISweetManualSortMdskService {

    @Autowired
    private SweetManualSortMdskMapper sweetManualSortMdskMapper;
    @Autowired
    private RedisMDSKDataUtils redisDataUtils;

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

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

}
