package com.wzj.soopin.member.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.service.IMemberService;
import com.wzj.soopin.member.service.ITencentIMServicce;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.mq.domain.MemberCreateEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 消息事件监听器
 *
 * @author ruoyi
 */
@Slf4j
@Component
@AllArgsConstructor
public class MemberCreateEventListener {


    private final IMemberService memberService;

    private final ITencentIMServicce tencentIMService;



    /**
     * 处理消息事件
     */
    @Async
    @EventListener
    @Transactional(rollbackFor = Exception.class)
    public void handleMessageEvent(MemberCreateEvent event) {
        try {
            // 提取消息和用户ID
            Map<String,Object> userMap = (Map<String,Object>)event.getSource();

            //先检查绑定该用户的会员是否存在
            if(userMap.get("userId")==null){
                return;
            }
            List<Member> memberList =  memberService.list(new LambdaQueryWrapper<Member>()
                .eq(Member::getUserId,userMap.get("userId"))
            );
            if(CollectionUtil.isNotEmpty(memberList)){
                Member member = memberList.get(0);
                if(!member.getPhoneHidden().equals(userMap.get("phonenumber"))){
                    //解绑
                    member.setUserId(0l);
                    memberService.updateById(member);
                }else{
                    //如果已经绑定过了 则不再更新
//                    return;
                }
            }

            //根据手机号查询会员
            memberList =  memberService.list(new LambdaQueryWrapper<Member>()
                    .eq(Member::getPhoneEncrypted, (String) userMap.get("phonenumber"))
            );

            //如果存在则绑定
            //如果不存在则创建
            if (!memberList.isEmpty() ){
                //绑定
                Member member = memberList.get(0);
                member.setUserId((Long) userMap.get("userId"));
                member.setRole(Integer.valueOf(userMap.get("role").toString()));
                memberService.updateById(member);
                //设置im账号为管理员
                tencentIMService.updateMemberRole(member);
            } else {
                //创建
                Member member=new Member();
                member.setNickname((String) userMap.get("nickName"));
                member.setPassword((String) userMap.get("password"));
                member.setPhoneHidden((String) userMap.get("phonenumber"));
                member.setAvatar((String) userMap.get("avatar"));
                member.setGender((Integer) userMap.get("sex"));
                member.setRole(Integer.valueOf(userMap.get("role").toString()));

                member.setUserId((Long) userMap.get("userId"));
                memberService.save(member);
                //创建im账号
                String userSig=tencentIMService.createTencentIMAccount(member);

                member.setUserSig(userSig);
                memberService.saveOrUpdate(member);

                //设置im账号为管理员
                tencentIMService.updateMemberRole(member);


            }

        } catch (Exception e) {
            log.error("处理消息事件失败", e);
        }
    }
}
