package com.cyksj.service.corp.impl;

import cn.hutool.core.date.DateTime;
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.config.corp.WeChatCorpFactory;
import com.cyksj.mapper.AddressMapper;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.corp.CorpUserAuthMapper;
import com.cyksj.mapper.corp.CorpUserMapper;
import com.cyksj.mapper.market.task.UserBindDetailMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.CorpWxOrderDonView;
import com.cyksj.model.request.corp.CorpCommonReq;
import com.cyksj.model.request.corp.CorpXmlMessage;
import com.cyksj.model.views.TicketView;
import com.cyksj.model.views.YHLXUserDetailView;
import com.cyksj.service.corp.CorpUserService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 项目名: 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;

	@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")));
			List<TicketView> ticketViews = beanSearcher.searchAll(TicketView.class, MapUtils.builder()
					.field(TicketView::getUserId, userIdList).op(Operator.InList)
					.field(TicketView::getGrStatus, List.of("validity", "outside")).op(Operator.InList)
					.build());
			DateTime now = DateTime.now();
			List<TicketView> tkCollect = ticketViews.stream().filter(tk -> {
				if (tk.getExpiryTime() != null && tk.getExpiryTime().before(now)) {
					return false;
				}
				return true;
			}).collect(Collectors.toList());
			view.setTicketViews(tkCollect);
			List<CorpWxOrderDonView> orderDonViews = beanSearcher.searchAll(CorpWxOrderDonView.class, MapUtils.builder()
					.field(CorpWxOrderDonView::getUserId, userIdList).op(Operator.InList)
					.orderBy(CorpWxOrderDonView::getId).desc()
					.build());
			view.setOrderDonViews(orderDonViews);
		}
		view.setMarkInfo(corpUser.getMarkInfo());
		if (userIdList.size() == 3) {
			view.setIsBind(true);
		}
		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);
	}

	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);
			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"));
			}
		} else {
			corpUser = corpUserMapper.selectOne(Wrappers.lambdaQuery(CorpUser.class).eq(CorpUser::getId, corpUserAuth.getCorpUserId()).last("limit 1"));
		}
		return corpUser;
	}
}
