package com.cyksj.service.shop.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.ValidatorUtil;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
import com.cyksj.mapper.shop.YhShopApplyRecordMapper;
import com.cyksj.mapper.shop.YhShopMapper;
import com.cyksj.model.dto.YhShopInfo;
import com.cyksj.model.entity.SysConfig;
import com.cyksj.model.entity.UserDistribute;
import com.cyksj.model.entity.YhShop;
import com.cyksj.model.entity.YhShopApplyRecord;
import com.cyksj.service.shop.YhShopFrontService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/*
 *项目名: yhlxj
 *文件名: YhShopServiceImpl
 *创建者: JavaZou
 *创建时间:2023/9/14 17:00
 */
@Service
@RequiredArgsConstructor
public class YhShopServiceImpl implements YhShopFrontService {
	private final YhShopMapper yhShopMapper;

	private final YhShopApplyRecordMapper yhShopApplyRecordMapper;

	private final SysConfigMapper sysConfigMapper;

	private final UserDistributeMapper userDistributeMapper;

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void applyOpenShop(YhShop shopInfo) {
		String customId = shopInfo.getCustomId();
		String name = shopInfo.getName();
		Long userId = shopInfo.getUserId();
		//参数校验
		checkShopInfo(name, customId);
		YhShop is_open = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId));
		if (is_open != null) {
			throw BusinessRuntimeException.getInstance("只能申请开店一次");
		}
		YhShop is_customId = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getCustomId, customId).last("limit 1"));
		if (is_customId != null) {
			throw BusinessRuntimeException.getInstance("该店铺id已存在");
		}
		//校验推广订单 次数是否合格
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, Constant.USER_OPEN_SHOP_DS_ORDERS_LIMIT_KEY).last("limit 1"));
		if (sysConfig == null) {
			throw BusinessRuntimeException.getInstance("申请开店功能已关闭");
		}
		String sysValue = sysConfig.getSysValue();
		if (StrUtil.isEmpty(sysValue)) {
			throw BusinessRuntimeException.getInstance("申请开店功能已关闭");
		}
		int ds_order_limit = Integer.parseInt(sysValue);
		if (ds_order_limit <= 0) {
			throw BusinessRuntimeException.getInstance("申请开店功能已关闭");
		}
		//开店用户 当前分销单数
		int user_ds_order = userDistributeMapper.count(userId);
		if (user_ds_order < ds_order_limit) {
			throw BusinessRuntimeException.getInstance("您推广单数不符合开店资格");
		}
		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, userId)
				.eq(UserDistribute::getDeleted, true)
				.last("limit 1"));
		Long businessId = 0l;
		if (userDistribute != null) {
			businessId = userDistribute.getBusinessId();
		}
		try {
			YhShop save = new YhShop();
			save.setName(name);
			save.setUserId(userId);
			save.setCustomId(customId);
			save.setVerifyStatus(YhShop.Status.verify);
			save.setBusinessId(businessId);
			yhShopMapper.insert(save);

			YhShopApplyRecord yhShopApplyRecord = new YhShopApplyRecord();
			yhShopApplyRecord.setName(name);
			yhShopApplyRecord.setUserId(userId);
			yhShopApplyRecord.setCustomId(customId);
			yhShopApplyRecord.setVerifyStatus(YhShopApplyRecord.Status.verify);
			yhShopApplyRecord.setBusinessId(businessId);
			yhShopApplyRecordMapper.insert(yhShopApplyRecord);
		} catch (Exception e) {
			throw BusinessRuntimeException.getInstance("系统繁忙，请重试..");
		}
	}

	@Override
	public void reApplyOpenShop(YhShop shopInfo) {
		String customId = shopInfo.getCustomId();
		String name = shopInfo.getName();
		Long userId = shopInfo.getUserId();
		checkShopInfo(name, customId);

		YhShop is_open = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userId));
		if (is_open == null) {
			throw BusinessRuntimeException.getInstance("您暂无申请开店记录..");
		}
		String db_cId = is_open.getCustomId();
		YhShop.Status verifyStatus = is_open.getVerifyStatus();
		if (verifyStatus == YhShop.Status.verify) {
			throw BusinessRuntimeException.getInstance("您的开店申请正在审核中.");
		}
		if (verifyStatus == YhShop.Status.success) {
			throw BusinessRuntimeException.getInstance("您的开店申请已通过.");
		}

		if (!db_cId.equals(customId)) {
			YhShop is_customId = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
					.eq(YhShop::getCustomId, customId).last("limit 1"));
			if (is_customId != null) {
				throw BusinessRuntimeException.getInstance("该店铺id已存在");
			}
		}

		try {
			//重置更新申请信息
			int update = yhShopMapper.update(null, Wrappers.lambdaUpdate(YhShop.class)
					.eq(YhShop::getId, is_open.getId())
					.eq(YhShop::getVerifyStatus, YhShop.Status.fail)
					.set(YhShop::getName, name)
					.set(YhShop::getCustomId, customId)
					.set(YhShop::getVerifyStatus, YhShop.Status.verify)
					.set(YhShop::getReason, null));
			if (update != 1) {
				throw BusinessRuntimeException.getInstance("系统繁忙，请重试..");
			}
			YhShopApplyRecord yhShopApplyRecord = new YhShopApplyRecord();
			yhShopApplyRecord.setUserId(userId);
			yhShopApplyRecord.setName(name);
			yhShopApplyRecord.setCustomId(customId);
			yhShopApplyRecord.setVerifyStatus(YhShopApplyRecord.Status.verify);
			yhShopApplyRecordMapper.insert(yhShopApplyRecord);
		} catch (Exception e) {
			throw BusinessRuntimeException.getInstance("系统繁忙，请重试..");
		}
	}

	@Override
	public Long checkShopCustomIdAndReturnShopId(String customId) {
		Long yhsId = 0l;
		if (StrUtil.isEmpty(customId)) {
			return yhsId;
		}
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getCustomId, customId).last("limit 1"));
		if (yhShop == null) {
			throw BusinessRuntimeException.getInstance("该店铺不存在");
		}
		if (yhShop.getVerifyStatus() != YhShop.Status.success) {
			throw BusinessRuntimeException.getInstance("该店铺异常,请联系客服");
		}
		if (!yhShop.getStatus()) {
			throw BusinessRuntimeException.getInstance("该店铺已关闭,请联系客服");
		}
		yhsId = yhShop.getId();
		return yhsId;
	}

	@Override
	public YhShopInfo getYhShopInfo(String customId) {
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getCustomId, customId).last("limit 1"));
		if (yhShop == null) {
			return null;
		}
		YhShopInfo yhShopInfo = new YhShopInfo();
		BeanUtil.copyProperties(yhShop, yhShopInfo);
		return yhShopInfo;
	}

	@Override
	public Long getYhsIdByCustomId(String customId) {
		Long yhsId = 0l;
		if (StrUtil.isEmpty(customId)) {
			return yhsId;
		}
		customId = customId.trim();
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getCustomId, customId).last("limit 1"));
		if (yhShop == null) {
			return yhsId;
		}
		yhsId = yhShop.getId();
		return yhsId;
	}

	public void checkShopInfo(String name, String customId) {
		if (StrUtil.isEmpty(name)) {
			throw BusinessRuntimeException.getInstance("请输入店铺名称");
		}
		if (name.length() > 60) {
			throw BusinessRuntimeException.getInstance("店铺名称过长");
		}
		if (StrUtil.isEmpty(customId)) {
			throw BusinessRuntimeException.getInstance("请自定义店铺id");
		}
		if (customId.length() < 3 || customId.length() > 10) {
			throw BusinessRuntimeException.getInstance("请输入正确的店铺id");
		}
		if (!ValidatorUtil.isEnNum(customId)) {
			throw BusinessRuntimeException.getInstance("请输入数字字母的组合");
		}
	}
}
