package com.cyksj.service.mange.goods;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.GoodsDonCategoryMapper;
import com.cyksj.mapper.GoodsDonCategoryRelateMapper;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.model.entity.GoodsDon;
import com.cyksj.model.entity.GoodsDonCategory;
import com.cyksj.model.entity.GoodsDonCategoryRelate;
import com.cyksj.service.mange.GoodsDonCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: GoodsDonCategoryServiceImpl
 *创建者: JavaZou
 *创建时间:2023/8/11 13:45
 */
@Service
@RequiredArgsConstructor
public class GoodsDonCategoryServiceImpl extends ServiceImpl<GoodsDonCategoryMapper, GoodsDonCategory> implements GoodsDonCategoryService {
	private final GoodsDonMapper goodsDonMapper;

	private final GoodsDonCategoryRelateMapper goodsDonCategoryRelateMapper;

	@Override
	public void saveOrUpdateGoods(GoodsDonCategory category) {
		try {
			this.saveOrUpdate(category);
		} catch (DuplicateKeyException e) {
			throw BusinessRuntimeException.getInstance("分类名称重复");
		}
	}

	@Override
	public void delById(Long id) {
		Integer count = goodsDonMapper.selectCount(Wrappers.lambdaQuery(GoodsDon.class)
				.eq(GoodsDon::getCategory, id)
				.eq(GoodsDon::getDeleted, true));
		if (count > 0) {
			throw BusinessRuntimeException.getInstance("存在该分类下的商品");
		}
		this.removeById(id);
	}

	@Override
	public List<GoodsDonCategory> getCateGoryViewByGoodsId(Long goodsId) {
		List<GoodsDonCategory> categoryList = goodsDonCategoryRelateMapper.getCateGoryViewByGoodsId(goodsId);
		return categoryList;
	}

	@Override
	public void saveBatchRelate(Long goodsId, List<Long> categoryList) {
		//查询已有的分类
		categoryList = this.list(Wrappers.lambdaQuery(GoodsDonCategory.class)
				.in(GoodsDonCategory::getId, categoryList)).stream().map(GoodsDonCategory::getId).collect(Collectors.toList());
		Long category;
		if (CollUtil.isNotEmpty(categoryList)) {
			if (categoryList.size() > 1) {
				goodsDonCategoryRelateMapper.saveBatchGoodsRelate(goodsId, categoryList);
				List<Long> sorted = categoryList.stream().sorted(Comparator.comparing((i) -> i)).collect(Collectors.toList());
				category = sorted.get(0);
			} else {
				GoodsDonCategoryRelate goodsDonCategoryRelate = new GoodsDonCategoryRelate();
				goodsDonCategoryRelate.setGoodsId(goodsId);
				category = categoryList.get(0);
				goodsDonCategoryRelate.setCategory(category);
				goodsDonCategoryRelateMapper.insert(goodsDonCategoryRelate);
			}
			goodsDonMapper.update(null, Wrappers.lambdaUpdate(GoodsDon.class)
					.set(GoodsDon::getCategory, category)
					.eq(GoodsDon::getId, goodsId));
		}
	}

	@Override
	public void handleGoodsRelate(Long goodsId, List<Long> categoryList) {
		//更新第三方平台信息
		updateThirdGoodsInfo(goodsId, categoryList);

		if (CollUtil.isEmpty(categoryList)) {
			goodsDonCategoryRelateMapper.delete(Wrappers.lambdaQuery(GoodsDonCategoryRelate.class).eq(GoodsDonCategoryRelate::getGoodsId, goodsId));
			goodsDonMapper.update(null, Wrappers.lambdaUpdate(GoodsDon.class)
					.set(GoodsDon::getCategory, 0)
					.eq(GoodsDon::getId, goodsId));
			return;
		}
		List<GoodsDonCategoryRelate> goodsDonCategoryRelates = goodsDonCategoryRelateMapper.selectList(Wrappers.lambdaQuery(GoodsDonCategoryRelate.class).eq(GoodsDonCategoryRelate::getGoodsId, goodsId));
		if (goodsDonCategoryRelates.isEmpty()) {
			saveBatchRelate(goodsId, categoryList);
			return;
		}
		AtomicBoolean ic = new AtomicBoolean(true);

		//需要删除
		goodsDonCategoryRelates.forEach(data -> {
			if (!categoryList.contains(data.getCategory())) {
				goodsDonCategoryRelateMapper.deleteById(data.getId());
				categoryList.remove(data.getCategory());
				ic.set(false);
			}
		});
		if (ic.get() && categoryList.size() == goodsDonCategoryRelates.size()) {
			return;
		}
		saveBatchRelate(goodsId, categoryList);
	}

	private void updateThirdGoodsInfo(Long goodsId, List<Long> categoryList) {
		AtomicBoolean isThirdGoods = new AtomicBoolean(false);
		if (CollUtil.isNotEmpty(categoryList)) {
			//第三方商品信息更新
			categoryList.forEach(ct->{
				if (Constant.THIRD_CATEGORY == ct) {
					isThirdGoods.set(true);
				}
			});
		}
		goodsDonMapper.update(null, Wrappers.lambdaUpdate(GoodsDon.class)
				.set(GoodsDon::getIsThirdGoods, isThirdGoods.get())
				.eq(GoodsDon::getId, goodsId));
	}
}
