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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.jsonwebtoken.lang.Assert;
import org.springblade.sing.active.entity.ActiveHelp;
import org.springblade.sing.active.vo.ActiveHelpVO;
import org.springblade.sing.active.mapper.ActiveHelpMapper;
import org.springblade.sing.active.service.IActiveHelpService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

/**
 * 活动记录 服务实现类
 *
 * @author BladeX
 * @since 2021-11-22
 */
@Service
public class ActiveHelpServiceImpl extends BaseServiceImpl<ActiveHelpMapper, ActiveHelp> implements IActiveHelpService {

	@Override
	public IPage<ActiveHelpVO> selectActiveHelpPage(IPage<ActiveHelpVO> page, ActiveHelpVO activeHelp) {
		return page.setRecords(baseMapper.selectActiveHelpPage(page, activeHelp));
	}

    @Override
	@Transactional
    public ActiveHelp queryIndex(ActiveHelpVO activeHelpVO) {

		Assert.notNull(activeHelpVO.getPhone(), "请添加手机号");
		Assert.notNull(activeHelpVO.getActiveId(), "非法操作");

		synchronized(activeHelpVO.getPhone().intern()){
			ActiveHelp activeHelp = baseMapper.selectOne(new LambdaQueryWrapper<ActiveHelp>().eq(ActiveHelp::getPhone,
				activeHelpVO.getPhone()).eq(ActiveHelp::getActiveId,activeHelpVO.getActiveId()));

			if (activeHelp == null){
				Long maxIndex = baseMapper.selectIndexMax();

				if (maxIndex != null){
					activeHelpVO.setIndex(maxIndex + 1L);
				}else {
					activeHelpVO.setIndex(1L);
				}
				baseMapper.insert(activeHelpVO);
			}
			return baseMapper.selectOne(new LambdaQueryWrapper<ActiveHelp>().eq(ActiveHelp::getPhone,activeHelpVO.getPhone()));
		}
	}

}
