package com.wzj.soopin.member.business.impl;

import com.wzj.soopin.member.business.IMemberBusiness;
import com.wzj.soopin.member.convert.MemberConvert;
import com.wzj.soopin.member.domain.bo.MemberBO;
import com.wzj.soopin.member.domain.po.Fans;
import com.wzj.soopin.member.domain.po.Member;
import com.wzj.soopin.member.domain.vo.MemberVO;
import com.wzj.soopin.member.service.IFansService;
import com.wzj.soopin.member.service.IMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BusinessImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@AllArgsConstructor
@Slf4j
public class MemberBusinessImpl extends BusinessImpl<IMemberService, MemberConvert, MemberVO, MemberBO, Member>
    implements IMemberBusiness {

    private final IFansService fansService;
    @Override
    public void bindSpread(MemberBO memberBO) {
        //获取用户信息
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("用户未登录");
        }

        //检查推广人
        Long memberId = loginUser.getUserId();
        //检查推广人是否绑定
        Member member = service.getById(loginUser.getUserId());
        if (member.getSpreadUid() != null) {
            throw new ServiceException("用户已绑定推广人");
        }
        //检查推广人是否存在
        Member spreadMember = service.getById(memberBO.getId());
        if (spreadMember == null) {
            throw new ServiceException("推广人不存在");
        }
        //更新用户的推广人
        member = Member.builder().id(memberId).spreadUid(spreadMember.getId()).spreadTime(LocalDateTime.now()).build();
        service.updateById(member);

        //两人互加好友

        Fans fans=new Fans();
        fans.setVloggerId(memberId);
        fans.setFanId(spreadMember.getId());
        fans.setFriendFlag(1);
        fans.setBothFriend(1);
        fansService.save(fans);
        log.info("用户{}关注了用户{}",memberId,spreadMember.getId());

        //被关注人也关注用户
        Fans fans2=new Fans();
        fans2.setVloggerId(spreadMember.getId());
        fans2.setFanId(memberId);
        fans2.setFriendFlag(1);
        fans2.setBothFriend(1);
        fansService.save(fans2);
        log.info("用户{}关注了用户{}",spreadMember.getId(),memberId);
    }

    @Override
    public void bindWechat(MemberBO memberBO) {

    }


}
