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.mapper.GoodsDonMapper;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.model.entity.GoodsDon;
import com.cyksj.model.entity.GoodsDonSku;
import com.cyksj.service.mange.CmsGoodsDonService;
import com.ejlchina.searcher.BeanSearcher;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author chan
 * @date 2022/9/27 5:31 PM
 */
@Service
@RequiredArgsConstructor
public class CmsGoodsDonServiceImpl extends ServiceImpl<GoodsDonMapper, GoodsDon> implements CmsGoodsDonService {
	private final BeanSearcher beanSearcher;

	private final GoodsDonMapper goodsDonMapper;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	@Override
	public void updateGoodsSkuPrice(Long goodsId, GoodsDon goods) {
		goods = Optional.ofNullable(goods).orElse(goodsDonMapper.selectById(goodsId));
		List<GoodsDonSku> skuViews = goodsDonSkuMapper.selectList(Wrappers.lambdaQuery(GoodsDonSku.class)
				.eq(GoodsDonSku::getGoodsId, goodsId)
				.eq(GoodsDonSku::getStatus, true)
				.orderByAsc(GoodsDonSku::getPrice));
		//是否有特殊属性
		if (CollUtil.isEmpty(skuViews)) {
			if (goods.getIsSp()) {
				goods.setIsSp(false);
			}
			if (goods.getIsOwns()) {
				goods.setIsOwns(false);
			}
			goodsDonMapper.updateById(goods);
		}
		if (!skuViews.isEmpty()) {
			//是否有特定价格规格
			int spSkuCount = goodsDonSkuMapper.selectCount(Wrappers.lambdaQuery(GoodsDonSku.class)
					.eq(GoodsDonSku::getGoodsId, goodsId)
					.gt(GoodsDonSku::getSpecificPrice, 0)
					.eq(GoodsDonSku::getStatus, true));
			int userOwnsSkuCount = goodsDonSkuMapper.selectCount(Wrappers.lambdaQuery(GoodsDonSku.class)
					.eq(GoodsDonSku::getGoodsId, goodsId)
					.isNotNull(GoodsDonSku::getUserOwns)
					.eq(GoodsDonSku::getStatus, true));
			goods.setIsSp(spSkuCount > 0 ? true : false);
			goods.setIsOwns(userOwnsSkuCount > 0 ? true : false);

			GoodsDonSku min = skuViews.get(0);
			goods.setMinPrice(min.getPrice());
			if (min.getDays() == null) {
				min.setDays(0);
			}
			if (min.getMonths() == null) {
				min.setMonths(0);
			}
			goods.setMinMonths(min.getMonths());
			goods.setMinDays(min.getDays());
			if (skuViews.size() == 1) {
				goods.setMaxPrice(min.getPrice());
				goods.setMaxMonths(min.getMonths());
				goods.setMaxDays(min.getDays());
			} else {
				GoodsDonSku max = skuViews.get(skuViews.size() - 1);
				if (max.getDays() == null) {
					max.setDays(0);
				}
				if (max.getMonths() == null) {
					max.setMonths(0);
				}
				goods.setMaxPrice(max.getPrice());
				goods.setMaxMonths(max.getMonths());
				goods.setMaxDays(max.getDays());
			}
			goodsDonMapper.updateById(goods);
		}
	}
}
