/*
 *      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.goods.wrapper;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springblade.common.utils.BeanPropertyUtil;
import org.springblade.common.utils.SpringContextHolder;
import org.springblade.core.mp.support.BaseEntityWrapper;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.gateway.goods_gateway.service.AppHelpGoodsService;
import org.springblade.sing.active.entity.ActiveHelpRecord;
import org.springblade.sing.active.service.IActiveHelpRecordService;
import org.springblade.sing.goods.entity.HelpGoods;
import org.springblade.sing.goods.vo.HelpGoodsVO;
import org.springblade.sing.point.entity.PointRecord;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import java.util.Objects;

/**
 * 助力商城包装类,返回视图层所需的字段
 *
 * @author BladeX
 * @since 2021-11-09
 */
@AllArgsConstructor
public class HelpGoodsWrapper extends BaseEntityWrapper<HelpGoods, HelpGoodsVO> {

	private final static AppHelpGoodsService appHelpGoodsService = SpringContextHolder.getBean(AppHelpGoodsService.class);

	private final static IActiveHelpRecordService activeHelpRecordService = SpringContextHolder.getBean(IActiveHelpRecordService.class);

	private final Long userId;

	private final Long productId;

	public static HelpGoodsWrapper build(Long userId, Long productId) {
		return new HelpGoodsWrapper(userId, productId);
	}

	@Override
	public HelpGoodsVO entityVO(HelpGoods helpGoods) {
		HelpGoodsVO helpGoodsVO = Objects.requireNonNull(BeanUtil.copy(helpGoods, HelpGoodsVO.class));

		//查询用户剩余道具次数
		if (ObjectUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(productId)) {
			//判断该活动商品兑换剩余次数
			long total = helpGoodsVO.getTotal() - appHelpGoodsService.userHelpGoodsExchangeCount(userId, helpGoodsVO.getId());
			//判断该用户对该活动投票剩余次数
			if (Long.valueOf(-1L).equals(helpGoodsVO.getTotal()) && Long.valueOf(-1L).equals(helpGoodsVO.getActiveVote())) {
				helpGoodsVO.setRemainCount(-1L);
			} else if (0L < total || Long.valueOf(-1).equals(helpGoodsVO.getTotal())) {
				Map<String, Object> map = activeHelpRecordService.getMap(Wrappers.<ActiveHelpRecord>query().select(new StringBuilder("ifnull(sum(")
						.append(BeanPropertyUtil.getFieldNameToUnder(ActiveHelpRecord::getVoteCount))
						.append("),0) as count")
						.toString())
					.lambda()
					.eq(ActiveHelpRecord::getProductId, productId) //判断作品ID
					.eq(ActiveHelpRecord::getUserId, userId)    //判断用户ID
					.eq(ActiveHelpRecord::getHelpGoodsId, helpGoodsVO.getId()) //判断道具ID
					.last(new StringBuilder("and date_format(")
						.append(BeanPropertyUtil.getFieldNameToUnder(PointRecord::getCreateTime))
						.append(",\"%Y-%m-%d\")=\"")
						.append(DateUtil.format(DateUtil.now(), "yyyy-MM-dd").trim()).append("\"").toString()));
				//活动允许投票数/兑换所得票数-所投的票数/兑换所得票数
				long count = BigDecimal.valueOf(helpGoodsVO.getActiveVote())
					.divide(helpGoodsVO.getVotePointRate())
					.subtract(BigDecimal.valueOf(MapUtil.getLong(map, "count"))
						.divide(helpGoodsVO.getVotePointRate())).setScale(0, RoundingMode.FLOOR).longValue();
				//判断道具兑换剩余次数和活动投票剩余次数
				if (Long.valueOf(-1).equals(helpGoodsVO.getTotal())) {
					helpGoodsVO.setRemainCount(count < 0L ? 0L : count);
				} else {
					//剩余活动次数 > 道具剩余次数 = 道具剩余次数 || 道具剩余次数 > 剩余活动投票次数 = 剩余活动投票次数
					if (count > total) {
						helpGoodsVO.setRemainCount(total < 0L ? 0L : total);
					} else {
						helpGoodsVO.setRemainCount(count < 0L ? 0L : count);
					}
				}
			} else {
				helpGoodsVO.setRemainCount(0L);
			}
		}
		//User createUser = UserCache.getUser(helpGoods.getCreateUser());
		//User updateUser = UserCache.getUser(helpGoods.getUpdateUser());
		//helpGoodsVO.setCreateUserName(createUser.getName());
		//helpGoodsVO.setUpdateUserName(updateUser.getName());

		return helpGoodsVO;
	}

}
