package com.cyksj.service.corp.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Codec;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.corp.CorpWxYlFollowConfigMapper;
import com.cyksj.mapper.corp.CorpWxYlRecordMapper;
import com.cyksj.mapper.market.task.UserBindDetailMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.TempCorpFollowCodeReq;
import com.cyksj.model.request.corp.CorpFollowContact;
import com.cyksj.model.response.UserInfoResp;
import com.cyksj.model.views.CorpUserFollowView;
import com.cyksj.service.corp.CorpUserFrontService;
import com.cyksj.service.corp.WxCorpOps;
import com.cyksj.service.user.UserBindRelationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 项目名: yhlxj2
 * 文件名: CorpUserFrontServiceImpl
 * 创建者: JavaZou
 * 创建时间:2025/3/11 16:29
 */
@Service
@RequiredArgsConstructor
public class CorpUserFrontServiceImpl implements CorpUserFrontService {
	private final UserBindDetailMapper userBindDetailMapper;

	private final BeanSearcher beanSearcher;

	private final UserMapper userMapper;

	private final WxCorpOps wxCorpOps;

	private final SysConfigMapper sysConfigMapper;

	private final UserBindRelationService userBindRelationService;

	private final OrderDonMapper orderDonMapper;

	private final CorpWxYlRecordMapper corpWxYlRecordMapper;

	private final CorpWxYlFollowConfigMapper corpWxYlFollowConfigMapper;

	@Override
	public UserInfoResp getUserInfoResp(long userId, Integer type) {
		UserInfoResp userInfoResp = new UserInfoResp();
		User user = userMapper.selectById(userId);
		if (type == 0 || type == 1) {
			String unionId = user.getUnionid();
			if (StrUtil.isEmpty(unionId)) {
				//获取绑定的微信用户id
				UserBindDetail bindDetail = userBindDetailMapper.selectOne(Wrappers.lambdaQuery(UserBindDetail.class)
						.and(qr -> qr.eq(UserBindDetail::getPhoneUserId, user.getId()).or().eq(UserBindDetail::getEmailUserId, user.getId()))
						.last("limit 1"));
				if (bindDetail != null && bindDetail.getUserId() != null) {
					User wxUser = userMapper.selectById(bindDetail.getUserId());
					if (wxUser != null) {
						unionId = wxUser.getUnionid();
					}
				}
			}
			if (StrUtil.isEmpty(unionId)) {
				userInfoResp.setIsJoinWx(false);
			} else {
				CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
						.field(CorpUserFollowView::getUnionId, unionId)
						.field(CorpUserFollowView::getStatus, 1).build());
				if (corpUserFollowView != null) {
					userInfoResp.setIsJoinWx(true);
				} else userInfoResp.setIsJoinWx(false);
			}
		}
		//是否下过单
		if (type == 0 || type == 2) {
			List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, user);
			Integer selectCount = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
					.in(OrderDon::getUserId, userIdList)
					.notIn(OrderDon::getStatus, Constant.noOrderStatus));
			userInfoResp.setIsPay(selectCount > 0);
		}
		return userInfoResp;
	}

	@Override
	public String generateTempCorpFollowCode(TempCorpFollowCodeReq tempCorpFollowCodeReq) throws Exception {
		CorpFollowContact corpFollowContact = new CorpFollowContact();
		tempCorpFollowCodeReq.setYl(Optional.ofNullable(tempCorpFollowCodeReq.getYl()).orElse(true));
		String state = Codec.DoBase64.custom().setData(Jsons.toJson(tempCorpFollowCodeReq)).encodeAsText();
		CorpWxYlRecord corpWxYlRecord = new CorpWxYlRecord();
		corpWxYlRecord.setState(state);
		corpWxYlRecordMapper.insert(corpWxYlRecord);
		//场景，1-在小程序中联系，2-通过二维码联系
		corpFollowContact.setScene(2);
		corpFollowContact.setState(Constant.CORP_WX_YL_PREFIX + corpWxYlRecord.getId());
		corpFollowContact.setTemp(false);
		//是否开启同一外部企业客户只能添加同一个员工，默认为否，开启后，同一个企业的客户会优先添加到同一个跟进人
		corpFollowContact.setExclusive(false);
		corpFollowContact.setSkip_verify(true);
		//系统配置
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.CORP_WX_YL_FOLLOW_IDS_KEY)
				.last("limit 1"));
		if (sysConfig == null || StrUtil.isEmpty(sysConfig.getSysValue())) {
			throw BusinessRuntimeException.getInstance("获取错误，请刷新重试");
		}
		List<String> followIds = Jsons.parseList(sysConfig.getSysValue(), String.class);
		String randFollowId = followIds.get(RandomUtil.randomInt(followIds.size()));
		corpFollowContact.setUser(List.of(randFollowId));
		//联系方式类型,1-单人, 2-多人
		corpFollowContact.setType(corpFollowContact.getUser().size() > 1 ? 2 : 1);
		String re = wxCorpOps.generateTempCorpFollowCode(corpFollowContact);
		JSONObject jsonObject = Jsons.parseObject(re, JSONObject.class);
		//记录下 删除
		String configId = jsonObject.getStr("config_id");
		CorpWxYlFollowConfig followConfig= new CorpWxYlFollowConfig();
		followConfig.setConfigId(configId);
		corpWxYlFollowConfigMapper.insert(followConfig);
		return jsonObject.getStr("qr_code");
	}
}
