package org.springblade.gateway.active_gateway.controller;

import com.alibaba.fastjson.JSONObject;
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.apache.commons.lang3.ObjectUtils;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.active_gateway.util.ActiveNoticeUtil;
import org.springblade.sing.active.entity.ActiveNotice;
import org.springblade.sing.active.entity.ActiveRecord;
import org.springblade.sing.active.service.IActiveNoticeService;
import org.springblade.sing.active.service.IActiveRecordService;
import org.springframework.web.bind.annotation.GetMapping;
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 java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 11:38 2021/11/29
 * @Modified By:
 */
@RestController
@AllArgsConstructor
@RequestMapping("app/active/notice")
@Api(value = "活动通知", tags = "活动通知接口")
@Slf4j
public class AppActiveNoticeController {
	private final IActiveRecordService activeRecordService;
	private final IActiveNoticeService activeNoticeService;

	/**
	 * 初始化作品(预热)
	 */
	@PostConstruct
	public void init() {
		//查询所有的活动列表
		for (ActiveRecord activeRecord : activeRecordService.list(
			Wrappers.<ActiveRecord>lambdaQuery().select(ActiveRecord::getId))) {
			//查询该活动的所有作品
			List<ActiveNotice> activeNoticeList = activeNoticeService.list(Wrappers.<ActiveNotice>lambdaQuery()
					.select(ActiveNotice::getTitle, ActiveNotice::getContent)
					.eq(ActiveNotice::getActiveId, activeRecord.getId()));
			if (ObjectUtils.isNotEmpty(activeNoticeList) && activeNoticeList.size() != 0) {
				Map<Object, Object> map = activeNoticeList.stream().collect(Collectors.toMap(ActiveNotice::getTitle, ele-> JSONObject.toJSONString(ele)));
				ActiveNoticeUtil.setActiveNoticeMapCache(activeRecord.getId(), map);
			}
		}
	}

	@GetMapping("/getNotice")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取通知")
	public R<ActiveNotice> getNotice(@ApiParam(value = "活动ID") @RequestParam(required = false) Long activeId,
									 @ApiParam(value = "通知标题",required = true) @RequestParam String title) {
		return R.data(ActiveNoticeUtil.getActiveNoticeMapCache(activeId,title));
	}
}
