package com.cyksj.service.corp.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.StringUtil;
import com.cyksj.config.corp.WeChatCorpFactory;
import com.cyksj.mapper.*;
import com.cyksj.mapper.corp.CorpFollowMapper;
import com.cyksj.mapper.corp.CorpUserAuthMapper;
import com.cyksj.mapper.corp.CorpUserMapper;
import com.cyksj.mapper.corp.kf.CorpKfUserMapper;
import com.cyksj.mapper.manage.cms.CmsUserMapper;
import com.cyksj.mapper.market.task.UserBindDetailMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.kf.CorpKfUserInfo;
import com.cyksj.model.request.corp.CorpCommonReq;
import com.cyksj.model.request.corp.CorpXmlMessage;
import com.cyksj.model.views.YHLXUserDetailView;
import com.cyksj.service.corp.CorpUserService;
import com.cyksj.service.corp.WxCorpOps;
import com.cyksj.service.corp.msg.CorpEventActionService;
import com.cyksj.service.user.UserBindRelationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 项目名: yhlxj
 * 文件名: CorpUserServiceImpl
 * 创建者: JavaZou
 * 创建时间:2023/12/14 16:33
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CorpUserServiceImpl implements CorpUserService {

	private final CorpEventActionService corpEventActionService;

	private final CorpUserMapper corpUserMapper;

	private final UserMapper userMapper;

	private final BeanSearcher beanSearcher;

	private final AddressMapper addressMapper;

	private final CorpUserAuthMapper corpUserAuthMapper;

	private final UserBindRelationService userBindRelationService;

	private final OrderDonMapper orderDonMapper;

	private final UserBindDetailMapper userBindDetailMapper;

	private final SpotifyUserSelfServiceRecordMapper spotifyUserSelfServiceRecordMapper;

	private final UserIdentityMapper userIdentityMapper;

	private final WxCorpOps wxCorpOps;

	private final CorpKfUserMapper corpKfUserMapper;

	private final CorpFollowMapper corpFollowMapper;

	private final CmsUserMapper cmsUserMapper;

	private final PhoneCodeMapper phoneCodeMapper;

	@Override
	public YHLXUserDetailView getUserDetailView(String externalUserid, String corpId) throws Exception {
		CorpUser corpUser = getExternalUserId(corpId, externalUserid);
		if (corpUser == null) {
			log.info("该客户{}不存在", externalUserid);
			return new YHLXUserDetailView();
		}
		//获取用户基本信息
		if (StrUtil.isEmpty(corpUser.getUnionid())) {
			log.info("该客户{}不是微信用户或未关联unionId", externalUserid);
			return new YHLXUserDetailView();
		}
		Long corpUserUserId = corpUser.getUserId();
		User user;
		if (corpUserUserId == 0) {
			user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUnionid, corpUser.getUnionid()).last("limit 1"));
			if (user == null) {
				log.info("该客户{}不是银河用户", externalUserid);
				return new YHLXUserDetailView();
			}
			corpUser.setUserId(user.getId());
			corpUserMapper.updateById(corpUser);
		}else {
			user = Optional.ofNullable(userMapper.selectById(corpUserUserId)).orElseGet(()->{
				User user1 = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUnionid, corpUser.getUnionid()).last("limit 1"));
				corpUser.setUserId(user1.getId());
				corpUserMapper.updateById(corpUser);
				return user1;
			});
		}
		//关联关系
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(corpUser.getUserId(), user);
		YHLXUserDetailView view = Optional.ofNullable(beanSearcher.searchFirst(YHLXUserDetailView.class, MapUtils.builder().field(YHLXUserDetailView::getUserId, corpUser.getUserId()).op(Operator.Equal).build())).orElse(new YHLXUserDetailView());
		if (view.getUserId() != null) {
			view.setAddress(addressMapper.selectOne(Wrappers.lambdaQuery(Address.class).eq(Address::getUserId, view.getUserId()).eq(Address::getIsDefault, true).last("limit 1")));

			UserBindDetail bindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
					.eq(UserBindDetail::getUserId, user.getId())
					.last("limit 1"));
			if (bindDetail != null) {
				if (bindDetail.getPhoneUserId() != null || bindDetail.getEmailUserId() != null) {
					//用户绑定信息
					view.setUserBindInfos(userMapper.selectUserById(bindDetail.getPhoneUserId(), bindDetail.getEmailUserId()));
				}
			}
		}
		view.setMarkInfo(corpUser.getMarkInfo());
		if (userIdList.size() == 3) {
			view.setIsBind(true);
		}
		Integer count = spotifyUserSelfServiceRecordMapper.selectCount(Wrappers.lambdaQuery(SpotifyUserSelfServiceRecord.class)
				.in(SpotifyUserSelfServiceRecord::getUserId, userIdList));
		view.setIsSpotifySelfService(count > 0);

		Integer count2 = userIdentityMapper.selectCount(Wrappers.lambdaQuery(UserIdentity.class)
				.in(UserIdentity::getUserId, userIdList)
				.eq(UserIdentity::getTag, UserIdentity.Tag.VIP));
		view.setIsVip(count2 > 0);
		//微信客服 用户
		view.setCorpKfUser(getCorpKfUser(externalUserid));
		return view;
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void bindOtherUsersByOrderNo(CorpCommonReq corpCommonReq) throws Exception {
		String externalUserid = corpCommonReq.getExternalUserid();
		String corpId = corpCommonReq.getCorpId();
		String orderNo = corpCommonReq.getOrderNo();
		if (StrUtil.isEmpty(orderNo)) {
			throw BusinessRuntimeException.getInstance("用户订单号不为空");
		}
		CorpUser corpUser = getExternalUserId(corpId, externalUserid);
		if (corpUser == null) {
			throw BusinessRuntimeException.getInstance("添加用户不存在");
		}
		if (StrUtil.isEmpty(corpUser.getUnionid())) {
			throw BusinessRuntimeException.getInstance("该用户不是微信用户");
		}
		OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
				.eq(OrderDon::getOrderNo, orderNo)
				.last("limit 1"));
		if (orderDon == null) {
			throw BusinessRuntimeException.getInstance("该订单号不存在");
		}
		Long orderDonUserId = orderDon.getUserId();
		User orderUser = userMapper.selectById(orderDonUserId);
		if (StrUtil.isNotBlank(orderUser.getUnionid())) {
			throw BusinessRuntimeException.getInstance("该订单号对应的用户是微信用户,无法绑定");
		}
		UserBindDetail orderUserBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
				.eq(StrUtil.isNotBlank(orderUser.getLoginPhone()), UserBindDetail::getPhoneUserId, orderDonUserId)
				.eq(StrUtil.isNotBlank(orderUser.getEmail()), UserBindDetail::getEmailUserId, orderDonUserId));
		if (orderUserBindDetail != null && orderUserBindDetail.getUserId() != null) {
			throw BusinessRuntimeException.getInstance("该订单号对应的用户已绑定微信");
		}
		User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUnionid, corpUser.getUnionid()).last("limit 1"));
		if (user == null) {
			user = new User();
			user.setNickname(corpUser.getName());
			user.setHeadimgurl(corpUser.getAvatar());
			user.setUnionid(corpUser.getUnionid());
			userMapper.insert(user);
		}
		corpUser.setUserId(user.getId());
		corpUserMapper.updateById(corpUser);

		//是否已绑定
		UserBindDetail corpUserBindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
				.eq(UserBindDetail::getUserId, corpUser.getUserId()).last("limit 1"));

		if (corpUserBindDetail != null && orderUserBindDetail != null) {
			throw BusinessRuntimeException.getInstance("已有绑定其他用户信息");
		}

		if (corpUserBindDetail != null) {
			String phone = corpUserBindDetail.getPhone();
			String email = corpUserBindDetail.getEmail();
			if (StrUtil.isNotBlank(orderUser.getLoginPhone()) && StrUtil.isNotBlank(phone)) {
				throw BusinessRuntimeException.getInstance("该微信用户已绑定手机订单用户");
			}

			if (StrUtil.isNotBlank(orderUser.getEmail()) && StrUtil.isNotBlank(email)) {
				throw BusinessRuntimeException.getInstance("该微信用户已绑定邮箱订单用户");
			}
		}

		UserBindDetail bindDetail = null;
		if (orderUserBindDetail != null) {
			bindDetail = orderUserBindDetail;
		}

		if (corpUserBindDetail != null) {
			bindDetail = corpUserBindDetail;
		}

		bindDetail = Optional.ofNullable(bindDetail).orElse(new UserBindDetail());

		bindDetail.setUserId(user.getId());
		if (StrUtil.isNotBlank(orderUser.getLoginPhone())) {
			bindDetail.setPhone(orderUser.getLoginPhone());
			bindDetail.setPhoneUserId(orderDonUserId);
		}

		if (StrUtil.isNotBlank(orderUser.getEmail())) {
			bindDetail.setEmail(orderUser.getEmail());
			bindDetail.setEmailUserId(orderDonUserId);
		}

		if (bindDetail.getId() == null) {
			userBindDetailMapper.insert(bindDetail);
		} else {
			userBindDetailMapper.updateById(bindDetail);
		}
	}


	@Override
	public void markCorpUser(CorpCommonReq corpCommonReq) throws Exception {
		String markInfo = corpCommonReq.getMarkInfo();
		CorpUser corpUser = getExternalUserId(corpCommonReq.getCorpId(), corpCommonReq.getExternalUserid());
		if (corpUser == null) {
			throw BusinessRuntimeException.getInstance("该用户不存在");
		}
		if (StrUtil.isEmpty(markInfo)) {
			markInfo = StrUtil.EMPTY;
		}
		corpUser.setMarkInfo(markInfo);

		corpUserMapper.updateById(corpUser);
	}

	@Override
	public void spotifySelfService(Long orderId) {
		OrderDon orderDon = orderDonMapper.selectById(orderId);
		if (orderDon == null) {
			return;
		}
		Long userId = orderDon.getUserId();
		Integer selectCount = spotifyUserSelfServiceRecordMapper.selectCount(Wrappers.lambdaQuery(SpotifyUserSelfServiceRecord.class)
				.eq(SpotifyUserSelfServiceRecord::getUserId, userId));
		if (selectCount > 0) {
			return;
		}
		try {
			SpotifyUserSelfServiceRecord spotifyUserSelfServiceRecord = new SpotifyUserSelfServiceRecord();
			spotifyUserSelfServiceRecord.setUserId(userId);
			spotifyUserSelfServiceRecordMapper.insert(spotifyUserSelfServiceRecord);
		} catch (DuplicateKeyException e) {

		}
	}

	@Override
	public String getPhoneTmpCode(String phone) {
		PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class)
				.eq(PhoneCode::getPhone, phone).last("limit 1"));
		if (phoneCode == null) {
			phoneCode = new PhoneCode();
		}
		String code = StringUtil.getRandomCodeStr(null);
		phoneCode.setCode(code);
		if (phoneCode.getId() == null) {
			phoneCodeMapper.insert(phoneCode);
		} else phoneCodeMapper.updateById(phoneCode);
		return code;
	}

	public CorpUser getExternalUserId(String corpId, String externalUserid) throws Exception {
		WxCorpApp wxCorpApp = WeChatCorpFactory.getCorpConfigStrategy(corpId);

		LambdaQueryWrapper<CorpUserAuth> corpUserAuthWrapper = Wrappers.lambdaQuery(CorpUserAuth.class)
				.eq(CorpUserAuth::getExternalUserid, externalUserid)
				.eq(CorpUserAuth::getWxCorpId, wxCorpApp.getId()).last("limit 1");
		CorpUserAuth corpUserAuth = corpUserAuthMapper.selectOne(corpUserAuthWrapper);
		CorpUser corpUser = null;
		if (corpUserAuth == null) {
			//尝试添加客户
			CorpXmlMessage message = new CorpXmlMessage();
			message.setToUserName(corpId);
			message.setExternalUserId(externalUserid);
			try {
				corpEventActionService.addExternalContact(message, null);
				corpUserAuth = corpUserAuthMapper.selectOne(corpUserAuthWrapper);
				if (corpUserAuth != null) {
					corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class).eq(CorpUser::getId, corpUserAuth.getCorpUserId()).last("limit 1"));
				}
			} catch (Exception e) {
				if (corpUser == null) {
					corpUser = new CorpUser();
					CorpKfUserInfo corpKfUserInfo = wxCorpOps.getCorpKfUserInfo(externalUserid);
					corpUser.setUnionid(corpKfUserInfo.getUnionid());
					corpUser.setName(corpKfUserInfo.getNickname());
					corpUser.setGender(corpKfUserInfo.getGender());
					corpUser.setAvatar(corpKfUserInfo.getAvatar());
					corpUser.setType(1);
					corpUser.setUserId(0l);
					corpUserMapper.insert(corpUser);

					corpUserAuth = new CorpUserAuth();
					corpUserAuth.setWxCorpId(wxCorpApp.getId());
					corpUserAuth.setCorpUserId(corpUser.getId());
					corpUserAuth.setExternalUserid(corpKfUserInfo.getExternalUserid());
					corpUserAuthMapper.insert(corpUserAuth);
				}
			}
		} else {
			corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class).eq(CorpUser::getId, corpUserAuth.getCorpUserId()).last("limit 1"));
		}
		return corpUser;
	}

	private CorpKfUser getCorpKfUser(String externalUserid) {
		//微信客服用户信息
		CorpKfUser corpKfUser = corpKfUserMapper.selectOne(Wrappers.lambdaQuery(CorpKfUser.class)
				.eq(CorpKfUser::getExternalUserid, externalUserid)
				.last("limit 1"));
		if (corpKfUser != null) {
			if (corpKfUser.getIsDevice()) {
				CorpFollow corpFollow = corpFollowMapper.selectOne(Wrappers.lambdaQuery(CorpFollow.class)
						.eq(CorpFollow::getUserid, corpKfUser.getFollowId())
						.last("limit 1"));
				String followName = null;
				if (corpFollow != null) {
					followName = corpFollow.getName();
					if (corpFollow.getCmsUserId() != null) {
						CmsUser cmsUser = cmsUserMapper.selectById(corpFollow.getCmsUserId());
						if (cmsUser != null) {
							followName = cmsUser.getNickname();
						}
					}
				}
				corpKfUser.setFollowName(followName);
			}
		}
		return corpKfUser;
	}
}
