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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.finance.entity.OrderGrant;
import org.springblade.modules.finance.vo.OrderGrantVO;
import org.springblade.modules.finance.mapper.OrderGrantMapper;
import org.springblade.modules.finance.service.IOrderGrantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;

/**
 * 订单预授权表 服务实现类
 *
 * @author BladeX
 * @since 2022-03-27
 */
@Service
public class OrderGrantServiceImpl extends ServiceImpl<OrderGrantMapper, OrderGrant> implements IOrderGrantService {

	@Override
	public IPage<OrderGrantVO> selectOrderGrantPage(IPage<OrderGrantVO> page, OrderGrantVO orderGrant) {
		return page.setRecords(baseMapper.selectOrderGrantPage(page, orderGrant));
	}

	@Override
	public List<OrderGrant> selectGrant(Long batNo, Long userId) {
		List<OrderGrant> list = baseMapper.selectList(Wrappers.<OrderGrant>lambdaQuery()
			.eq(OrderGrant::getBatNo,batNo)
			.eq(OrderGrant::getUserId, userId)
				.ne(OrderGrant::getStatus, 0) //不能为0;
				.eq(OrderGrant::getDataDate, DateUtil.format(DateUtil.now(), DateUtil.PATTERN_DATE))
			//.eq(OrderGrant::getStatus, 1) //查询已经做预授权的 改为删除当日全部
		);
		//查询正在做预授权的数据
		return list;
	}

	/**
	 * 修改数据
	 * @param entity 修改数据
	 * @return boolean
	 */
	@Override
	public boolean thaw(OrderGrant entity) {
		OrderGrant grantUpdate = new OrderGrant();
		grantUpdate.setId(entity.getId());
		//剩余数量为1时，把授权状态变为已解冻
		if (entity.getNowNum() == 1){
			grantUpdate.setStatus(2);//解冻
			grantUpdate.setNowNum(0);
			grantUpdate.setUnfreezeTime(DateUtil.now());//解冻时间
		}else{
			//状态不变
			grantUpdate.setNowNum(entity.getNowNum() - 1);//减少数量
		}
		int i = baseMapper.updateById(grantUpdate);
		return i == 1;
	}

}
