package com.example.hospital.patient.wx.api.config;

import cn.hutool.core.map.MapUtil;
import com.example.hospital.patient.wx.api.db.dao.DoctorWorkPlanDao;
import com.example.hospital.patient.wx.api.db.dao.DoctorWorkPlanScheduleDao;
import com.example.hospital.patient.wx.api.db.dao.MedicalRegistrationDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;

@Slf4j
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
    @Resource
    private MedicalRegistrationDao medicalRegistrationDao;

    @Resource
    private DoctorWorkPlanDao doctorWorkPlanDao;

    @Resource
    private DoctorWorkPlanScheduleDao doctorWorkPlanScheduleDao;

    @Resource
    private RedisTemplate redisTemplate;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    @Transactional
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        if(key.startsWith("registration_payment_")){
            String outTradeNo = key.split("_")[2];
            medicalRegistrationDao.discardPayment(outTradeNo);
            doctorWorkPlanDao.releaseNumByOutTradeNo(outTradeNo);
            doctorWorkPlanScheduleDao.releaseNumByOutTradeNo(outTradeNo);
            HashMap map = medicalRegistrationDao.searchWorkPlanIdAndScheduleId(outTradeNo);
            int scheduleId = MapUtil.getInt(map, "doctorScheduleId");
            int workPlanId = MapUtil.getInt(map, "workPlanId");
            key = "doctor_schedule_" + scheduleId;
            if(redisTemplate.hasKey(key)){
                redisTemplate.opsForHash().increment(key,"num",-1);
            }
        }
        super.onMessage(message, pattern);
    }
}
