package com.cyksj.service.mange.goods;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.GoodsDonQaMapper;
import com.cyksj.mapper.GoodsDonQaRelateMapper;
import com.cyksj.model.entity.GoodsDonQa;
import com.cyksj.model.entity.GoodsDonQaRelate;
import com.cyksj.service.mange.GoodsDonQaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 项目名: yhlxj2
 * 文件名: GoodsDonQaServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/5/24 15:57
 */
@Service
@RequiredArgsConstructor
public class GoodsDonQaServiceImpl extends ServiceImpl<GoodsDonQaMapper, GoodsDonQa> implements GoodsDonQaService {
	private final GoodsDonQaRelateMapper goodsDonQaRelateMapper;

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void saveOrdUpdateQa(GoodsDonQa goodsDonQa) {
		checkQAParams(goodsDonQa);

		Long id = goodsDonQa.getId();
		List<Long> goodsIds = goodsDonQa.getGoodsIds();
		if (id != null) {
			goodsDonQaRelateMapper.delete(Wrappers.lambdaQuery(GoodsDonQaRelate.class).notIn(GoodsDonQaRelate::getGoodsId, goodsIds).eq(GoodsDonQaRelate::getQuestionId, id));
			this.updateById(goodsDonQa);
		} else {
			this.save(goodsDonQa);
			id = goodsDonQa.getId();
		}
		goodsDonQaRelateMapper.batchInsert(id, goodsIds);
	}

	private void checkQAParams(GoodsDonQa goodsDonQa) {
		String problem = goodsDonQa.getProblem();
		Integer type = goodsDonQa.getType();
		if (type == null || type < 1 || type > 2) {
			throw BusinessRuntimeException.getInstance("请选择对应问题类型");
		}
		if (StrUtil.isEmpty(problem)) {
			throw BusinessRuntimeException.getInstance("问题不为空");
		}
		String url = goodsDonQa.getUrl();
		String content = goodsDonQa.getContent();
		if (ObjectUtil.isAllEmpty(url, content)) {
			throw BusinessRuntimeException.getInstance("请选择对应回答");
		}
		if (StrUtil.isNotBlank(url)) {
			goodsDonQa.setContent(null);
		}
		if (StrUtil.isNotBlank(content)) {
			goodsDonQa.setUrl(null);
		}
		List<Long> goodsIds = goodsDonQa.getGoodsIds();
		if (CollUtil.isEmpty(goodsIds)) {
			throw BusinessRuntimeException.getInstance("请选择对应展示平台");
		}
	}

	@Override
	public GoodsDonQa getDetailById(Long id) {
		GoodsDonQa byId = this.getById(id);
		byId.setGoodsIds(goodsDonQaRelateMapper.getQaGoodsByQaId(id));
		return byId;
	}
}
