package com.playlet.web.service.app.impl;

import com.playlet.system.domain.PlayletPublicDetail;
import com.playlet.system.domain.PublicStarRecord;
import com.playlet.system.service.IPlayletPublicDetailService;
import com.playlet.system.service.IPublicStarRecordService;
import com.playlet.web.service.app.PublicStarRecordAppService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PublicStarRecordAppServiceImpl implements PublicStarRecordAppService {

    private final IPublicStarRecordService iPublicStarRecordService;

    private final IPlayletPublicDetailService iPlayletPublicDetailService;

    @Override
    public void addRecord(PublicStarRecord publicStarRecord) {
        publicStarRecord.setCreateTime(new Date());
        iPublicStarRecordService.insertPublicStarRecord(publicStarRecord);
        // 增加文章点赞数量
        PlayletPublicDetail detail = iPlayletPublicDetailService.getById(publicStarRecord.getDetailId());
        if(detail != null){
            if(detail.getStarCount() == null){
                detail.setStarCount("1");
            }else {
                detail.setStarCount(String.valueOf(Long.parseLong(detail.getStarCount()) + 1));
            }
        }
        iPlayletPublicDetailService.updateById(detail);
    }

    @Override
    public PublicStarRecord queryRecord(PublicStarRecord publicStarRecord) {
        return iPublicStarRecordService
                .lambdaQuery()
                .eq(PublicStarRecord::getDetailId, publicStarRecord.getDetailId())
                .eq(PublicStarRecord::getUserId, publicStarRecord.getUserId())
                .one();
    }

    @Override
    public void deleteRecord(PublicStarRecord publicStarRecord) {
        PublicStarRecord record = iPublicStarRecordService
                .lambdaQuery()
                .eq(PublicStarRecord::getDetailId, publicStarRecord.getDetailId())
                .eq(PublicStarRecord::getUserId, publicStarRecord.getUserId())
                .one();
        if(record != null){
            iPublicStarRecordService.removeById(record.getId());

            // 增加文章点赞数量
            PlayletPublicDetail detail = iPlayletPublicDetailService.getById(publicStarRecord.getDetailId());
            if(detail != null){
                detail.setStarCount(String.valueOf(Long.parseLong(detail.getStarCount()) - 1));
            }
            iPlayletPublicDetailService.updateById(detail);
        }
    }
}
