package com.bcxin.message.service.messagecenter;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.message.common.utils.IdGeneratorSnowflake;
import com.bcxin.message.dao.mapper.messagecenter.MsgAdminUserSenderMapper;
import com.bcxin.message.dtos.request.BindSenderRequest;
import com.bcxin.message.entity.messagecenter.MsgAdminUserSenderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * description：消息中心用户发送者表 service
 * author：linchunpeng
 * date：2023/11/17
 */
@Slf4j
@Service
public class MsgAdminUserSenderService extends ServiceImpl<MsgAdminUserSenderMapper, MsgAdminUserSenderEntity> {

    @Autowired
    private IdGeneratorSnowflake snowflake;

    /**
     * description：appid绑定sender
     * author：linchunpeng
     * date：2023/11/21
     */
    @Transactional
    public void bindSender(BindSenderRequest request) {
        MsgAdminUserSenderEntity msgAdminUserSenderEntity = this.findByAppidAndSender(request.getAppid(), request.getSender());
        if (request.getOperateType() == 1) {
            //绑定
            if (msgAdminUserSenderEntity == null) {
                this.bind(request.getAppid(), request.getSender(), request.getSenderType());
            }
        } else {
            //解绑
            if (msgAdminUserSenderEntity != null) {
                this.removeById(msgAdminUserSenderEntity.getId());
            }
        }
    }

    /**
     * description：通过appid 与 sender，查询绑定关系
     * author：linchunpeng
     * date：2023/11/21
     */
    public MsgAdminUserSenderEntity findByAppidAndSender(String appid, String sender) {
        LambdaQueryChainWrapper<MsgAdminUserSenderEntity> lqw = this.lambdaQuery();
        lqw.eq(MsgAdminUserSenderEntity::getAppid, appid);
        lqw.eq(MsgAdminUserSenderEntity::getSender, sender);
        return lqw.one();
    }

    /**
     * description：创建绑定sender关系
     * author：linchunpeng
     * date：2023/11/21
     */
    private void bind(String appid, String sender, String senderType) {
        MsgAdminUserSenderEntity msgAdminUserSenderEntity = new MsgAdminUserSenderEntity();
        msgAdminUserSenderEntity.setId(snowflake.snowflakeId());
        msgAdminUserSenderEntity.setAppid(appid);
        msgAdminUserSenderEntity.setSender(sender);
        msgAdminUserSenderEntity.setSenderType(senderType);
        msgAdminUserSenderEntity.setCreateTime(new Date());
        msgAdminUserSenderEntity.setUpdateTime(new Date());
        this.save(msgAdminUserSenderEntity);
    }

}
