package com.yizhi.application.assignment.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.assignment.application.feign.AssignmentStudentClient;
import com.yizhi.assignment.application.vo.apivo.*;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.course.application.feign.LessonClient;
import com.yizhi.course.application.vo.CourseStudentListVo;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "学员端-作业接口")
@RestController
@RequestMapping("/student/assignment")
public class StudentAssignmentController {
	
	 private static final Logger logger = LoggerFactory.getLogger(StudentAssignmentController.class);

	@Autowired
	private AssignmentStudentClient assignmentStudentClient;
	@Autowired
	private LessonClient lessonClient;
	@Autowired
	private AssignmentClient assignmentClient;
	
	@GetMapping("/my/answer/zip")
	public Response<String> getStudentAnswerZipByAnswerId(@RequestParam(name="assignmentId")Long assignmentId,@RequestParam(name="answerId")Long answerId) {
		logger.info("进入中台");
		System.out.println("中台进入");
		
		String url=null;
		try {
			url=assignmentStudentClient.getStudentAnswerZipByAnswerId(assignmentId, answerId);
			return Response.ok(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}
		
			

	@GetMapping("/my/list")
	@ApiOperation(value = "分页查询作业列表", notes = "分页查询作业列表",response= ApiAssignmentListResultVO.class)
	public Response<ApiAssignmentListResultVO> list(
			@ApiParam(name = "type", value = "类型（1,进行中，2：已结束）", required = true) @RequestParam(name = "type", defaultValue = "1") int type,
			@ApiParam(name = "pageNo", value = "要跳转的页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") int pageNo,
			@ApiParam(name = "pageSize", value = "每页条数，默认：10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
		try {
			Long companyId= ContextHolder.get().getCompanyId();
			Long siteId = ContextHolder.get().getSiteId();
			Long accountId = ContextHolder.get().getAccountId();
			List<Long> relationIds = ContextHolder.get().getRelationIds();
			Page<ApiAssignmentListResultVO> page = new Page<ApiAssignmentListResultVO>();
			page = assignmentStudentClient.list(type, pageNo, pageSize, accountId, relationIds, companyId,siteId);
			if (page != null) {
				List<ApiAssignmentListResultVO> list = page.getRecords();
				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("current", pageNo);
				map.put("size", pageSize);
				map.put("total", page.getTotal());
				Pair<List<ApiAssignmentListResultVO>, Map<String, Integer>> pair = new MutablePair<List<ApiAssignmentListResultVO>, Map<String, Integer>>(
						list, map);
				return Response.ok(pair);
			} else {
				return Response.ok(ReturnCode.RESOURCE_NOT_FOUND);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@GetMapping("/my/list/search")
	@ApiOperation(value = "根据关键字查询", notes = "根据关键字查询",response=ApiAssignmentListResultVO.class)
	public Response<ApiAssignmentListResultVO> listSearch(
			@ApiParam(name = "name", value = "关键字", required = false) @RequestParam(name = "name", required = false) String name,
			@ApiParam(name = "pageNo", value = "要跳转的页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") int pageNo,
			@ApiParam(name = "pageSize", value = "每页条数，默认：10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
		try {
			/*
			 * Long siteId=3L; Long accountId=1989311074940907520L; List<Long>
			 * relationIds=new ArrayList<Long>(); relationIds.add(1989311074940907520L);
			 */
			Long accountId = ContextHolder.get().getAccountId();
			List<Long> relationIds = ContextHolder.get().getRelationIds();
			Long siteId = ContextHolder.get().getSiteId();
			Page<ApiAssignmentListResultVO> page = assignmentStudentClient.listSearch(name, pageNo, pageSize, accountId,
					relationIds, siteId);
			if (page != null) {
				List<ApiAssignmentListResultVO> list = page.getRecords();
				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("current", pageNo);
				map.put("size", pageSize);
				map.put("total", page.getTotal());
				Pair<List<ApiAssignmentListResultVO>, Map<String, Integer>> pair = new MutablePair<List<ApiAssignmentListResultVO>, Map<String, Integer>>(
						list, map);
				return Response.ok(pair);
			} else {
				return Response.ok(ReturnCode.RESOURCE_NOT_FOUND);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}


	@GetMapping("/my/answer/list")
	@ApiOperation(value="作业列表",notes="作业列表",response= ApiAssignmentAnswerResultVo.class)
	public Response<ApiAssignmentAnswerResultVo> answerList(@ApiParam(name = "assignmentId", value = "作业id", required = true)@RequestParam(name = "assignmentId") Long assignmentId) {
		Long accountId = ContextHolder.get().getAccountId();
		try {
			ApiAssignmentAnswerResultVo apiAssignmentAnswerResultVo = assignmentStudentClient.answerList(assignmentId, accountId);
			return Response.ok(apiAssignmentAnswerResultVo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());

		}

	}

	@GetMapping("/my/getAssignment")
	@ApiOperation(value = "查看作业的信息--提交页面", notes = "查看作业的信息--提交页面", response = ApiAssignmentVO.class)
	public Response<ApiAssignmentVO> getAssignment(@ApiParam(name = "assignmentId", value = "作业id", required = true) @RequestParam(name = "assignmentId") Long assignmentId) {
		Long accountId = ContextHolder.get().getAccountId();
		try {
			ApiAssignmentVO vo = assignmentStudentClient.getAssignment(assignmentId, accountId);
			if (vo != null) {
				return Response.ok(vo);
			} else {
				return Response.ok(ReturnCode.RESOURCE_NOT_FOUND);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}


	@GetMapping("/my/toAssignment")
	@ApiOperation(value = "查看某一份作业细节", notes = "查看某一份作业细节", response = ApiAssignmentDetailsVo.class)
	public Response<ApiAssignmentDetailsVo> toAssignment(@ApiParam(name = "assignmentId", value = "作业id", required = true) @RequestParam(name = "assignmentId") Long assignmentId,
														 @ApiParam(name = "answerId", value = "答案id", required = true) @RequestParam(name = "answerId") Long answerId) {
		Long accountId = ContextHolder.get().getAccountId();
		try {
			ApiAssignmentDetailsVo vo = assignmentStudentClient.toAssignment(assignmentId, answerId, accountId);
			if (vo != null) {
				return Response.ok(vo);
			} else {
				return Response.ok(ReturnCode.RESOURCE_NOT_FOUND);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}


	@PostMapping("/my/submit")
	@ApiOperation(value = "作业提交", notes = "作业提交")
	public Response<String> submit(@RequestBody ApiAssignmentAswerVO assignmentAswerVO) {
		try {

			assignmentAswerVO.setAccountId(ContextHolder.get().getAccountId());
			assignmentAswerVO.setAccountName(ContextHolder.get().getAccountName());
			assignmentAswerVO.setRealName(ContextHolder.get().getAccountFullName());
			assignmentAswerVO.setCompanyId(ContextHolder.get().getCompanyId());
			assignmentAswerVO.setSiteId(ContextHolder.get().getSiteId());
			assignmentAswerVO.setOrgId(ContextHolder.get().getOrgId());


			/**
			 * 防止pc和微信同时提交作业0 可以提交  1没有提交次数 2已经逾期
			 */

			Integer isCanSubmit=assignmentStudentClient.canSubmit(assignmentAswerVO);
			if(isCanSubmit==1) {
				return Response.fail("提交次数达到上限");
			}
			
			if(isCanSubmit==2) {
				return Response.fail("该作业已逾期");
			}

			Boolean isSubmit = assignmentStudentClient.submit(assignmentAswerVO);
			if (isSubmit) {
				return Response.ok(ReturnCode.SUCCESS);
			} else {
				return  Response.fail(ReturnCode.SAVE_FAIL.getCode(),ReturnCode.SAVE_FAIL.getMsg());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@GetMapping("/my/suggestion/get")
	@ApiOperation(value = "查看作业评阅", notes = "查看作业评阅", response = ApiSuggestionVo.class)
	public Response<ApiSuggestionVo> getSuggesstion(
			@ApiParam(name = "assignmentId", value = "作业id", required = true) @RequestParam(name = "assignmentId") Long assignmentId) {
		try {
			Long accountId = ContextHolder.get().getAccountId();
			ApiSuggestionVo vo = assignmentStudentClient.getSuggesstion(assignmentId, accountId);
			if (vo != null) {
				return Response.ok(vo);
			} else {
				return Response.ok(ReturnCode.RESOURCE_NOT_FOUND);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@GetMapping("/my/pass/list")
	@ApiModelProperty(value = "查看已通过的做课", notes = "查看已通过的做课")
	public Response<CourseStudentListVo> getPassMaterialList(
			@ApiParam(name = "name", value = "关键字", required = false) @RequestParam(name = "name", required = false) String name,
			@ApiParam(name = "pageNo", value = "要跳转的页数", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") int pageNo,
			@ApiParam(name = "pageSize", value = "每页条数，默认：10", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
		try {
			Long accountId = ContextHolder.get().getAccountId();
			Page<CourseStudentListVo> page = lessonClient.getPassMaterialList(name, accountId, pageNo, pageSize);
			if (page != null) {
				List<CourseStudentListVo> list = page.getRecords();
				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("pageNo", pageNo);
				map.put("pageSize", pageSize);
				map.put("total", page.getTotal());
				Pair<List<CourseStudentListVo>, Map<String, Integer>> pair = new MutablePair<List<CourseStudentListVo>, Map<String, Integer>>(
						list, map);
				return Response.ok(pair);
			} else {
				return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}
	}

	@GetMapping("/pc/getAssignment")
	@ApiOperation(value = "Pc端查看作业的信息--提交页面", notes = "Pc端查看作业的信息--提交页面", response = ApiAssignmentVO.class)
	public Response<ApiAssignmentVO> pcGetAssignment(@ApiParam(name = "assignmentId", value = "作业id", required = true) @RequestParam(name = "assignmentId") Long assignmentId) {
		Long accountId = ContextHolder.get().getAccountId();
		try {
			ApiAssignmentVO vo = assignmentStudentClient.getAssignment(assignmentId, accountId);
			if (vo != null) {
				return Response.ok(vo);
			} else {
				return Response.fail(Constants.ASSIGNMENT_MSG_RESOURSE_NOT_EXIST.getCode().toString(), Constants.ASSIGNMENT_MSG_RESOURSE_NOT_EXIST.getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL.getCode().toString(), Constants.MSG_BIZ_FAIL.getName());
		}
	}

	@PostMapping("/pc/submit")
	@ApiOperation(value = "PC端作业提交", notes = "作业提交")
	public Response<String> pcSubmit(@ApiParam(value = "assignmentId、source默认为1-- 必传") @RequestBody ApiAssignmentAswerVO assignmentAswerVO) {

		assignmentAswerVO.setAccountId(ContextHolder.get().getAccountId());
		assignmentAswerVO.setAccountName(ContextHolder.get().getAccountName());
		assignmentAswerVO.setRealName(ContextHolder.get().getAccountFullName());
		assignmentAswerVO.setCompanyId(ContextHolder.get().getCompanyId());
		assignmentAswerVO.setSiteId(ContextHolder.get().getSiteId());
		assignmentAswerVO.setOrgId(ContextHolder.get().getOrgId());
		Integer isCanSubmit = assignmentStudentClient.canSubmit(assignmentAswerVO);
		if (isCanSubmit == 1) {
			return Response.fail(Constants.ASSIGNMENT_MSG_EXCEEDING_NUMBER_SUBMIT.getCode().toString(), Constants.ASSIGNMENT_MSG_EXCEEDING_NUMBER_SUBMIT.getName());
		}
		if (isCanSubmit == 2) {
			return Response.fail(Constants.ASSIGNMENT_MSG_END.getCode().toString(), Constants.ASSIGNMENT_MSG_END.getName());
		}

		if (StringUtils.isEmpty(assignmentAswerVO.getContent()) && null == assignmentAswerVO.getFileVos()) {
			//提交内容不能为空
			return Response.fail(Constants.ASSIGNMENT_MSG_SUBMIT_NULL.getCode().toString(), Constants.ASSIGNMENT_MSG_SUBMIT_NULL.getName());
		}

		Boolean isSubmit = assignmentStudentClient.submit(assignmentAswerVO);
		if (isSubmit) {
			return Response.ok(Constants.MSG_SUCCESS.getName());
		} else {
			return Response.fail(Constants.MSG_BIZ_FAIL.getCode().toString(), Constants.MSG_BIZ_FAIL.getName());
		}
	}

	@GetMapping("/pc/answer/list")
	@ApiOperation(value = "Pc端提交作业记录", notes = "Pc端提交作业记录", response = ApiAssignmentAnswerResultVo.class)
	public Response<ApiAssignmentAnswerResultVo> pcAnswerList(@ApiParam(name = "assignmentId", value = "作业id", required = true) @RequestParam(name = "assignmentId") Long assignmentId) {
		Long accountId = ContextHolder.get().getAccountId();
		try {
			ApiAssignmentAnswerResultVo apiAssignmentAnswerResultVo = assignmentStudentClient.answerList(assignmentId, accountId);
			return Response.ok(apiAssignmentAnswerResultVo);
		} catch (Exception e) {
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL.getCode().toString(), Constants.MSG_BIZ_FAIL.getName());
		}
	}

	@GetMapping("/pc/getAssignmentDetail")
	@ApiOperation(value = "查看某一份作业答案细节", notes = "查看某一份作业答案细节", response = ApiAssignmentDetailsVo.class)
	public Response<ApiAssignmentDetailsVo> pcGetAssignmentDetail(@ApiParam(name = "assignmentId", value = "作业id", required = true) @RequestParam(name = "assignmentId") Long assignmentId,
																  @ApiParam(name = "answerId", value = "答案id", required = true) @RequestParam(name = "answerId") Long answerId) {
		Long accountId = ContextHolder.get().getAccountId();
		try {
			ApiAssignmentDetailsVo vo = assignmentStudentClient.toAssignment(assignmentId, answerId, accountId);
			if (vo != null) {
				return Response.ok(vo);
			} else {
				return Response.fail(Constants.ASSIGNMENT_MSG_RESOURSE_NOT_EXIST.getCode().toString(), Constants.ASSIGNMENT_MSG_RESOURSE_NOT_EXIST.getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL.getCode().toString(), Constants.MSG_BIZ_FAIL.getName());
		}
	}

	@GetMapping("/pc/hasEnded")
	@ApiOperation(value = "全局搜索进入作业时，作业逾期需要提示")
	public Response hasEnded(@RequestParam("assignmentId") @ApiParam(value = "assignmentId") Long assignmentId) {

		ApiAssignmentAswerVO assignmentAswerVO = new ApiAssignmentAswerVO();
		assignmentAswerVO.setAccountId(ContextHolder.get().getAccountId());
		assignmentAswerVO.setAssignmentId(assignmentId);

		Integer isCanSubmit = assignmentStudentClient.canSubmit(assignmentAswerVO);
//		if (isCanSubmit == 1) {
//			return Response.fail(Constants.ASSIGNMENT_MSG_EXCEEDING_NUMBER_SUBMIT.getCode().toString(), Constants.ASSIGNMENT_MSG_EXCEEDING_NUMBER_SUBMIT.getName());
//		}
		if (isCanSubmit == 2) {
			return Response.fail(Constants.ASSIGNMENT_MSG_END.getCode().toString(), Constants.ASSIGNMENT_MSG_END.getName());//该作业已逾期
		}
		return Response.ok();
	}
}