package com.cyksj.service.cps.shop;

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.manage.distribute.UserDistributeMapper;
import com.cyksj.mapper.shop.YhShopApplyRecordMapper;
import com.cyksj.mapper.shop.YhShopDistributeWaitingSendPointsMapper;
import com.cyksj.mapper.shop.YhShopMapper;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.UserDistribute;
import com.cyksj.model.entity.YhShop;
import com.cyksj.model.entity.YhShopApplyRecord;
import com.cyksj.model.request.YhShopApplyMoneyReq;
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.pay.TransferFuncService;
import com.cyksj.service.user.BadIntentionOpService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/*
 *项目名: yhlxj
 *文件名: YhShopManageServiceImpl
 *创建者: JavaZou
 *创建时间:2023/9/19 17:36
 */
@Service
@RequiredArgsConstructor
public class YhShopManageServiceImpl implements YhShopManageService{
	private final YhShopMapper yhShopMapper;

	private final UserMapper userMapper;

	private final RedisService redisService;

	private final MailService mailService;

	private final TransferFuncService transferFuncService;

	private final YhShopDistributeWaitingSendPointsMapper yhShopDistributeWaitingSendPointsMapper;

	private final YhShopApplyRecordMapper yhShopApplyRecordMapper;

	private final UserDistributeMapper userDistributeMapper;

	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("登录信息不存在");
		//是否是店铺主
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getVerifyStatus, YhShop.Status.success)
				.eq(YhShop::getUserId, user.getId()).last("limit 1"));
		if (yhShop == null) {
			throw BusinessRuntimeException.getInstance("您不是银河小店店铺主");
		}

		String CACHE_LOGIN_KEY = RedisService.key.YH_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.YH_SHOP_BACK_LOGIN_KEY.getTimeout());
	}

	@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.YH_SHOP_BACK_LOGIN_KEY.getName();
		if (type == 1) {
			if (StrUtil.isEmpty(phone)) {
				throw BusinessRuntimeException.getInstance("请输入正确的手机号");
			}
			CACHE_LOGIN_KEY += phone;
		} else if (type == 2) {
			if (!Validator.isEmail(email)) {
				throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
			}
			CACHE_LOGIN_KEY += email;
		}
		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("用户不存在");
		//是否是店铺主
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getVerifyStatus, YhShop.Status.success)
				.eq(YhShop::getUserId, user.getId()).last("limit 1"));
		if (yhShop == null) {
			throw BusinessRuntimeException.getInstance("您不是银河小店店铺主");
		}
		redisService.del(CACHE_LOGIN_KEY);
		return user;
	}

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

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

	@Override
	public User yhShopManageRedirect(long userId) {
		//是否是店铺主
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getVerifyStatus, YhShop.Status.success)
				.eq(YhShop::getUserId, userId).last("limit 1"));
		if (yhShop == null) {
			throw BusinessRuntimeException.getInstance("您不是银河小店店铺主");
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public Result applyMoney(YhShopApplyMoneyReq applyMoneyReq) throws Exception {
		return transferFuncService.yhShopDistributeApply(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;
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void addUserShop(YhShop yhShop) {
		Long userId = yhShop.getUserId();
		Integer count = yhShopMapper.selectCount(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId));
		if (count > 0) {
			return;
		}
		yhShop.setVerifyStatus(YhShop.Status.success);
		Optional.ofNullable(userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, userId)
				.eq(UserDistribute::getDeleted, 1)
				.last("limit 1"))).ifPresent(e->{
			yhShop.setBusinessId(e.getBusinessId());
		});
		if (yhShop.getBusinessId() != null) {
			yhShop.setBusinessBindTime(DateTime.now());
		}

		yhShopMapper.insert(yhShop);

		YhShopApplyRecord yhShopApplyRecord = new YhShopApplyRecord();
		yhShopApplyRecord.setName(yhShop.getName());
		yhShopApplyRecord.setUserId(userId);
		yhShopApplyRecord.setCustomId(yhShop.getCustomId());
		yhShopApplyRecord.setVerifyStatus(YhShopApplyRecord.Status.success);
		yhShopApplyRecord.setBusinessId(yhShop.getBusinessId());
		yhShopApplyRecordMapper.insert(yhShopApplyRecord);
	}
}
