package com.ruoyi.web.controller.cgb;

import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.cgb.domain.CgbScoreDetail;
import com.ruoyi.cgb.domain.CgbScoreItem;
import com.ruoyi.cgb.domain.CgbScoreSession;
import com.ruoyi.cgb.domain.CgbWorksInfo;
import com.ruoyi.cgb.service.ICgbScoreDetailService;
import com.ruoyi.cgb.service.ICgbScoreItemService;
import com.ruoyi.cgb.service.ICgbScoreSessionService;
import com.ruoyi.cgb.service.ICgbWorksInfoService;
import com.ruoyi.common.core.domain.AjaxResult;

@RestController
@RequestMapping("/cgbActive")
public class CgbActiveController {

	@Autowired
	private ICgbScoreSessionService cgbScoreSessionService;

	@Autowired
	private ICgbScoreDetailService cgbScoreDetailService;

	@Autowired
	private ICgbScoreItemService cgbScoreItemService;

	@Autowired
	private ICgbWorksInfoService cgbWorksInfoService;

	
	
	

	/**
	 * 接口0：创建评分场次
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/createScoreSession")
	public AjaxResult createScoreSession() {
		CgbScoreSession session = new CgbScoreSession();
		session.setStatus("1");
		session.setCurrScoreWorksGroup("0");
		session.setCurrRankWorksGroup("0");
		cgbScoreSessionService.save(session);
		return AjaxResult.success(session);
	}

	/**
	 *  接口1：查看当前场次信息
	 * 
	 * @return
	 */
	@GetMapping(value = "/queryCurrScoreSession")
	public AjaxResult queryCurrScoreSession() {
		CgbScoreSession session = new CgbScoreSession();
		List<CgbScoreSession> sessionList = cgbScoreSessionService.queryList(session);
		if (sessionList != null && !sessionList.isEmpty()) {
			return AjaxResult.success(sessionList.get(0));
		} else {
			return AjaxResult.error("暂无评分场次，请先创建");
		}

	}
	
	/**
	 *  接口2：查看作品列表
	 * 
	 * @return
	 */
	@GetMapping(value = "/queryWorkList")
	public AjaxResult queryWorkList(CgbScoreItem cgbScoreItem) {
		Long sessionId = cgbScoreItem.getSessionId();
		if (sessionId == null) {
			throw new RuntimeException("场次id不能为空");
		}
		CgbWorksInfo cgbWorksInfo = new CgbWorksInfo();
		
		
		List<CgbWorksInfo> list = cgbWorksInfoService.queryList(cgbWorksInfo);
		for(CgbWorksInfo w:list) {
			CgbScoreItem itemQo=new CgbScoreItem();
			itemQo.setSessionId(sessionId);
			itemQo.setWorksGroup(w.getWorksGroup());
			List<CgbScoreItem> itemList = cgbScoreItemService.queryList(itemQo);
			if(itemList!=null && !itemList.isEmpty()) {
				CgbScoreItem item=itemList.get(0);
				if(item!=null && "1".equals(item.getIsStopScore())) {
					w.setIsStopScore("1");
				}else {
					w.setIsStopScore("0");
				}
				w.setIsStartScore("1");
			}else {
				w.setIsStartScore("0");
				w.setIsStopScore("0");
			}
			
		}
		
		Collections.sort(list, new Comparator<CgbWorksInfo>() {
			@Override
			public int compare(CgbWorksInfo o1, CgbWorksInfo o2) {
				return Integer.parseInt(o1.getWorksGroup())-Integer.parseInt(o2.getWorksGroup());
			}
		});
		
		
		return AjaxResult.success(list);
	}

	/**
	 * 接口3：管理员开启评分通道
	 * 
	 * @param cgbScoreDetail
	 * @return
	 */
	@PostMapping(value = "/adminStartScore")
	public AjaxResult adminStartScore(@RequestBody CgbScoreDetail cgbScoreDetail) {
		// 场次id
		Long sessionId = cgbScoreDetail.getSessionId();
		// 作品组号
		String worksGroup = cgbScoreDetail.getWorksGroup();

		if (sessionId == null || StringUtils.isBlank(worksGroup)) {
			throw new RuntimeException("场次id或作品组号不能为空");
		}

		CgbScoreItem cgbScoreItem = new CgbScoreItem();
		cgbScoreItem.setSessionId(sessionId);
		cgbScoreItem.setWorksGroup(worksGroup);

		List<CgbScoreItem> itemList = cgbScoreItemService.queryList(cgbScoreItem);
		if (itemList == null || itemList.isEmpty()) {
			CgbScoreItem item = new CgbScoreItem();
			item.setSessionId(sessionId);
			item.setIsStopScore("0");
			item.setWorksGroup(worksGroup);
			item.setTotalCommentCtl(0);
			item.setMaxScore(0d);
			item.setMinScore(0d);
			item.setCurrScore(0d);
			item.setRanking(0);
			item.setStatus("1");
			cgbScoreItemService.save(item);
		}

		CgbScoreSession cgbScoreSession = cgbScoreSessionService.getById(sessionId);
		cgbScoreSession.setCurrScoreWorksGroup(worksGroup);
		cgbScoreSessionService.updateById(cgbScoreSession);

		CgbScoreItem item = doQuerySubmitInfo(cgbScoreItem);

		return AjaxResult.success(item);
	}

	/**
	 * 接口4：查看评分信息
	 * 
	 * @param cgbScoreItem
	 * @return
	 */
	@GetMapping(value = "/querySubmitInfo")
	public AjaxResult querySubmitInfo(CgbScoreItem cgbScoreItem) {
		try {
			CgbScoreItem item = doQuerySubmitInfo(cgbScoreItem);
			return AjaxResult.success(item);
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
	}

	private CgbScoreItem doQuerySubmitInfo(CgbScoreItem cgbScoreItem) {

		// 场次id
		Long sessionId = cgbScoreItem.getSessionId();

		// 作品组号
		String worksGroup = cgbScoreItem.getWorksGroup();

		if (sessionId == null || StringUtils.isBlank(worksGroup)) {
			throw new RuntimeException("场次id或作品组号不能为空");
		}

		CgbScoreSession cgbScoreSession = cgbScoreSessionService.getById(sessionId);

		CgbScoreItem qo = new CgbScoreItem();
		qo.setSessionId(sessionId);
		qo.setWorksGroup(worksGroup);

		List<CgbScoreItem> itemList = cgbScoreItemService.queryList(qo);
		if (itemList == null || itemList.isEmpty()) {
			CgbScoreItem zone = new CgbScoreItem();
			zone.setSessionId(sessionId);
			zone.setWorksGroup(worksGroup);
			zone.setMaxScore(0d);
			zone.setMinScore(0d);
			zone.setCurrScore(0d);
			zone.setRemark("0");
			zone.setTotalCommentCtl(0);
			zone.setCurrScoreWorksGroup("0");
			return zone;

		}

		CgbScoreItem item = itemList.get(0);
		if (cgbScoreSession != null) {

			CgbWorksInfo currCgbWorksInfoQo = new CgbWorksInfo();
			currCgbWorksInfoQo.setWorksGroup(cgbScoreSession.getCurrScoreWorksGroup());

			List<CgbWorksInfo> cgbWorksInfoList = cgbWorksInfoService.queryList(currCgbWorksInfoQo);
			if (cgbWorksInfoList != null && cgbWorksInfoList.get(0) != null) {
				item.setCurrCgbWorksInfo(cgbWorksInfoList.get(0));
			}

			CgbScoreDetail cgbScoreDetailQo = new CgbScoreDetail();
			cgbScoreDetailQo.setSessionId(sessionId);
			cgbScoreDetailQo.setWorksGroup(cgbScoreSession.getCurrScoreWorksGroup());
			List<CgbScoreDetail> currScoreDetailList = cgbScoreDetailService.queryList(cgbScoreDetailQo);

			item.setCurrScoreDetailList(currScoreDetailList);

			item.setTotalCommentCtl(currScoreDetailList.size());

			item.setCurrScoreWorksGroup(cgbScoreSession.getCurrScoreWorksGroup());
		}
		return item;
	}

	/**
	 * 接口5：评委提交评分
	 * 
	 * @return
	 */
	@PostMapping(value = "/commentSumitScore")
	public AjaxResult commentSumitScore(@RequestBody CgbScoreDetail cgbScoreDetail) {

		// 场次id
		Long sessionId = cgbScoreDetail.getSessionId();
		// 作品组号
		String worksGroup = cgbScoreDetail.getWorksGroup();

		CgbScoreSession cgbScoreSession = cgbScoreSessionService.getById(sessionId);

		String commentId = cgbScoreDetail.getCommentId();

		/** 评分1 */
		Double score1 = cgbScoreDetail.getScore1();

		/** 评分2 */
		Double score2 = cgbScoreDetail.getScore2();

		/** 评分3 */
		Double score3 = cgbScoreDetail.getScore3();

		/** 评分4 */
		Double score4 = cgbScoreDetail.getScore4();

		if (sessionId == null || StringUtils.isBlank(worksGroup) || StringUtils.isBlank(commentId) || score1 == null || score2 == null || score3 == null
				|| score4 == null) {
			return AjaxResult.error("场次id、作品组号、评委id、评分不能为空");
		}

		CgbScoreDetail cgbScoreDetailQo = new CgbScoreDetail();
		cgbScoreDetailQo.setSessionId(sessionId);
		cgbScoreDetailQo.setWorksGroup(cgbScoreSession.getCurrScoreWorksGroup());
		cgbScoreDetailQo.setCommentId(commentId);
		List<CgbScoreDetail> currScoreDetailList = cgbScoreDetailService.queryList(cgbScoreDetailQo);
		if (currScoreDetailList != null && !currScoreDetailList.isEmpty()) {
			return AjaxResult.error("您已经提交过了，请勿重复提交");
		}

		cgbScoreDetailService.save(cgbScoreDetail);
//		TODO	统计评分

		CgbScoreItem cgbScoreItem = new CgbScoreItem();
		cgbScoreItem.setSessionId(sessionId);
		cgbScoreItem.setWorksGroup(worksGroup);

		List<CgbScoreItem> itemList = cgbScoreItemService.queryList(cgbScoreItem);

		if (itemList != null && !itemList.isEmpty()) {

			CgbScoreItem item = itemList.get(0);
			item.setTotalCommentCtl(item.getTotalCommentCtl() == null ? 1 : (item.getTotalCommentCtl() + 1));
			cgbScoreItemService.updateById(item);

		}

		CgbScoreItem item = doQuerySubmitInfo(cgbScoreItem);

		return AjaxResult.success(item);
	}

	

	/**
	 * 接口6：管理员确认评分
	 * 
	 * @param cgbScoreDetail
	 * @return
	 */
	@PostMapping(value = "/adminConfirmScore")
	public AjaxResult adminConfirmScore(@RequestBody CgbScoreDetail cgbScoreDetail) {

		// 场次id
		Long sessionId = cgbScoreDetail.getSessionId();

		// 作品组号
		String worksGroup = cgbScoreDetail.getWorksGroup();

		if (sessionId == null || StringUtils.isBlank(worksGroup)) {
			throw new RuntimeException("场次id或作品组号不能为空");
		}

		CgbScoreItem cgbScoreItem = new CgbScoreItem();
		cgbScoreItem.setSessionId(sessionId);

		// 所有作品评分
		Map<String, CgbScoreItem> itemMap = new HashMap<String, CgbScoreItem>();
		List<CgbScoreItem> itemList = cgbScoreItemService.queryList(cgbScoreItem);
		if (itemList != null && !itemList.isEmpty() && itemList.get(0) != null) {
			for (CgbScoreItem item : itemList) {
				itemMap.put(item.getWorksGroup(), item);
			}
			for (CgbScoreItem item : itemMap.values()) {

				CgbScoreDetail cgbScoreDetailQo1 = new CgbScoreDetail();
				cgbScoreDetailQo1.setSessionId(sessionId);
				cgbScoreDetailQo1.setWorksGroup(item.getWorksGroup());
				List<CgbScoreDetail> detailList = cgbScoreDetailService.queryList(cgbScoreDetailQo1);

				double totalScore = 0;
				double maxScore = 0;
				double minScore = 0;
				double currScore = 0;
				int totalCommentCtl = 0;

				if (detailList != null && !detailList.isEmpty()) {
					Double[] list = new Double[detailList.size()];
					totalCommentCtl = detailList.size();// 评分人数
//					for (CgbScoreDetail detail : detailList) {
						for (int i = 0; i < detailList.size(); i++) {
							CgbScoreDetail detail = detailList.get(i);

							double score = (detail.getScore1() == null ? 0d : detail.getScore1()) + (detail.getScore2() == null ? 0d : detail.getScore2())
								+ (detail.getScore3() == null ? 0d : detail.getScore3()) + (detail.getScore4() == null ? 0d : detail.getScore4());
//						if (maxScore < score) {
//							maxScore = score;
//						}
//						if (minScore > score) {
//							minScore = score;
//						}
						list[i] = score;
						totalScore = totalScore + score;
					}
					Arrays.sort(list);
					maxScore =list[list.length-1];
					minScore = list[0];
					
					if (totalCommentCtl > 2) {
//						currScore = (totalScore - maxScore - minScore) / (totalCommentCtl - 2);// 去掉最高分，最低分
						currScore = totalScore / totalCommentCtl;//不再去掉最高分最底分，直接取平均分
					} else if (totalCommentCtl > 0) {
						currScore = totalScore / totalCommentCtl;
					}
 
				}

				item.setTotalCommentCtl(totalCommentCtl);
				item.setMaxScore(maxScore);
				item.setMinScore(minScore);
				item.setCurrScore(currScore);
				item.setTotalScore(totalScore);

			}

			List<CgbScoreItem> allItemList = new ArrayList<CgbScoreItem>();
			allItemList.addAll(itemMap.values());

			Collections.sort(allItemList, new Comparator<CgbScoreItem>() {
				@Override
				public int compare(CgbScoreItem o1, CgbScoreItem o2) {
					double diff = o2.getCurrScore() - o1.getCurrScore();
					if (diff > 0) {
						return 1;
					} else if (diff < 0) {
						return -1;
					} else {
						return 0;
					}
				}
			});

			for (int i = 0; i < allItemList.size(); i++) {
				int r = i + 1;
				CgbScoreItem item = allItemList.get(i);
				item.setRanking(r);
				if(worksGroup.equals(item.getWorksGroup())) {
					item.setIsStopScore("1");
				}
				cgbScoreItemService.updateById(item);
			}
		}

		CgbScoreSession cgbScoreSession = cgbScoreSessionService.getById(sessionId);
		cgbScoreSession.setCurrRankWorksGroup(worksGroup);
		cgbScoreSessionService.updateById(cgbScoreSession);

		return AjaxResult.success();
	}

	/**
	 * 接口7：查看排行榜
	 * 
	 * @param cgbScoreDetail
	 * @return
	 */
	@GetMapping(value = "/queryRank")
	public AjaxResult queryRank(CgbScoreDetail cgbScoreDetail) {
		CgbWorksInfo cgbWorksInfo = new CgbWorksInfo();
		List<CgbWorksInfo> list = cgbWorksInfoService.queryList(cgbWorksInfo);
		// 场次id
		Long sessionId = cgbScoreDetail.getSessionId();

		if (sessionId == null) {
			throw new RuntimeException("场次id不能为空");
		}

		for (CgbWorksInfo work : list) {
			CgbScoreItem cgbScoreItem = new CgbScoreItem();
			cgbScoreItem.setSessionId(sessionId);
			cgbScoreItem.setWorksGroup(work.getWorksGroup());
			List<CgbScoreItem> itemList = cgbScoreItemService.queryList(cgbScoreItem);

			if (itemList != null && !itemList.isEmpty()) {
				CgbScoreItem item = itemList.get(0);
				work.setTotalCommentCtl(item.getTotalCommentCtl());
				work.setMaxScore(item.getMaxScore());
				work.setMinScore(item.getMinScore());
				work.setCurrScore(item.getCurrScore());
				work.setRanking(item.getRanking());
			} else {
				work.setTotalCommentCtl(0);
				work.setMaxScore(0d);
				work.setMinScore(0d);
				work.setCurrScore(0d);
				work.setRanking(0);
			}

		}
		Collections.reverse(list);
//		TODO	分数排序
		return AjaxResult.success(list);
	}

}
