package com.rf.psychological.miniapp.praise.service.impl;

import cn.hutool.core.date.DateUtil;
import com.rf.psychological.miniapp.praise.model.PraiseEntity;
import com.rf.psychological.miniapp.praise.repository.PraiseRepository;
import com.rf.psychological.miniapp.praise.service.PraiseService;
import com.rf.psychological.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description:点赞接口
 * @Author: mimang
 * @Date: 2023/5/26
 */
@Service
public class PraiseServiceImpl implements PraiseService {

    @Autowired
    private PraiseRepository repository;

    @Override
    public PraiseEntity save(PraiseEntity entity) {
        //1.首先判断该点赞操作是否存在，若存在取消，2.该点赞不存在，相反状态下是否存在，若存在先取消再保存
        PraiseEntity old = isPraise(entity.getBusinessId(), entity.getUserId(), entity.getType());
        if (old != null){
            return cancel(old);
        }else {
            //查询相反类型点赞是否存在，若存在取消掉，反之继续
            String type ;
            if (entity.getType().equals(Constant.DEFAULT_VALUE_ZERO)){
                type = Constant.DEFAULT_VALUE_ONE;
            }else {
                type = Constant.DEFAULT_VALUE_ZERO;
            }
            PraiseEntity clickEntity = isPraise(entity.getBusinessId(), entity.getUserId(),type);
            if (clickEntity != null){
                cancel(clickEntity);
            }
        }

        entity.setCreateTime(DateUtil.now());
        entity.setStatus(Constant.DEFAULT_VALUE_ZERO);
        return repository.save(entity);
    }

    /**
     * 获取到
     * @param businessId
     * @return
     */
    @Override
    public List<Map> queryByBusinessId(String businessId) {
        return repository.queryAllByBusinessIdGroupByType(businessId);
    }

    @Override
    public PraiseEntity findById(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public PraiseEntity cancel(PraiseEntity entity) {
        entity.setStatus(Constant.DEFAULT_VALUE_ONE);
        entity.setUpdateTime(DateUtil.now());
        return repository.save(entity);
    }

    @Override
    public PraiseEntity isPraise(String businessId, String userId, String type) {
        return repository.findByBusinessIdAndUserIdAndTypeAndStatus(businessId,userId,type,Constant.DEFAULT_VALUE_ZERO);
    }

    @Override
    public PraiseEntity isPraise(String businessId, String userId) {
        return repository.findByBusinessIdAndUserIdAndStatus(businessId,userId,Constant.DEFAULT_VALUE_ZERO);
    }

}
