package com.sqx.modules.artificerselfgoods.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.exception.SqxException;
import com.sqx.modules.artificerselfgoods.dao.BlArtificerSelfGoodsDao;
import com.sqx.modules.artificerselfgoods.entity.BlArtificerSelfGoods;
import com.sqx.modules.artificerselfgoods.service.BlArtificerSelfGoodsEntryExitRecordsService;
import com.sqx.modules.artificerselfgoods.service.BlArtificerSelfGoodsService;
import com.sqx.modules.shopping.dao.GoodsTypeJpaRepository;
import com.sqx.modules.shopping.entity.GoodsType;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 消息
 */
@Service
public class BlArtificerSelfGoodsServiceImpl extends ServiceImpl<BlArtificerSelfGoodsDao, BlArtificerSelfGoods> implements BlArtificerSelfGoodsService {

	@Lazy
	@Autowired
	private BlArtificerSelfGoodsService artificerSelfGoodsService;

	@Autowired
	private GoodsTypeJpaRepository goodsJpaTypeRepository;


	@Autowired
	private BlArtificerSelfGoodsEntryExitRecordsService artificerSelfGoodsEntryExitRecordsService;

	private SysUserEntity getUser() {
		return ((SysUserEntity) SecurityUtils.getSubject().getPrincipal());
	}

	@Override
	public List<BlArtificerSelfGoods> findArtificerSelfGoodsByArtificerId(String artificerId) {
		QueryWrapper<BlArtificerSelfGoods> qw = new QueryWrapper<>();
		qw.lambda().eq(BlArtificerSelfGoods::getArtificerId, artificerId);
		return list(qw);
	}

	@Override
	public List<BlArtificerSelfGoods> findArtificerSelfGoodsByArtificerIdAndGoodsTypeId(String artificerId, String goodsTypeId) {
		QueryWrapper<BlArtificerSelfGoods> qw = new QueryWrapper<>();
		qw.lambda().eq(BlArtificerSelfGoods::getArtificerId, artificerId);
		qw.lambda().eq(BlArtificerSelfGoods::getSelfGoodsTypeId, goodsTypeId);
		return list(qw);
	}

	@Override
	public BlArtificerSelfGoods findArtificerSelfGoodsByArtificerIdAndGoodsId(String artificerId, String goodsId) {
		QueryWrapper<BlArtificerSelfGoods> qw = new QueryWrapper<>();
		qw.lambda().eq(BlArtificerSelfGoods::getArtificerId, artificerId);
		qw.lambda().eq(BlArtificerSelfGoods::getSelfGoodsId, goodsId);
		qw.last("limit 1");
		return getOne(qw);
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean addOrInWarehouse(BlArtificerSelfGoods artificerSelfGoods) {
		if(artificerSelfGoods.getId() == null){
			artificerSelfGoodsService.addWarehouse(artificerSelfGoods);
		} else {
			artificerSelfGoodsService.inWarehouse(artificerSelfGoods.getId(),artificerSelfGoods.getPurchasePrice(), artificerSelfGoods.getChangeNum());
		}
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean addOrInWarehouse(List<BlArtificerSelfGoods> artificerSelfGoodsList) {
		artificerSelfGoodsList.forEach(this::addOrInWarehouse);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean addWarehouse(BlArtificerSelfGoods artificerSelfGoods) {
		save(artificerSelfGoods);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean addWarehouse(List<BlArtificerSelfGoods> artificerSelfGoodsList) {
		artificerSelfGoodsService.saveBatch(artificerSelfGoodsList);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean inWarehouse(Long artificerSelfGoodsId, BigDecimal purchasePrice, int changeNum) {
		BlArtificerSelfGoods e = getById(artificerSelfGoodsId);
		if(e == null) return false;
		Integer afterTheChangeNum = e.getNum();
		e.setLastTimeChangeNum(changeNum);
		e.setLastTimeNum(e.getNum());
		Integer beforeTheChangeNum = afterTheChangeNum + changeNum;
		if(beforeTheChangeNum < 0){
			throw new SqxException("不可修改为负库存！");
		}
		e.setNum(beforeTheChangeNum);
		updateById(e);
		//记录日志
		artificerSelfGoodsEntryExitRecordsService.addInLog(e, null, afterTheChangeNum, beforeTheChangeNum, changeNum, purchasePrice);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean inWarehouse(List<BlArtificerSelfGoods> artificerSelfGoodsList) {
		artificerSelfGoodsList.forEach(x -> artificerSelfGoodsService.inWarehouse(x.getId(), x.getPurchasePrice(), x.getChangeNum()));
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean outWarehouse(Long artificerSelfGoodsId, int changeNum, String userId) {
		BlArtificerSelfGoods e = getById(artificerSelfGoodsId);
		if(e == null) return false;
		Integer afterTheChangeNum = e.getNum();
		e.setLastTimeChangeNum(changeNum);
		e.setLastTimeNum(e.getNum());
		Integer beforeTheChangeNum = afterTheChangeNum - changeNum;
		if(beforeTheChangeNum < 0){
			throw new SqxException("不可修改为负库存！");
		}
		e.setNum(beforeTheChangeNum);
		updateById(e);
		//记录日志
		artificerSelfGoodsEntryExitRecordsService.addOutLog(e, null, afterTheChangeNum, beforeTheChangeNum, changeNum, userId);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean outWarehouse(List<BlArtificerSelfGoods> artificerSelfGoodsList) {
		artificerSelfGoodsList.forEach(x -> artificerSelfGoodsService.outWarehouse(x.getId(), x.getChangeNum(), x.getUserId()));
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean editWarehouse(BlArtificerSelfGoods artificerSelfGoods) {
		Integer changeNum = artificerSelfGoods.getChangeNum();
		String remark = artificerSelfGoods.getRemark();

		BlArtificerSelfGoods e = findArtificerSelfGoodsByArtificerIdAndGoodsId(artificerSelfGoods.getArtificerId(), String.valueOf(artificerSelfGoods.getSelfGoodsId()));
		if(e == null) {
			//新增
			//查询type的pid
//			Specification<GoodsType> goodsTypeQc = (root, criteriaQuery, criteriaBuilder) -> {
//				List<Predicate> predicateList = new ArrayList<>();
//				predicateList.add(criteriaBuilder.equal(root.get("parentId"), "56"),criteriaBuilder.equal(root.get("id"), "56")));
//				return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
//			};
			GoodsType materialTypes = goodsJpaTypeRepository.getById(Long.valueOf(artificerSelfGoods.getGoods().getTypeId()));


			BlArtificerSelfGoods addData = new BlArtificerSelfGoods();

			addData.setCreateTime(DateUtil.now());
			addData.setUpdateTime(DateUtil.now());
			addData.setCreateAt(getUser().getUsername());
			addData.setUpdateAt(getUser().getUsername());

			addData.setSelfGoodsId(artificerSelfGoods.getGoods().getId());
			addData.setSelfGoodsTitle(artificerSelfGoods.getGoods().getTitle());
			addData.setSelfGoodsTypeId(artificerSelfGoods.getGoods().getTypeId());
			addData.setSelfGoodsTypeParentId(String.valueOf(materialTypes.getParentId()));
			addData.setArtificerId(artificerSelfGoods.getArtificerId());
			addData.setNum(artificerSelfGoods.getChangeNum());
			addData.setChangeNum(artificerSelfGoods.getChangeNum());
			addData.setRemark(artificerSelfGoods.getRemark());

			save(addData);
			artificerSelfGoodsEntryExitRecordsService.editLog(addData, getUser().getUsername(), null, null, changeNum, remark);
		} else {
			e.setUpdateTime(DateUtil.now());
			e.setUpdateAt(getUser().getUsername());
			//修改
			Integer afterTheChangeNum = e.getNum();
			e.setLastTimeChangeNum(changeNum);
			e.setLastTimeNum(e.getNum());
			Integer beforeTheChangeNum = afterTheChangeNum + changeNum;
			if(beforeTheChangeNum < 0){
				throw new SqxException("不可修改为负库存！");
			}
			e.setNum(beforeTheChangeNum);
			updateById(e);
			//记录日志
			artificerSelfGoodsEntryExitRecordsService.editLog(e, getUser().getUsername(), afterTheChangeNum, beforeTheChangeNum, changeNum, remark);
		}
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean editWarehouse(List<BlArtificerSelfGoods> artificerSelfGoodsList) {
		artificerSelfGoodsList.forEach(this::editWarehouse);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean editWarehouseById(Long artificerSelfGoodsId, int changeNum, String remark) {
		BlArtificerSelfGoods e = getById(artificerSelfGoodsId);
		if(e == null) return false;
		Integer afterTheChangeNum = e.getNum();
		e.setLastTimeChangeNum(changeNum);
		e.setLastTimeNum(e.getNum());
		Integer beforeTheChangeNum = afterTheChangeNum + changeNum;
		if(beforeTheChangeNum < 0){
			throw new SqxException("不可修改为负库存！");
		}
		e.setNum(beforeTheChangeNum);
		updateById(e);
		//记录日志
		artificerSelfGoodsEntryExitRecordsService.editLog(e, null, afterTheChangeNum, beforeTheChangeNum, changeNum, remark);
		return true;
	}

	@Transactional( rollbackFor = {Exception.class} )
	@Override
	public boolean editWarehouseById(List<BlArtificerSelfGoods> artificerSelfGoodsList) {
		artificerSelfGoodsList.forEach(x -> artificerSelfGoodsService.editWarehouseById(x.getId(), x.getChangeNum(), x.getRemark()));
		return true;
	}

}
