package com.cyksj.service.mange.goods;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.manage.distribute.UserBusinessDefaultRateConfigMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
import com.cyksj.mapper.shop.*;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.DistributeApplyMoneyReq;
import com.cyksj.model.request.YhShopVerifyReq;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mange.CmsYhShopCommonService;
import com.cyksj.service.mange.business.UserBusinessRateService;
import com.cyksj.service.shop.YhShopUserPlatDistributeRateService;
import com.cyksj.service.user.UserBenefitsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/*
 *项目名: yhlxj
 *文件名: CmsYhShopCommonServiceImpl
 *创建者: JavaZou
 *创建时间:2023/9/15 17:27
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CmsYhShopCommonServiceImpl implements CmsYhShopCommonService {
	private final GoodsDonMapper goodsDonMapper;

	private final YhShopMapper yhShopMapper;

	private final YhShopApplyRecordMapper yhShopApplyRecordMapper;

	private final UserBusinessRateService userBusinessRateService;

	private final YhShopUserPlatDistributeRateService yhShopUserPlatDistributeRateService;

	private final YhShopDistributeMoneyApplyMapper yhShopDistributeMoneyApplyMapper;

	private final UserBenefitsService userBenefitsService;

	private final UserBusinessDefaultRateConfigMapper defaultRateConfigMapper;

	private final UserDistributeMapper userDistributeMapper;

	private final YhShopUserPlatDistributeRateMapper yhShopUserPlatDistributeRateMapper;

	private final RedisService redisService;

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void verifyYhShopApply(YhShopVerifyReq verifyReq) {
		Long id = verifyReq.getId();
		YhShopApplyRecord.Status verifyStatus = verifyReq.getVerifyStatus();
		String reason = verifyReq.getReason();
		YhShopApplyRecord yhShopApplyRecord = yhShopApplyRecordMapper.selectById(id);
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, yhShopApplyRecord.getUserId()).last("limit 1"));
		Assert.notNull(yhShopApplyRecord, "开店申请记录不存在");
		Assert.notNull(yhShop, "开店申请记录不存在");
		if (yhShopApplyRecord.getVerifyStatus() != YhShopApplyRecord.Status.verify && yhShopApplyRecord.getVerifyStatus() != YhShopApplyRecord.Status.modify) {
			throw BusinessRuntimeException.getInstance("该开店申请已审核");
		}
		if (verifyStatus != YhShopApplyRecord.Status.success && verifyStatus != YhShopApplyRecord.Status.fail) {
			throw BusinessRuntimeException.getInstance("请选择正确的审核状态");
		}
		if (verifyStatus == YhShopApplyRecord.Status.fail) {
			if (StrUtil.isEmpty(reason)) {
				throw BusinessRuntimeException.getInstance("请输入审核失败原因");
			}
			yhShopApplyRecord.setReason(reason);
			yhShop.setReason(reason);
			if (yhShop.getVerifyStatus() == YhShop.Status.verify) {
				yhShop.setVerifyStatus(YhShop.Status.fail);
			}
		} else {
			//申请修改
			if (yhShopApplyRecord.getVerifyStatus() == YhShopApplyRecord.Status.modify) {
				yhShop.setName(yhShopApplyRecord.getName());
			}
			if (yhShop.getVerifyStatus() == YhShop.Status.success) {
				yhShop.setName(yhShopApplyRecord.getName());
			}
			yhShop.setReason(null);
			if (yhShop.getVerifyStatus() == YhShop.Status.verify) {
				yhShop.setVerifyStatus(YhShop.Status.success);
				//审核成功 同步分销管理 设置的平台提成比例
				UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
						.eq(UserDistribute::getUserId, yhShop.getUserId())
						.eq(UserDistribute::getDeleted, true).last("limit 1"));
				if (userDistribute != null) {
					yhShop.setBusinessId(userDistribute.getBusinessId());
					yhShopUserPlatDistributeRateMapper.batchInsertGoodsRate(yhShop.getUserId());
				}
			}
		}
		yhShopApplyRecord.setVerifyTime(DateTime.now());
		yhShopApplyRecord.setVerifyStatus(verifyStatus);
		yhShopApplyRecordMapper.updateById(yhShopApplyRecord);
		yhShopMapper.updateById(yhShop);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void setYhShopGoodsRate(List<YhShopUserPlatDistributeRate> yhShopUserPlatDistributeRates, Long businessId, Long userId) {
		yhShopUserPlatDistributeRates.forEach(data -> {
			data.setUserId(userId);
			Long goodsId = data.getGoodsId();
			GoodsDon goodsDon = goodsDonMapper.selectById(goodsId);
			Assert.notNull(goodsDon, "请检查你设置的平台是否存在");
			Integer rate = data.getRate();
			if (rate == null || rate < 0 || rate > 100) {
				throw BusinessRuntimeException.getInstance("请输入正确的店铺分销平台比例");
			}
			Integer secondRate = data.getSecondRate();
			if (secondRate != null && (secondRate < 0 || secondRate > 100)) {
				throw BusinessRuntimeException.getInstance("请输入正确的分销比例");
			}
			//店铺分销虚物分销比例且配置商务
			if (businessId != null && goodsDon.getType() == 1) {
				checkDistributorAndBusinessRate(data.getRate(), goodsDon.getId(), goodsDon.getTitle());
			}
		});
		yhShopUserPlatDistributeRateService.saveOrUpdateBatch(yhShopUserPlatDistributeRates);
	}

	@Override
	public void setYhShopBusiness(YhShop yhShop) {
		Long businessId = yhShop.getBusinessId();
		Long id = yhShop.getId();
		YhShop dbShop = yhShopMapper.selectById(id);
		Assert.notNull(dbShop, "请检查店铺是否存在");
		if (dbShop.getVerifyStatus() != YhShop.Status.success) {
			throw BusinessRuntimeException.getInstance("请检查该店铺是否审核成功");
		}
		yhShop.setUserId(dbShop.getUserId());
		if (businessId == null && dbShop.getBusinessId() == 0) {
			return;
		}
		if (businessId == null && dbShop.getBusinessId() != 0) {
			yhShopMapper.update(null, Wrappers.lambdaUpdate(YhShop.class)
					.set(YhShop::getBusinessId, 0)
					.set(YhShop::getBusinessBindTime, null)
					.eq(YhShop::getId, id));
		}
		if (!dbShop.getBusinessId().equals(businessId)) {
			if (!userBusinessRateService.isBusiness(businessId)) {
				throw BusinessRuntimeException.getInstance("请选择正确的商务人员");
			}
			dbShop.setBusinessId(businessId);
			dbShop.setBusinessBindTime(DateTime.now());
		}
		dbShop.setRemark(yhShop.getRemark());
		yhShopMapper.updateById(dbShop);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void verifyYhShopApplyMoney(DistributeApplyMoneyReq distributeApplyMoneyReq) {
		YhShopDistributeMoneyApply.Status status = YhShopDistributeMoneyApply.Status.checkStatus(distributeApplyMoneyReq.getVerifyStatus());
		if (status == null || status == YhShopDistributeMoneyApply.Status.verifying) {
			throw BusinessRuntimeException.getInstance("审核状态错误");
		}
		YhShopDistributeMoneyApply distributeMoneyApply = yhShopDistributeMoneyApplyMapper.selectById(distributeApplyMoneyReq.getId());
		if (distributeMoneyApply == null) {
			throw BusinessRuntimeException.getInstance("提现记录不存在");
		}
		if (distributeMoneyApply.getVerifyStatus() != YhShopDistributeMoneyApply.Status.verifying) {
			throw BusinessRuntimeException.getInstance("该提现记录已处理,无法再进行审核");
		}
		distributeMoneyApply.setVerifyStatus(status);
		if (YhShopDistributeMoneyApply.Status.fail.name().equals(distributeApplyMoneyReq.getVerifyStatus()) && StrUtil.isEmpty(distributeApplyMoneyReq.getReason())) {
			throw BusinessRuntimeException.getInstance("拒绝原因为空");
		}
		if (YhShopDistributeMoneyApply.Status.fail.name().equals(distributeApplyMoneyReq.getVerifyStatus())) {
			distributeMoneyApply.setReason(distributeApplyMoneyReq.getReason());
			Long userId = distributeMoneyApply.getUserId();
			userBenefitsService.addYhsMoney(userId, distributeMoneyApply.getMoney());
			log.info("店铺提现审核失败,归还店铺申请提现金额:{}至用户{}结束", distributeMoneyApply.getMoney().divide(BigDecimal.valueOf(100)), userId);
		}
		if (YhShopDistributeMoneyApply.Status.success.name().equals(distributeApplyMoneyReq.getVerifyStatus())) {
//			if (StrUtil.isBlank(distributeApplyMoneyReq.getImg())) {
//				throw BusinessRuntimeException.getInstance("审核成功时,打款图片不存在");
//			}
			distributeMoneyApply.setImg(distributeApplyMoneyReq.getImg());
		}
		yhShopDistributeMoneyApplyMapper.updateById(distributeMoneyApply);

		if (distributeMoneyApply.getVerifyStatus() == YhShopDistributeMoneyApply.Status.fail) {
			String type = "shop";
			String key = String.format(RedisService.key.APPLY_MONEY_DAY_LIMIT_KEY.getName(), distributeMoneyApply.getUserId().toString(), type, distributeMoneyApply.getUserId());
			redisService.del(key);
		}
	}

	@Override
	public void updateVerifyImg(DistributeApplyMoneyReq distributeApplyMoneyReq) {
		Long id = distributeApplyMoneyReq.getId();
		String img = distributeApplyMoneyReq.getImg();
		if (id == null) {
			throw BusinessRuntimeException.getInstance("请选择对应的申请提现记录");
		}
		YhShopDistributeMoneyApply yhShopDistributeMoneyApply = yhShopDistributeMoneyApplyMapper.selectById(id);
		if (yhShopDistributeMoneyApply == null) {
			throw BusinessRuntimeException.getInstance("请选择对应的申请提现记录");
		}
		if (StrUtil.isEmpty(img)) {
			throw BusinessRuntimeException.getInstance("请传入对应的审核图片");
		}
		if (yhShopDistributeMoneyApply.getVerifyStatus() != YhShopDistributeMoneyApply.Status.success) {
			throw BusinessRuntimeException.getInstance("该申请提现记录未审核成功");
		}
		yhShopDistributeMoneyApply.setImg(img);
		yhShopDistributeMoneyApplyMapper.updateById(yhShopDistributeMoneyApply);
	}

	public void checkDistributorAndBusinessRate(Integer distributeGoodsRate, Long goodsId, String goodsName) {
		UserBusinessDefaultRateConfig defaultGoodsRateConfig = defaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(UserBusinessDefaultRateConfig.class)
				.eq(UserBusinessDefaultRateConfig::getGoodsId, goodsId)
				.last("limit 1"));
		Optional.ofNullable(defaultGoodsRateConfig).ifPresent(config -> {
			if (distributeGoodsRate > config.getMaxRate()) {
				throw BusinessRuntimeException.getInstance(String.format("该%s平台最高可配置分销比例为%s", goodsName, config.getMaxRate()));
			}
		});
	}
}
