package com.cyksj.service.mange.goods;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.ChatgptUserMapper;
import com.cyksj.mapper.GoodsDiscountPlusPurchaseRelationMapper;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.UpgradePackageMapper;
import com.cyksj.mapper.shop.YhShopGoodsRateMapper;
import com.cyksj.mapper.shop.YhShopGoodsSkuMapper;
import com.cyksj.mapper.shop.YhShopSkuSysTakeDownRecordMapper;
import com.cyksj.model.entity.*;
import com.cyksj.service.mange.CmsGoodsDonSkuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author chan
 * @date 2022/9/27 5:43 PM
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CmsGoodsDonSkuServiceImpl extends ServiceImpl<GoodsDonSkuMapper,GoodsDonSku> implements CmsGoodsDonSkuService {
	private final GoodsDiscountPlusPurchaseRelationMapper discountPlusPurchaseRelationMapper;

	private final GoodsDonSkuMapper skuMapper;

	private final ChatgptUserMapper chatgptUserMapper;

	private final YhShopGoodsRateMapper yhShopGoodsRateMapper;

	private final YhShopGoodsSkuMapper yhShopGoodsSkuMapper;

	private final YhShopSkuSysTakeDownRecordMapper yhShopSkuSysTakeDownRecordMapper;

	private final UpgradePackageMapper upgradePackageMapper;

	@Override
	public void handleDiscountPurchaseGoods(GoodsDonSku sku, List<GoodsDiscountPlusPurchaseRelation> discountPlusPurchaseGoods) {
		Long skuId = sku.getId();
		Long goodsId = sku.getGoodsId();
		List<GoodsDiscountPlusPurchaseRelation> dbDiscountPlusGoodsList = discountPlusPurchaseRelationMapper.selectList(Wrappers.lambdaQuery(GoodsDiscountPlusPurchaseRelation.class)
				.eq(GoodsDiscountPlusPurchaseRelation::getSkuId, skuId));
		if (CollUtil.isEmpty(dbDiscountPlusGoodsList) && CollUtil.isNotEmpty(discountPlusPurchaseGoods)) {
			discountPlusPurchaseGoods.forEach(discountGoods -> {
				checkPurchaseParamsAndSaveOrUpdate(goodsId, skuId, discountGoods);
			});
			sku.setIsDp(true);
			return;
		}
		//优惠加购为空
		if (CollUtil.isEmpty(discountPlusPurchaseGoods)) {
			discountPlusPurchaseRelationMapper.delete(Wrappers.lambdaQuery(GoodsDiscountPlusPurchaseRelation.class)
					.eq(GoodsDiscountPlusPurchaseRelation::getSkuId, skuId));
			sku.setIsDp(false);
			return;
		}

		//新增或更新
		sku.setIsDp(true);
		Map<Long, GoodsDiscountPlusPurchaseRelation> skuIdMap = new ConcurrentHashMap<>();
		discountPlusPurchaseGoods.forEach(discountGoods -> {
			AtomicBoolean is_exist = new AtomicBoolean(false);
			if (skuIdMap.get(discountGoods.getDisSid()) == null) {
				skuIdMap.put(discountGoods.getDisSid(), discountGoods);
			}
			dbDiscountPlusGoodsList.forEach(db_exist->{
				//存在
				if (db_exist.getDisSid().equals(discountGoods.getDisSid())) {
					is_exist.set(true);
					discountGoods.setId(db_exist.getId());
					checkPurchaseParamsAndSaveOrUpdate(goodsId, skuId, discountGoods);
				}
			});
			//不存在新增
			if (!is_exist.get()) {
				checkPurchaseParamsAndSaveOrUpdate(goodsId, skuId, discountGoods);
			}
		});

		//去除数据库已被删除的
		dbDiscountPlusGoodsList.forEach(dbDiscountPlusGoods -> {
			GoodsDiscountPlusPurchaseRelation exists = skuIdMap.get(dbDiscountPlusGoods.getDisSid());
			//不存在
			if (exists == null) {
				discountPlusPurchaseRelationMapper.deleteById(dbDiscountPlusGoods.getId());
			}
		});
	}

	@Override
	public void updateMirrorCarUserNum(GoodsDonSku sku) {
		if (sku.getIsCar() != null && sku.getIsCar()) {
			Long id = sku.getId();
			GoodsDonSku dbSku = skuMapper.selectById(id);
			Integer gptLimitNum = sku.getGptLimitNum();
			Long gptLimitTime = sku.getGptLimitTime();

			Integer dbGptLimitNum = dbSku.getGptLimitNum();
			Long dbGptLimitTime = dbSku.getGptLimitTime();

			if (gptLimitNum == null || gptLimitNum < 0) {
				throw BusinessRuntimeException.getInstance("请输入正确的限制次数");
			}

			if (gptLimitTime == null || gptLimitTime < 0) {
				throw BusinessRuntimeException.getInstance("请输入正确的限制时间");
			}

			if (!ObjectUtil.equal(gptLimitNum, dbGptLimitNum) || !ObjectUtil.equal(gptLimitTime, dbGptLimitTime)) {
				//更新该规格镜像车队的用户次数 时间
				chatgptUserMapper.updateChatGptCarUserNumAndLimitTime(sku.getId(), gptLimitNum, gptLimitTime);
			}
		}
	}

	@Override
	public void setBelowPriceShopSkuDown(Long skuId, BigDecimal newPrice) {
		YhShopGoodsRate yhShopGoodsRate = yhShopGoodsRateMapper.selectOne(Wrappers.lambdaQuery(YhShopGoodsRate.class)
				.eq(YhShopGoodsRate::getSkuId, skuId)
				.last("limit 1"));
		if (yhShopGoodsRate != null) {
			BigDecimal differPrice = newPrice.multiply(BigDecimal.valueOf(yhShopGoodsRate.getRate()).divide(BigDecimal.valueOf(100)));
			BigDecimal minPrice = newPrice.subtract(differPrice);
			BigDecimal maxPrice = newPrice.add(differPrice);
			//不在设置的价格区间店铺 统统下架
			//记录那些店铺规格被下架
			List<YhShopGoodsSku> yhShopGoodsSkus = yhShopGoodsSkuMapper.getBelowPriceShopSku(skuId, minPrice, maxPrice);
			if (CollUtil.isNotEmpty(yhShopGoodsSkus)) {
				yhShopSkuSysTakeDownRecordMapper.batchInsert(yhShopGoodsSkus, minPrice);
				Integer update = yhShopGoodsSkuMapper.setBelowPriceShopSkuDown(skuId, minPrice, maxPrice);
				log.info("变更skuId:{}规格价格,店铺数量:{}低于价格区间:{}-{}下架", skuId, update, minPrice, maxPrice);
			}
		}
	}

	@Override
	public void handleGptPackageSku(GoodsDonSku dbSku, GoodsDonSku sku) throws Exception {
		Long gptLimitTime = dbSku.getGptLimitTime();
		Integer gptLimitNum = dbSku.getGptLimitNum();
		BigDecimal price = dbSku.getPrice();
		BigDecimal newPrice = sku.getPrice();
		//GPT镜像套餐包关联
		if (sku.getGoodsId() == 18 && sku.getIsMirror()) {
			//同步升级规格的价格
			if (gptLimitNum != sku.getGptLimitNum() || gptLimitTime != sku.getGptLimitTime() || price.compareTo(newPrice) != 0) {
				if (price.compareTo(newPrice) != 0) {
					//本身是需升级的规格 同步套餐价格
					UpgradePackage upgradePackageSelfBind = upgradePackageMapper.selectOne(Wrappers.lambdaQuery(UpgradePackage.class).apply("JSON_CONTAINS(sku_ids,'\"" + sku.getId() + "\"')")
							.eq(UpgradePackage::getStatus, Boolean.TRUE)
							.eq(UpgradePackage::getGptType, 0)
							.eq(UpgradePackage::getDeleted, Boolean.TRUE)
							.last("limit 1"));
					if (upgradePackageSelfBind != null) {
						Long upgradeSkuId = upgradePackageSelfBind.getUpgradeSkuId();
						GoodsDonSku upgradeSku = skuMapper.selectById(upgradeSkuId);
						if (upgradeSku != null && upgradeSku.getPrice().compareTo(sku.getPrice()) > 0) {
							upgradePackageSelfBind.setPrice(upgradeSku.getPrice().subtract(sku.getPrice()));
							upgradePackageMapper.updateById(upgradePackageSelfBind);
						}
					}
				}

				//被绑定升级套餐
				List<UpgradePackage> toUpgradePackages = upgradePackageMapper.selectList(Wrappers.lambdaQuery(UpgradePackage.class)
						.eq(UpgradePackage::getUpgradeSkuId, sku.getId()));
				if (CollUtil.isNotEmpty(toUpgradePackages)) {
					toUpgradePackages.forEach(toUpgradePackage->{
						if (price.compareTo(sku.getPrice()) != 0) {
							Long skuId = null;
							try {
								skuId = Jsons.parseList(toUpgradePackage.getSkuIds(), Long.class).get(0);
								//需升级的规格
								GoodsDonSku oriSku = skuMapper.selectById(skuId);
								if (oriSku == null) {
									return;
								}
								BigDecimal differ = sku.getPrice().subtract(oriSku.getPrice());
								if (differ.compareTo(BigDecimal.ZERO) > 0) {
									toUpgradePackage.setPrice(differ);
								}
							} catch (Exception e) {
							}
						}
						toUpgradePackage.setTime(sku.getGptLimitTime());
						toUpgradePackage.setNum(sku.getGptLimitNum());
						upgradePackageMapper.updateById(toUpgradePackage);
					});
				}
			}
		}
	}

	public void checkPurchaseParamsAndSaveOrUpdate(Long goodsId, Long skuId, GoodsDiscountPlusPurchaseRelation discountGoods) {
		Long disSid = discountGoods.getDisSid();
		if (disSid == null) {
			throw BusinessRuntimeException.getInstance("请选择对应优惠加购规格");
		}
		if (skuId.equals(disSid)) {
			return;
		}
		BigDecimal disPrice = discountGoods.getDisPrice();
		GoodsDonSku sku = skuMapper.selectOne(Wrappers.lambdaQuery(GoodsDonSku.class)
				.eq(GoodsDonSku::getId, disSid).last("limit 1"));
		if (sku == null) {
			throw BusinessRuntimeException.getInstance("优惠加购规格不存在");
		}
		if (!sku.getStatus()) {
			throw BusinessRuntimeException.getInstance("{0}规格未上架", sku.getSpecVal());
		}
		if (disPrice == null || disPrice.compareTo(BigDecimal.ZERO) <= 0) {
			throw BusinessRuntimeException.getInstance("请输入正确的优惠加购价格");
		}
		discountGoods.setGoodsId(goodsId);
		discountGoods.setSkuId(skuId);
		discountGoods.setDisGid(sku.getGoodsId());
		if (discountGoods.getId() != null) {
			discountPlusPurchaseRelationMapper.updateById(discountGoods);
			return;
		}
		try {
			discountPlusPurchaseRelationMapper.insert(discountGoods);
		} catch (DuplicateKeyException e) {
		}
	}
}
