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

import org.springblade.common.cache.ParamCache;
import org.springblade.common.enums.IntegralSourceEnum;
import org.springblade.common.enums.PrizeTypeEnum;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.modules.activities.entity.SignIn;
import org.springblade.modules.activities.entity.SignInRecord;
import org.springblade.modules.activities.service.ISignInRecordService;
import org.springblade.modules.activities.vo.SignInVO;
import org.springblade.modules.activities.mapper.SignInMapper;
import org.springblade.modules.activities.service.ISignInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.modules.activities.wrapper.SignInWrapper;
import org.springblade.modules.api.vo.SignInPrizeVO;
import org.springblade.modules.mall.entity.GoodsInfo;
import org.springblade.modules.mall.service.IGoodsInfoService;
import org.springblade.modules.platform.service.IUserAppService;
import org.springblade.modules.system.entity.UserApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 签到信息表 服务实现类
 *
 * @author BladeX
 * @since 2023-05-05
 */
@Service
public class SignInServiceImpl extends ServiceImpl<SignInMapper, SignIn> implements ISignInService {

	@Autowired
	private ISignInRecordService signInRecordService;
	@Autowired
	private IUserAppService userAppService;
	@Autowired
	private IGoodsInfoService goodsInfoService;

	@Override
	public IPage<SignInVO> selectSignInPage(IPage<SignInVO> page, SignInVO signIn) {
		return page.setRecords(baseMapper.selectSignInPage(page, signIn));
	}

	@Override
	public SignInVO getUserSignInfo(Long userId) {
		SignIn signIn = this.lambdaQuery().eq(SignIn::getUserId, userId).one();
		// 没有数据时，初始化数据
		if (signIn == null) {
			signIn = new SignIn();
			signIn.setDays(0);
			signIn.setUserId(userId);
			this.save(signIn);
		}
		SignInVO signInVO = SignInWrapper.build().entityVO(signIn);
		List<SignInPrizeVO> signInPrize = this.getSignInPrizeList(userId);
		for (SignInPrizeVO signInPrizeVO : signInPrize) {
			signInPrizeVO.setSignIn(signIn.getDays() >= signInPrizeVO.getDays());
		}
		signInVO.setPrizeList(signInPrize);
		return signInVO;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public SignInVO signIn(Long userId) {
		SignIn signIn = this.lambdaQuery().eq(SignIn::getUserId, userId).one();
		Assert.notNull(signIn, "数据不存在");
		LocalDateTime now = LocalDateTime.now();
		// 最后签到时间不为空并且等于今天，则不能继续签到
		if (signIn.getLastSignInTime() != null && signIn.getLastSignInTime().toLocalDate().equals(now.toLocalDate())) {
			throw new ServiceException("您今天已签到");
		}
		signIn.setLastSignInTime(now);
		signIn.setDays(signIn.getDays() + 1);
		if (signIn.getDays() > 7) {
			throw new ServiceException("您已领满七天的奖励");
		}
		this.updateById(signIn);

		// save signInRecord
		SignInRecord signInRecord = new SignInRecord();
		signInRecord.setSignInId(signIn.getId());
		signInRecordService.save(signInRecord);

		SignInVO signInVO = SignInWrapper.build().entityVO(signIn);
		// 获取当日签到的奖励
		SignInPrizeVO prize = getCurrDayPrize(signIn.getDays(), userId);
		if (PrizeTypeEnum.INTEGRAL.getValue().equals(prize.getPrizeType())) {
			// 增加用户积分
			userAppService.addIntegral(userId, Double.parseDouble(prize.getPrizeNum().toString()), IntegralSourceEnum.SIGN_IN, "签到赠送");
		} else if (PrizeTypeEnum.REAL_GOODS.getValue().equals(prize.getPrizeType())) {
			// 查询签到商品信息
			String value = ParamCache.getValue("signin:prize:goodsId");
			GoodsInfo goodsInfo = goodsInfoService.getById(value);
			signInVO.setGoodsInfo(goodsInfo);
		}
		return signInVO;
	}

	@Override
	public List<SignIn> getNotContinuous() {
		return baseMapper.getNotContinuous();
	}

	/**
	 * 获取签到奖励列表
	 * @return
	 */
	private List<SignInPrizeVO> getSignInPrizeList(Long userId) {
		UserApp userApp = userAppService.getByUserId(userId);
		SignInPrizeVO first = new SignInPrizeVO(1, 2L, 1);
		SignInPrizeVO second = new SignInPrizeVO(2, 5L, 1);
		SignInPrizeVO third = new SignInPrizeVO(3, 5L, 1);
		SignInPrizeVO fourth = new SignInPrizeVO(4, 8L, 1);
		SignInPrizeVO fifth = new SignInPrizeVO(5, 8L, 1);
		SignInPrizeVO sixth = new SignInPrizeVO(6, 10L, 1);
		SignInPrizeVO seventh;
		if (userApp.getFreeWine()) {
			seventh = new SignInPrizeVO(7, 20L, 1);
		} else {
			seventh = new SignInPrizeVO(7, 1L, 2, "酒一瓶");
		}
		List<SignInPrizeVO> list = new ArrayList<>();
		list.add(first);
		list.add(second);
		list.add(third);
		list.add(fourth);
		list.add(fifth);
		list.add(sixth);
		list.add(seventh);
		return list;
	}


	/**
	 * 获取当日签到的奖励
	 * @param days 当天签到的天数
	 * @return
	 */
	private SignInPrizeVO getCurrDayPrize(Integer days, Long userId) {
		List<SignInPrizeVO> prizeList = this.getSignInPrizeList(userId);
		for (SignInPrizeVO vo : prizeList) {
			if (vo.getDays().equals(days)) {
				return vo;
			}
		}
		throw new ServiceException("获取当日签到的奖励异常");
	}

}
