package com.yida.data.device.telephone.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yida.data.common.core.entity.telephone.EduTelephoneCardMeal;
import com.yida.data.common.core.entity.telephone.EduTelephoneMeal;
import com.yida.data.device.telephone.mapper.EduTelephoneCardMealMapper;
import com.yida.data.device.telephone.service.EduTelephoneCardService;
import com.yida.data.device.telephone.service.EduTelephoneMealService;
import com.yida.data.rabbit.constant.RabbitConstant;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class TelephoneRabbitReceiver {

    private final EduTelephoneCardService eduTelephoneCardService;
    private final EduTelephoneCardMealMapper eduTelephoneCardMealMapper;
    private final EduTelephoneMealService eduTelephoneMealService;

    /**
     * 亲情电话套餐消费
     *
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(RabbitConstant.TELEPHONE_MEAL_QUEUE),
        exchange = @Exchange(RabbitConstant.TELEPHONE_EXCHANGE)
    ))
    public void meal(String msg) {
        log.info("接收消息，:[{}]", msg);
        JSONObject obj = JSONUtil.parseObj(msg);
        String studentId = obj.getStr("studentId");
        String identityId = obj.getStr("identityId");
        EduTelephoneMeal meal = eduTelephoneMealService.getById(Long.valueOf(identityId));
        //EduTelephoneCard card = eduTelephoneCardService.getOne(Wrappers.<EduTelephoneCard>lambdaQuery().eq(EduTelephoneCard::getStudentId, Long.valueOf(studentId)));
        // 查询上一套餐有效期结束时间
        EduTelephoneCardMeal cardMeal = eduTelephoneCardMealMapper.getLastMeal(Long.valueOf(studentId));
        if (cardMeal != null && cardMeal.getEndTime().isAfter(LocalDateTime.now())) {
            // 原有套餐未过期   更新结束时间
            cardMeal.setEndTime(cardMeal.getEndTime().plusMonths(meal.getMonth()).plusDays(meal.getDay()));
            eduTelephoneCardMealMapper.updateById(cardMeal);
        } else {
            // 新增套餐
            LocalDateTime startTime = LocalDateTime.now();
            cardMeal = new EduTelephoneCardMeal();
            cardMeal.setStudentId(Long.valueOf(studentId));
            cardMeal.setStartTime(startTime);
            cardMeal.setEndTime(startTime.plusMonths(meal.getMonth()).plusDays(meal.getDay()));
            eduTelephoneCardMealMapper.insert(cardMeal);
        }
    }
}
