package com.cyksj.service.distribute.equipment.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.GroupsRelationMapper;
import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserChanceMapper;
import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserReceiveBenefitsRecordMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.service.distribute.equipment.EquipmentDistributeFrontService;
import com.cyksj.service.exchange.ExchangeCodeService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/*
 *项目名: netflix
 *文件名: EquipmentDistributeFrontServiceImpl
 *创建者: JavaZou
 *创建时间:2023/2/23 16:20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EquipmentDistributeFrontServiceImpl implements EquipmentDistributeFrontService {
	private final GroupsRelationMapper groupsRelationMapper;

	private final BeanSearcher beanSearcher;

	private final ExchangeCodeService exchangeCodeService;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	private final EquipmentUserChanceMapper equipmentUserChanceMapper;

	private final EquipmentUserReceiveBenefitsRecordMapper equipmentUserReceiveBenefitsRecordMapper;

	@Override
	public GroupsRelationView useBenefits(Long userId, Long goodsId, Long skuId, Long relationId) {
		//减少获取权益机会
		EquipmentUserChance chance = equipmentUserChanceMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserChance.class)
				.eq(EquipmentUserChance::getUserId, userId).last("limit 1"));
		if (chance == null || chance.getNum() <= 0) {
			throw BusinessRuntimeException.getInstance("可领取次数为0");
		}
		Integer num = chance.getNum();
		Integer update = equipmentUserChanceMapper.subUserChanceNoRepeat(userId, num);
		if (update != 1) {
			throw BusinessRuntimeException.getInstance("操作频繁,请刷新页面后重试");
		}
		GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder()
				.field(GroupsRelationView::getGoodsId, goodsId)
				.field(GroupsRelationView::getId, relationId)
				.field(GroupsRelationView::getStatus, GroupsRelation.Status.validity.name())
				.orderBy(GroupsRelationView::getExpiryTime).asc()
				.field(GroupsRelationView::getUserId, userId)
				.build());
		GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(skuId);
		Long orderId = null;
		if (goodsDonSku == null || !goodsDonSku.getGoodsId().equals(goodsId)) {
			throw BusinessRuntimeException.getInstance("");
		}
		if (groupsRelationView == null) {
			//领取权益时，没有车票的用户自动上车，获得对应车票
			GroupsRelation relation = exchangeCodeService.getGroupTripsTicket(null, goodsDonSku, userId, null, OrderDon.Type.EQUIPMENT, null);
			relationId = relation.getId();
			orderId = relation.getOrderId();
		} else {
			Date expiryTime = groupsRelationView.getExpiryTime();
			if (expiryTime == null) {
				throw BusinessRuntimeException.getInstance("该车位暂未发车,请发车后再领取权益");
			}
			DateTime updateExpiryTime = null;
			if (goodsDonSku.getDays() != null && goodsDonSku.getDays() > 0) {
				updateExpiryTime = DateUtil.offsetDay(expiryTime, goodsDonSku.getDays());
			} else {
				updateExpiryTime = DateUtil.offset(expiryTime, DateField.MONTH, goodsDonSku.getMonths());
			}
			groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
					.eq(GroupsRelation::getId, groupsRelationView.getId())
					.eq(GroupsRelation::getUserId, userId)
					.set(GroupsRelation::getExpiryTime, updateExpiryTime));
			groupsRelationView.setUpdateExpiryTime(updateExpiryTime);
			relationId = groupsRelationView.getId();
		}
		//记录领取记录
		saveReceiveBenefitsRecord(userId, skuId, goodsDonSku.getDays(), goodsDonSku.getMonths(), relationId, orderId, 1);
		return groupsRelationView;
	}

	public void saveReceiveBenefitsRecord(Long userId, Long skuId, Integer days, Integer num, Long relationId, Long orderId, Integer statusCode) {
		EquipmentUserReceiveBenefitsRecord record = new EquipmentUserReceiveBenefitsRecord();
		record.setUserId(userId);
		record.setSkuId(skuId);
		record.setDays(days);
		record.setNum(num);
		record.setOrderId(orderId);
		record.setRelationId(relationId);
		record.setStatusCode(statusCode);
		equipmentUserReceiveBenefitsRecordMapper.insert(record);
	}
}
