package org.springblade.gateway.point_gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.lang.Assert;
import org.springblade.gateway.point_gateway.enums.PointTypeEnum;
import org.springblade.gateway.point_gateway.excetion.PointException;
import org.springblade.gateway.point_gateway.service.PointExchangeService;
import org.springblade.sing.goods.entity.GoodsRecord;
import org.springblade.sing.goods.entity.PointGoods;
import org.springblade.sing.goods.enums.GoodsRecordType;
import org.springblade.sing.goods.service.IGoodsRecordService;
import org.springblade.sing.goods.service.IPointGoodsService;
import org.springblade.sing.point.entity.PointRecord;
import org.springblade.sing.point.service.IPointRecordService;
import org.springblade.sing.user.entity.LoginUser;
import org.springblade.sing.user.service.ILoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class PointExchangeServiceImpl implements PointExchangeService {

	@Autowired
	private ILoginUserService loginUserService;
	@Autowired
	private IPointGoodsService pointGoodsService;
	@Autowired
	private IGoodsRecordService goodsRecordService;
	@Autowired
	private IPointRecordService pointRecordService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean exchange(String phone, Long goodsId, Long addressId) {

		LoginUser user = loginUserService.getOne(new LambdaQueryWrapper<LoginUser>().eq(LoginUser::getPhone,phone));
		Assert.notNull(user,"用户不存在");
		PointGoods goods = pointGoodsService.getById(goodsId);
		Assert.notNull(goods,"商品不存在");

		if (user.getPufaPoint().equals(BigDecimal.ZERO)){
			throw new PointException("积分不足");
		}

		if (user.getPufaPoint().compareTo(goods.getPoint()) < 0){
			throw new PointException("积分不足");
		}

		user.setPufaPoint(user.getPufaPoint().subtract(goods.getPoint()));

		Assert.isTrue(loginUserService.save(user),"兑换失败");

		//添加商品记录表
		GoodsRecord goodsRecord = new GoodsRecord();
		goodsRecord.setUserId(user.getId());
		goodsRecord.setPointGoodsId(goodsId);
		goodsRecord.setAddressId(addressId);
		goodsRecord.setType(GoodsRecordType.POINT_GOODS_EXCHANGE);

		Assert.isTrue(goodsRecordService.save(goodsRecord),"兑换失败");

		//添加积分消费
		PointRecord pointRecord = new PointRecord();
		pointRecord.setPoint(goods.getPoint());
		pointRecord.setUserId(user.getId());
		pointRecord.setPointGoodsId(goodsId);
		pointRecord.setPointType(PointTypeEnum.PUFA_POINT_EXCHANGE);
		Assert.isTrue(pointRecordService.save(pointRecord),"兑换失败");

		return true;
	}
}
