package cn.com.qmth.examcloud.core.questions.api.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
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 cn.com.qmth.examcloud.core.questions.service.CopyDataService;
import cn.com.qmth.examcloud.web.redis.RedisClient;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import cn.com.qmth.examcloud.web.support.ServletUtil;

@RestController
@RequestMapping("${api_cqb}/copy")
public class CopyDataController extends ControllerSupport {
	private static int cacheLockTimeout = 60 * 10;
	private static String withoutReduplicateLock = "$_COPY_QUESTION_DATA_NO_REDUPLICATE_LOCK";
	@Autowired
	private CopyDataService copyDataService;
	@Autowired
	private RedisClient redisClient;
//
//	//西交大数据复制
//	@GetMapping("data")
//	public void copyData(HttpServletResponse response) {
//		Long fromRootOrgId = 371L;
//		Long toRootOrgId = 21595L;
////		Long fromRootOrgId = 141L;
////		Long toRootOrgId = 150L;
//		User user = getAccessUser();
//		if (!user.getRootOrgId().equals(toRootOrgId)) {
//			ServletUtil.returnJson("请求失败，没有权限", response);
//			return;
//		}
//		String cacheLock = "$_COPY_QUESTION_DATA_LOCK";
//		Boolean lock = redisClient.setIfAbsent(cacheLock, cacheLock, cacheLockTimeout);
//		if (!lock) {
//			ServletUtil.returnJson("请求失败，正在处理数据", response);
//			return;
//		}
//		copyDataService.copyData(getAccessUser(), fromRootOrgId, toRootOrgId);
//	}
	
	
	//试题去重后复制
	@GetMapping("noreduplicate")
	public void copyNoReduplicate(HttpServletResponse response,@RequestParam String batch) {
		Boolean lock = redisClient.setIfAbsent(withoutReduplicateLock, withoutReduplicateLock, cacheLockTimeout);
		if (!lock) {
			ServletUtil.returnJson("请求失败，正在处理数据", response);
			return;
		}
		copyDataService.copyNoReduplicate(getAccessUser(), batch);
		ServletUtil.returnJson("请求成功", response);
	}
	
	@GetMapping("noreduplicate/status")
	public void copyNoReduplicateStatus(HttpServletResponse response) {
		String lock = redisClient.get(withoutReduplicateLock,String.class);
		if (lock!=null) {
			ServletUtil.returnJson("正在处理数据", response);
		}else {
			ServletUtil.returnJson("处理数据结束", response);
		}
	}

}
