package com.xxfc.platform.activity.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.activity.entity.ActivityProductSpecs;
import com.xxfc.platform.activity.mapper.ActivityProductSpecsMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@Api("活动商品规格")
public class ActivityProductSpecsBiz extends BaseBiz<ActivityProductSpecsMapper, ActivityProductSpecs> {

	public ObjectRestResponse add(ActivityProductSpecs activityProductSpecs) {
		if (activityProductSpecs == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		if (activityProductSpecs.getId() == null) {
			insertSelectiveRe(activityProductSpecs);
		} else {
			ActivityProductSpecs oldValue = getOne(activityProductSpecs.getId());
			BeanUtil.copyProperties(activityProductSpecs, oldValue, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
			updateSelectiveByIdRe(oldValue);
			return ObjectRestResponse.succ(oldValue);
		}
		return ObjectRestResponse.succ(activityProductSpecs);
	}

	public ActivityProductSpecs getOne(Long id) {
		Example example = new Example(ActivityProductSpecs.class);
		example.createCriteria().andEqualTo("id", id).andEqualTo("isDel", false);
		return mapper.selectOneByExample(example);
	}

	public List<ActivityProductSpecs> getAllByActiveId(Long activeId) {
		if (activeId == null) {
			return new ArrayList<>();
		}
		Example example = new Example(ActivityProductSpecs.class);
		example.createCriteria().andEqualTo("goodsId", activeId).andEqualTo("isDel", false);
		return mapper.selectByExample(example);
	}


	public ObjectRestResponse update(ActivityProductSpecs activityProductSpecs) {
		if (activityProductSpecs == null || activityProductSpecs.getId() == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		ActivityProductSpecs oldValue = selectById(activityProductSpecs.getId());
		if (oldValue != null) { //增加销量，减少库存
			if (oldValue.getStock() > 0 || activityProductSpecs.getSales() < 0) {
				oldValue.setSales(oldValue.getSales() + activityProductSpecs.getSales());
				oldValue.setStock(oldValue.getStock() - activityProductSpecs.getSales());
				updateSelectiveByIdRe(oldValue);
				return ObjectRestResponse.succ(oldValue);
			} else {
				return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "库存不足");
			}

		} else {
			return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "商品不存在！");
		}
	}

}
