package com.cyksj.service.mirrorshop.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.SmsUtil;
import com.cyksj.common.util.StringUtil;
import com.cyksj.dto.Result;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopDistributeWaitingSendPointsMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.UserMirrorShop;
import com.cyksj.model.request.UserMirrorShopApplyMoneyReq;
import com.cyksj.model.views.YhShopBrokenLineCpsUserWMoneyView;
import com.cyksj.model.views.YhShopUserWMoneyStatisticsDataView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mail.MailService;
import com.cyksj.service.mirrorshop.CmsUserMirrorShopService;
import com.cyksj.service.pay.TransferFuncService;
import com.cyksj.service.user.BadIntentionOpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 项目名: yhlxj2
 * 文件名: CmsUserMirrorShopServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/11/7 12:07
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CmsUserMirrorShopServiceImpl implements CmsUserMirrorShopService {
	private final UserMapper userMapper;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final MailService mailService;

	private final RedisService redisService;

	private final UserMirrorShopDistributeWaitingSendPointsMapper userMirrorShopDistributeWaitingSendPointsMapper;

	private final TransferFuncService transferFuncService;

	private final HttpServletRequest request;

	private final BadIntentionOpService badIntentionOpService;

	@Override
	public void getLoginCode(Integer type, String login, Integer cid, String verifyCode, String ticket, String randStr) {
		if (type > 2) {
			throw BusinessRuntimeException.getInstance("");
		}
		if (cid == null) {
			cid = 86;
		}
		String phone = null;
		String email = null;
		if (type == 1) phone = login;
		else if (type == 2) email = login;
		User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
				.eq(StrUtil.isNotBlank(phone), User::getLoginPhone, phone)
				.eq(StrUtil.isNotBlank(email), User::getEmail, email).last("limit 1"));
		if (user == null) throw BusinessRuntimeException.getInstance("登录信息不存在");
		//是否是店铺主
		UserMirrorShop shop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, user.getId()).last("limit 1"));
		if (shop == null) {
			throw BusinessRuntimeException.getInstance("您不是小店店铺主");
		}

		String CACHE_LOGIN_KEY = RedisService.key.USER_MIRROR_SHOP_BACK_LOGIN_KEY.getName() + login;
		Object o = redisService.get(CACHE_LOGIN_KEY);
		Long expire = redisService.getExpire(CACHE_LOGIN_KEY);
		if (o != null && expire >= 3 * 60 - 10) {
			throw BusinessRuntimeException.getInstance("获取验证码过于频繁");
		}
		String code = StringUtil.getRandomCodeStr(6);
		if (type == 1) {
			if (StrUtil.isEmpty(login) || (86 == cid && !Validator.isMobile(phone))) {
				throw BusinessRuntimeException.getInstance("请输入正确的手机号");
			}
			//是否是恶意用户
			badIntentionOpService.checkHandleBadUserOp(phone, verifyCode, ticket, randStr, request);
			SmsUtil.sendTencent(cid, login, code);
		} else if (type == 2) {
			if (!Validator.isEmail(login)) {
				throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
			}
			mailService.sendLoginCodeEmailToPeople(code, login);
		}
		redisService.set(CACHE_LOGIN_KEY, code, RedisService.key.USER_MIRROR_SHOP_BACK_LOGIN_KEY.getTimeout());
	}

	@Override
	public String yhShopManageRedirect(long userId) {
		//是否是店铺主
		UserMirrorShop shop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, userId).last("limit 1"));
		if (shop == null) {
			throw BusinessRuntimeException.getInstance("您不是小店店铺主");
		}
		return null;
	}

	@Override
	public User login(Integer type, String login, String code) {
		String phone = null;
		String email = null;
		if (type == null) {
			type = 1;
		}
		if (type > 2) {
			throw BusinessRuntimeException.getInstance("");
		}
		if (type == 1) phone = login;
		if (type == 2) email = login;
		if (StrUtil.isEmpty(code)) {
			throw BusinessRuntimeException.getInstance("请输入验证码");
		}
		String CACHE_LOGIN_KEY = RedisService.key.USER_MIRROR_SHOP_BACK_LOGIN_KEY.getName() + login;
		if (type == 1) {
			if (StrUtil.isEmpty(phone)) {
				throw BusinessRuntimeException.getInstance("请输入正确的手机号");
			}
		} else if (type == 2) {
			if (!Validator.isEmail(email)) {
				throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
			}
		}
		String cache_code = String.valueOf(redisService.get(CACHE_LOGIN_KEY));
		if (StrUtil.isBlank(cache_code) || !cache_code.equals(code)) {
			throw BusinessRuntimeException.getInstance("验证码错误");
		}
		User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
				.eq(StrUtil.isNotBlank(phone), User::getLoginPhone, phone)
				.eq(StrUtil.isNotBlank(email), User::getEmail, email).last("limit 1"));
		if (user == null) throw BusinessRuntimeException.getInstance("用户不存在");
		//是否是店铺主
		UserMirrorShop shop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, user.getId()).last("limit 1"));
		if (shop == null) {
			throw BusinessRuntimeException.getInstance("您不是小店店铺主");
		}
		return user;
	}

	@Override
	public YhShopBrokenLineCpsUserWMoneyView getWMoneyStatisticsDate(long yhShopUserId, DateTime first, DateTime end) {
		boolean today = isToday(first, end);
		return userMirrorShopDistributeWaitingSendPointsMapper.getWMoneyStatisticsDataView(yhShopUserId, first, end, today);
	}

	@Override
	public List<YhShopUserWMoneyStatisticsDataView> getWMoneyStatisticsDataView(long yhShopUserId, DateTime first, DateTime end) {
		boolean today = isToday(first, end);
		return userMirrorShopDistributeWaitingSendPointsMapper.getWMoneyStatisticsDate(yhShopUserId, first, end, today);
	}

	@Override
	public Result<String> applyMoney(UserMirrorShopApplyMoneyReq applyMoneyReq) {
		return transferFuncService.userMirrorShopDistributeApply(applyMoneyReq);
	}


	public boolean isToday(DateTime first, DateTime end) {
		boolean today = false;
		if (first != null && end != null) {
			if (DateUtil.beginOfDay(DateTime.now()).equals(first) && (DateUtil.beginOfDay(DateUtil.offsetDay(DateTime.now(), 1)).equals(end) || DateUtil.endOfDay(DateTime.now()).equals(end))) {
				today = true;
			}
		}
		return today;
	}
}
