package com.xinelu.mobile.service.wechatofficialaccountcallback.impl;

import com.xinelu.common.enums.OfficialAccountEventEnum;
import com.xinelu.common.enums.SubscribeStatusEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.DateUtils;
import com.xinelu.manage.domain.officialaccountsubscribeevent.OfficialAccountSubscribeEvent;
import com.xinelu.manage.domain.officialaccounttemplateevent.OfficialAccountTemplateEvent;
import com.xinelu.manage.domain.residentinfo.ResidentInfo;
import com.xinelu.manage.mapper.officialaccountsubscribeevent.OfficialAccountSubscribeEventMapper;
import com.xinelu.manage.mapper.officialaccounttemplateevent.OfficialAccountTemplateEventMapper;
import com.xinelu.manage.mapper.patientinfo.PatientInfoMapper;
import com.xinelu.mobile.service.wechatofficialaccountcallback.WeChatOfficialAccountCallbackService;
import com.xinelu.mobile.vo.wechatofficialaccountcallback.WeChatOfficialAccountEventPushVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Description 院后微信公众号事件回调service实现
 * @Author 纪寒
 * @Date 2024-03-25 14:55:53
 * @Version 1.0
 */
@Service
@Slf4j
public class WeChatOfficialAccountCallbackServiceImpl implements WeChatOfficialAccountCallbackService {

    @Resource
    private PatientInfoMapper patientInfoMapper;
    @Resource
    private OfficialAccountTemplateEventMapper officialAccountTemplateEventMapper;
    @Resource
    private OfficialAccountSubscribeEventMapper officialAccountSubscribeEventMapper;

    /**
     * 院后微信公众号模板消息事件回调处理
     *
     * @param eventPushVO 模板消息事件回调数据
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleOfficialAccountTemplateEvent(WeChatOfficialAccountEventPushVO eventPushVO) {
        //查询患者信息
        ResidentInfo patientInfo = patientInfoMapper.getPatientInfoByOpenId(eventPushVO.getFromUserName());
        if (Objects.isNull(patientInfo)) {
            log.info("当前患者信息不存在，微信用户openid为：{}", eventPushVO.getFromUserName());
            return;
        }
        OfficialAccountTemplateEvent templateEvent = new OfficialAccountTemplateEvent();
        templateEvent.setPatientId(Objects.isNull(patientInfo.getId()) ? null : patientInfo.getId());
        templateEvent.setPatientName(StringUtils.isBlank(patientInfo.getPatientName()) ? "" : patientInfo.getPatientName());
        templateEvent.setOpenid(eventPushVO.getFromUserName());
        templateEvent.setOfficialAccountAppId(StringUtils.isBlank(eventPushVO.getToUserName()) ? "" : eventPushVO.getToUserName());
        templateEvent.setSendTime(StringUtils.isBlank(eventPushVO.getCreateTime()) ? null : DateUtils.timestampToLocalDateTime(Long.parseLong(eventPushVO.getCreateTime()) * 1000L));
        templateEvent.setMsgType(StringUtils.isBlank(eventPushVO.getMsgType()) ? "" : eventPushVO.getMsgType());
        templateEvent.setEventType(StringUtils.isBlank(eventPushVO.getEvent()) ? "" : eventPushVO.getEvent());
        templateEvent.setMsgId(StringUtils.isBlank(eventPushVO.getMsgId()) ? "" : eventPushVO.getMsgId());
        templateEvent.setStatus(StringUtils.isBlank(eventPushVO.getStatus()) ? "" : eventPushVO.getStatus());
        templateEvent.setCreateTime(LocalDateTime.now());
        templateEvent.setCreateBy("xinyilu");
        int insertTemplateEventCount = officialAccountTemplateEventMapper.insertOfficialAccountTemplateEvent(templateEvent);
        if (insertTemplateEventCount < 0) {
            log.error("院后微信公众号模板事件推送，新增模板事件消息信息失败，信息为：[{}]", templateEvent);
            throw new ServiceException("院后微信公众号模板事件推送记录信息失败！");
        }
        log.info("院后微信公众号模板事件推送处理成功！");
    }

    /**
     * 院后微信公众号取消和关注事件回调处理
     *
     * @param eventPushVO 公众号取消和关注事件回调数据
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleOfficialAccountSubscribeEvent(WeChatOfficialAccountEventPushVO eventPushVO) {
        //关注公众号事件
        if (OfficialAccountEventEnum.SUBSCRIBE.getInfo().equals(eventPushVO.getEvent())) {
            handleSubscribeEventInfo(eventPushVO, SubscribeStatusEnum.accept.getValue());
        }
        //取消关注公众号事件
        if (OfficialAccountEventEnum.UNSUBSCRIBE.getInfo().equals(eventPushVO.getEvent())) {
            handleSubscribeEventInfo(eventPushVO, SubscribeStatusEnum.rejet.getValue());
        }
    }

    /**
     * 处理公众号订阅信息
     *
     * @param eventPushVO     公众号取消和关注事件回调数据
     * @param subscribeStatus 订阅状态
     */
    private void handleSubscribeEventInfo(WeChatOfficialAccountEventPushVO eventPushVO, String subscribeStatus) {
        int subscribeEventCount = officialAccountSubscribeEventMapper.getSubscribeEventInfo(eventPushVO.getFromUserName());
        if (subscribeEventCount == 0) {
            //没有订阅过，直接新增
            OfficialAccountSubscribeEvent subscribeEvent = new OfficialAccountSubscribeEvent();
            subscribeEvent.setOpenid(eventPushVO.getFromUserName());
            subscribeEvent.setOfficialAccountAppId(StringUtils.isBlank(eventPushVO.getToUserName()) ? "" : eventPushVO.getToUserName());
            subscribeEvent.setSendTime(StringUtils.isBlank(eventPushVO.getCreateTime()) ? null : DateUtils.timestampToLocalDateTime(Long.parseLong(eventPushVO.getCreateTime()) * 1000L));
            subscribeEvent.setMsgType(StringUtils.isBlank(eventPushVO.getMsgType()) ? "" : eventPushVO.getMsgType());
            subscribeEvent.setEventType(StringUtils.isBlank(eventPushVO.getEvent()) ? "" : eventPushVO.getEvent());
            subscribeEvent.setSubscribeStatus(subscribeStatus);
            subscribeEvent.setCreateTime(LocalDateTime.now());
            subscribeEvent.setCreateBy("xinyilu");
            int insertSubscribeEvent = officialAccountSubscribeEventMapper.insertOfficialAccountSubscribeEvent(subscribeEvent);
            if (insertSubscribeEvent < 0) {
                log.error("院后微信公众号关注和取消事件，新增信息失败，信息为：[{}]", subscribeEvent);
                throw new ServiceException("新增院后微信公众号关注和取消事件信息失败！");
            }
        } else {
            //订阅过，修改
            OfficialAccountSubscribeEvent subscribeEvent = new OfficialAccountSubscribeEvent();
            subscribeEvent.setOpenid(eventPushVO.getFromUserName());
            subscribeEvent.setSendTime(StringUtils.isBlank(eventPushVO.getCreateTime()) ? null : DateUtils.timestampToLocalDateTime(Long.parseLong(eventPushVO.getCreateTime()) * 1000L));
            subscribeEvent.setEventType(StringUtils.isBlank(eventPushVO.getEvent()) ? "" : eventPushVO.getEvent());
            subscribeEvent.setSubscribeStatus(subscribeStatus);
            subscribeEvent.setUpdateTime(LocalDateTime.now());
            subscribeEvent.setUpdateBy("xinyilu");
            int updateSubscribeEvent = officialAccountSubscribeEventMapper.updateSubscribeEventInfo(subscribeEvent);
            if (updateSubscribeEvent < 0) {
                log.error("院后微信公众号关注和取消事件，修改信息失败，信息为：[{}]", subscribeEvent);
                throw new ServiceException("修改院后微信公众号关注和取消事件信息失败！");
            }
        }
    }
}
