/*
 *      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.userMedal.service.impl;

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.modules.guosen.loginUser.entity.LoginUser;
import org.springblade.modules.guosen.loginUser.service.ILoginUserService;
import org.springblade.modules.guosen.medal.entity.Medal;
import org.springblade.modules.guosen.medal.service.IMedalService;
import org.springblade.modules.guosen.pointsDetail.entity.PointsDetail;
import org.springblade.modules.guosen.pointsDetail.service.IPointsDetailService;
import org.springblade.modules.guosen.userActivityStatistical.entity.UserActivityStatistical;
import org.springblade.modules.guosen.userActivityStatistical.service.IUserActivityStatisticalService;
import org.springblade.modules.guosen.userMedal.entity.UserMedal;
import org.springblade.modules.guosen.userMedal.mapper.UserMedalMapper;
import org.springblade.modules.guosen.userMedal.service.IUserMedalService;
import org.springblade.modules.guosen.userMedal.vo.UserMedalVO;
import org.springblade.modules.guosen.userMedalExchange.entity.UserMedalExchange;
import org.springblade.modules.guosen.userMedalExchange.service.IUserMedalExchangeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-06-18
 */
@Service
public class UserMedalServiceImpl extends BaseServiceImpl<UserMedalMapper, UserMedal> implements IUserMedalService {

	@Resource
	private IMedalService medalService;
	@Resource
	private ILoginUserService loginUserService;
	@Resource
	private IPointsDetailService pointsDetailService;
	@Resource
	private IUserMedalExchangeService userMedalExchangeService;
	@Resource
	private IUserActivityStatisticalService userActivityStatisticalService;

	@Override
	public IPage<UserMedalVO> selectUserMedalPage(IPage<UserMedalVO> page, UserMedalVO userMedal) {
		return page.setRecords(baseMapper.selectUserMedalPage(page, userMedal));
	}
	@Override
	@Transactional
	public R exchange(List<UserMedal> userMedalList) {
		BigDecimal exchangePointsValue = BigDecimal.ZERO;
		for (UserMedal item: userMedalList) {
			//获取该用户的勋章
			UserMedal userMedal = this.getById(item.getId());
			if ( item.getCount()>userMedal.getCount() || item.getCount() <= 0) {
				return R.fail("兑换失败，兑换数量有误");
			}
			Long medalId = userMedal.getMedalId();
			Medal medal = medalService.getById(medalId);
			//兑换勋章获取的积分值
			BigDecimal pointsValue = medal.getPointsValue().multiply(BigDecimal.valueOf(item.getCount()));
			//剩余数量
			int count = userMedal.getCount() - item.getCount();
			if (count == 0) {
				//删除
				this.removeById(userMedal);
			}else{
				userMedal.setCount(count);
				this.updateById(userMedal);
			}
			//用户积分增加
			LoginUser user = loginUserService.getById(item.getUserId());
			BigDecimal totalPoints = user.getTotalPoints();
			BigDecimal usablePoints = user.getUsablePoints();
			BigDecimal num1 = totalPoints == null|| totalPoints.equals(BigDecimal.ZERO) ? pointsValue : (pointsValue.add(totalPoints));
			BigDecimal num2 = usablePoints == null|| usablePoints.equals(BigDecimal.ZERO) ? pointsValue : (pointsValue.add(usablePoints));
			user.setTotalPoints(num1);
			user.setUsablePoints(num2);
			loginUserService.updateById(user);
			exchangePointsValue = exchangePointsValue.add(pointsValue);
			//用户活动统计的积分增加
			List<Long> activityIds = Func.toLongList(item.getActivityIds());
			for (Long activityId : activityIds) {
				UserActivityStatistical statistical = userActivityStatisticalService.getOne(Condition.getQueryWrapper(new UserActivityStatistical()).lambda()
					.eq(UserActivityStatistical::getUserId, user.getId())
					.eq(UserActivityStatistical::getActivityId, activityId));
				BigDecimal usablePointsValue = statistical.getUsablePointsValue();
				BigDecimal totalPointsValue = statistical.getTotalPointsValue();
				BigDecimal n1 = usablePointsValue == null|| usablePointsValue.equals(BigDecimal.ZERO) ? pointsValue : (pointsValue.add(usablePointsValue));
				BigDecimal n2 = totalPointsValue == null|| totalPointsValue.equals(BigDecimal.ZERO) ? pointsValue : (pointsValue.add(totalPointsValue));
				statistical.setUsablePointsValue(n1);
				statistical.setTotalPointsValue(n2);
				userActivityStatisticalService.updateById(statistical);
			}
			//用户勋章兑换记录
			UserMedalExchange userMedalExchange = new UserMedalExchange();
			userMedalExchange.setCount(item.getCount());
			userMedalExchange.setMedalId(item.getMedalId());
			userMedalExchange.setMedalName(medal.getName());
			userMedalExchange.setPointsValues(pointsValue);
			userMedalExchange.setUserId(item.getUserId());
			userMedalExchangeService.save(userMedalExchange);
		}
		//积分明细
		PointsDetail pointsDetail = new PointsDetail();
		pointsDetail.setUserId(userMedalList.get(0).getUserId());
		pointsDetail.setPointsValue(exchangePointsValue);
		pointsDetail.setType(3);
		pointsDetail.setNote("勋章兑换");
		pointsDetailService.save(pointsDetail);

		return R.data(exchangePointsValue);
	}

}
