/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.guosen.userGoods.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.guosen.goods.entity.Goods;
import org.springblade.modules.guosen.goods.service.IGoodsService;
import org.springblade.modules.guosen.goodsRecord.entity.GoodsRecord;
import org.springblade.modules.guosen.goodsRecord.service.IGoodsRecordService;
import org.springblade.modules.guosen.medal.entity.Medal;
import org.springblade.modules.guosen.medal.service.IMedalService;
import org.springblade.modules.guosen.present.entity.Present;
import org.springblade.modules.guosen.present.service.IPresentService;
import org.springblade.modules.guosen.userGoods.dto.UserGoodsDTO;
import org.springblade.modules.guosen.userGoods.entity.UserGoods;
import org.springblade.modules.guosen.userGoods.mapper.UserGoodsMapper;
import org.springblade.modules.guosen.userGoods.service.IUserGoodsService;
import org.springblade.modules.guosen.userGoods.vo.DonateVO;
import org.springblade.modules.guosen.userGoods.vo.UserGoodsVO;
import org.springblade.modules.guosen.userGoodsDonate.entity.UserGoodsDonate;
import org.springblade.modules.guosen.userGoodsDonate.service.IUserGoodsDonateService;
import org.springblade.modules.guosen.userMedal.entity.UserMedal;
import org.springblade.modules.guosen.userMedal.service.IUserMedalService;
import org.springblade.modules.system.vo.DataScopeVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-06-18
 */
@Service
public class UserGoodsServiceImpl extends BaseServiceImpl<UserGoodsMapper, UserGoods> implements IUserGoodsService {

	@Resource
	private IUserGoodsDonateService userGoodsDonateService;
	@Resource
	private IPresentService presentService;
	@Resource
	private IUserMedalService userMedalService;
	@Resource
	private IMedalService medalService;
	@Resource
	private IGoodsRecordService goodsRecordService;
	@Resource
	private IGoodsService goodsService;

	@Override
	public IPage<UserGoodsVO> selectUserGoodsPage(IPage<UserGoodsVO> page, UserGoodsVO userGoods) {
		return page.setRecords(baseMapper.selectUserGoodsPage(page, userGoods));
	}

	@Override
	public IPage<UserGoodsVO> getMyGoods(IPage<UserGoodsVO> page, UserGoodsDTO userGoods) {
		return page.setRecords(baseMapper.getMyGoods(page, userGoods));
	}

	@Override
	public List<UserGoodsVO> getMyGoods(UserGoodsDTO userGoods) {
		return baseMapper.getMyGoods(userGoods);
	}

	@Override
	@Transactional
	public R donate(List<UserGoods> userGoods) {
		List<DonateVO> donateVOList = new ArrayList<>();
		for (UserGoods item : userGoods) {
			//我的实物
			UserGoods myGoods = this.getById(item.getId());
			Integer itemCount = item.getCount();
			if (myGoods.getCount()< itemCount || itemCount <= 0) {
				return R.fail("捐赠失败，捐赠数量有误");
			}
			//实物详情
			Goods goods = goodsService.getById(myGoods.getGoodsId());
			//捐赠获取的勋章
			Long donateMedalId = goods.getDonateMedalId();
			Medal medal = medalService.getById(donateMedalId);
			//剩余数量
			int count = myGoods.getCount() - itemCount;
			if (count == 0) {
				//删除
				this.removeById(myGoods);
			}else{
				myGoods.setCount(count);
				this.updateById(myGoods);
			}
			//获取勋章
			UserMedal medalServiceOne = userMedalService.getOne(Condition.getQueryWrapper(new UserMedal()).lambda()
				.eq(UserMedal::getUserId, item.getUserId())
				.eq(UserMedal::getMedalId, donateMedalId));
			if (medalServiceOne!= null) {
				Integer medalServiceOneCount = medalServiceOne.getCount();
				Integer num= medalServiceOneCount== null ? itemCount : (medalServiceOneCount + itemCount);
				medalServiceOne.setCount(num);
				List<Long> longs = Func.toLongList(medalServiceOne.getActivityIds());
				List<Long> longs1 = Func.toLongList(item.getActivityIds());
				Set<Long> idsSet = new TreeSet<>(longs);
				Set<Long> idsSet1 = new TreeSet<>(longs1);
				idsSet.addAll(idsSet1);
				medalServiceOne.setActivityIds(StringUtil.join(idsSet));
				userMedalService.updateById(medalServiceOne);
			}else{
				UserMedal userMedalSave = new UserMedal();
				userMedalSave.setMedalId(donateMedalId);
				userMedalSave.setUserId(item.getUserId());
				userMedalSave.setCount(itemCount);
				userMedalSave.setActivityIds(item.getActivityIds());
				userMedalService.save(userMedalSave);
			}
			//插入捐赠记录表
			UserGoodsDonate userGoodsDonate = new UserGoodsDonate();
			userGoodsDonate.setMedalName(medal.getName());
			userGoodsDonate.setUserId(item.getUserId());
			userGoodsDonate.setCount(itemCount);
			userGoodsDonate.setDonateTime(LocalDateTime.now());
			userGoodsDonate.setMedalId(donateMedalId);
			userGoodsDonate.setGoodsId(goods.getId());
			userGoodsDonateService.save(userGoodsDonate);
			//封装返回的数据
			List<DonateVO> donateVOS = donateVOList.stream().filter(line -> line.getMedalId().equals(medal.getId())).collect(Collectors.toList());
			if (CollUtil.isEmpty(donateVOS)) {
				DonateVO donateVO = new DonateVO();
				donateVO.setMedalId(medal.getId());
				donateVO.setMedalName(medal.getName());
				donateVO.setCount(itemCount);
				donateVOList.add(donateVO);
			}else {
				DonateVO donateVO = donateVOS.get(0);
				donateVO.setCount(donateVO.getCount() + itemCount);
			}
		}
		return R.data(donateVOList);
	}

	@Override
	@Transactional
	public R obtain(List<UserGoodsDTO> userGoodsDTOS) {
		for (UserGoodsDTO item : userGoodsDTOS) {
			UserGoods myGoods = this.getById(item.getId());
			if (myGoods.getCount()<item.getCount() || item.getCount() <= 0) {
				return R.fail("领取失败，领取数量有误");
			}
			//剩余数量
			int count = myGoods.getCount() - item.getCount();
			if (count == 0) {
				//删除
				this.removeById(myGoods);
			}else{
				myGoods.setCount(count);
				this.updateById(myGoods);
			}
			//插入领取记录表
			Goods goods = goodsService.getById(myGoods.getGoodsId());

			GoodsRecord goodsRecord = new GoodsRecord();
			goodsRecord.setUserId(item.getUserId());
			goodsRecord.setGoodsId(goods.getId());
			goodsRecord.setGoodsName(goods.getGoodsName());
			goodsRecord.setGoodsPic(goods.getGoodsPic());
			goodsRecord.setCount(item.getCount());
			goodsRecord.setGoodsPostAmount(goods.getGoodsPostAmount());
			goodsRecord.setDistributionId(item.getDistributionId());
			goodsRecord.setDistributionStatus(0);
			goodsRecord.setAddressId(item.getAddressId());
			goodsRecordService.save(goodsRecord);
		}
		return R.status(true);
	}
}
