package com.cyksj.service.user.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.enums.GatewayApiCode;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.market.task.UserBindDetailMapper;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.UserBindDetail;
import com.cyksj.service.user.UserBindRelationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/*
 *项目名: netflix
 *文件名: UserBindRelationServiceImpl
 *创建者: JavaZou
 *创建时间:2023/8/1 15:03
 */
@Service
@RequiredArgsConstructor
public class UserBindRelationServiceImpl implements UserBindRelationService {

	private final UserBindDetailMapper userBindDetailMapper;

	private final UserMapper userMapper;

	@Override
	public List<Long> getRelationUserIdList(Long userId, User selectUser) {
		if (userId == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);
		List<Long> userIds = new ArrayList<>();
		User user = Optional.ofNullable(selectUser).orElse(userMapper.selectById(userId));
		if (user == null) throw BusinessRuntimeException.getGatewayApiCode(GatewayApiCode.CMS_TOKEN_VALID);

		UserBindDetail userBindDetail;
		//微信用户
		if (StrUtil.isNotBlank(user.getUnionid()) || StrUtil.isNotEmpty(user.getOpenId())) {
			userIds.add(userId);
			userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
					.eq(UserBindDetail::getUserId, userId).last("limit 1"));
			if (userBindDetail == null) {
				return userIds;
			}
			if (userBindDetail.getPhoneUserId() != null) {
				userIds.add(userBindDetail.getPhoneUserId());
			}
			if (userBindDetail.getEmailUserId() != null) {
				userIds.add(userBindDetail.getEmailUserId());
			}
			return userIds;
		}
		Long phoneUserId = null;
		Long emailUserId = null;
		if (StrUtil.isNotBlank(user.getLoginPhone())) {
			phoneUserId = user.getId();
		}
		if (StrUtil.isNotBlank(user.getEmail())) {
			emailUserId = user.getId();
		}
		//非微信用户
		userBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
				.eq(phoneUserId != null, UserBindDetail::getPhoneUserId, phoneUserId)
				.eq(emailUserId != null, UserBindDetail::getEmailUserId, emailUserId)
				.last("limit 1"));
		if (userBindDetail == null) {
			userIds.add(userId);
			return userIds;
		}
		phoneUserId = userBindDetail.getPhoneUserId();
		emailUserId = userBindDetail.getEmailUserId();
		Long wxUserId = userBindDetail.getUserId();
		if (wxUserId != null) {
			userIds.add(wxUserId);
		}
		if (phoneUserId != null) {
			userIds.add(phoneUserId);
		}
		if (emailUserId != null) {
			userIds.add(emailUserId);
		}
		return userIds;
	}
}
