package org.springblade.gateway.active_gateway.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.active_gateway.service.AppActiveProductService;
import org.springblade.sing.active.entity.ActiveHelpRecord;
import org.springblade.sing.active.entity.ActiveRecord;
import org.springblade.sing.active.service.IActiveProductRecordService;
import org.springblade.sing.active.service.IActiveRecordService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 9:52 2021/11/9
 * @Modified By:
 */
@RestController
@AllArgsConstructor
@RequestMapping("app/active/product")
@Api(value = "助力", tags = "助力接口")
@Slf4j
public class AppActiveProductController extends BladeController {
	private final AppActiveProductService activeService;

	private final IActiveProductRecordService activeProductRecordService;

	private final IActiveRecordService activeRecordService;

	/**
	 * 初始化作品(预热)
	 */
	@PostConstruct
	public void init() {
		//查询所有的活动列表
		for (ActiveRecord activeRecord : activeRecordService.list(
			Wrappers.<ActiveRecord>lambdaQuery().select(ActiveRecord::getId))) {
			activeService.refreshActiveProductCache(activeRecord.getId());
		}
	}

	/**
	 * 作品助力
	 */
	@ApiLog("作品助力")
//	@PostMapping("/productHelp")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "作品助力", notes = "传入activeHelpRecord")
	public R<String> productHelp(@Valid ActiveHelpRecord activeHelpRecord, HttpServletRequest request) {
		try {
			//获取用户IP地址
			activeHelpRecord.setIp(IPUtils.getRealIp(request));
			activeService.activeHelp(activeHelpRecord);
			return R.success("助力成功!");
		} catch (Exception e) {
			log.error(e.getMessage());
			return R.fail(e.getMessage());
		}
	}

	/**
	 * 作品缓存刷新
	 */
	@ApiLog("作品助力")
	@PostMapping("/refreshActiveProductCache")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "作品缓存刷新", notes = "传入activeId")
	public R<String> refreshActiveProductCache(@ApiParam("活动ID") @RequestParam Long activeId) {
		activeService.refreshActiveProductCache(activeId);
		return R.success("刷新成功");
	}
}
