package com.goafanti.achievement.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.goafanti.achievement.bo.InputAchievement;
import com.goafanti.achievement.service.AchievementService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.constant.PageConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.dao.AchievementKeywordMapper;
import com.goafanti.common.dao.AchievementPublishMapper;
import com.goafanti.common.enums.AchievementAuditStatus;
import com.goafanti.common.enums.AchievementFields;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.model.Achievement;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.portal.bo.AchievementResultObject;

@RestController
@RequestMapping(value = "/api/user/achievement")
public class UserAchievementApiController extends CertifyApiController {
	@Resource
	private AchievementService		achievementService;
	@Autowired
	private AchievementKeywordMapper		achievementKeywordMapper;
	@Autowired
	private AchievementPublishMapper achievementPublishMapper;
	/**
	 * 成果需求匹配列表
	 */
	@RequestMapping(value = "/achievementDemand", method = RequestMethod.GET)
	public Result achievementDemand(String id) {
		Result res = new Result();
		res.setData(achievementService.selectAchievementDemandListByAchievementId(id));
		return res;
	}


	/**
	 * 成果撤消发布(下架)
	 */
	@RequestMapping(value = "/offShelf", method = RequestMethod.POST)
	public Result offShelf(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}

		Achievement a = achievementService.selectByPrimaryKey(id);
		if (null == a) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "成果ID"));
			return res;
		}
		if(a.getAuditStatus() != AchievementAuditStatus.AUDITED.getCode()) {
			res.getError().add(buildError(ErrorConstants.STATUS_ERROR,"","当前状态不可撤销发布"));
			return res;
		}


		res.setData(achievementService.updateReleaseStatus(a));
		return res;
	}

	/**
	 * 成果列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	private Result list(Integer auditStatus, String name, Integer dataCategory,
		 String startDate, String endDate,
		 Integer pageNo, Integer pageSize) {
		Result res = new Result();
		res.setData(achievementService.listMyAchievement(auditStatus, name, dataCategory,
				 startDate, endDate, pageNo, pageSize));
		return res;
	}

	/**
	 * 新增成果
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	private Result apply(@Valid InputAchievement ia, BindingResult bindingResult,
			@RequestParam(name = "keywords[]", required = false) String[] keywords,
			@RequestParam(name = "publishPages[]", required = false)  String[] publishPages) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					AchievementFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		res = disposeInputAchievement(res, ia, keywords,publishPages);
		if (!res.getError().isEmpty()) {
			return res;
		}

		if(TokenManager.getUserId()==null) {
			res.getError().add(buildError(ErrorConstants.NON_LOGIN, "", ""));return res;
		}
		Achievement a = new Achievement();
		BeanUtils.copyProperties(ia, a);
		a.setOwnerId(TokenManager.getUserId());
		a.setInfoSources(1);
		List<String> webPages = new ArrayList<String>();
		List<String> appPages = new ArrayList<String>();
		PageConstants.putAchievement(publishPages, webPages, appPages);
		achievementService.saveAchievement(a, keywords,webPages,appPages);
		return res;
	}

	@RequestMapping(value = "/achievementDetail",method=RequestMethod.GET)
	private Result Detail(String id) {
		Result result=new Result();
		if (StringUtils.isBlank(id)) {
			result.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return result;
		}
		
		AchievementResultObject achievementObjects=achievementService.getAchievementDetailById(id);
		List<String>keywords=achievementKeywordMapper.getKeywordsByAchievementId(id);
		List<String> publishPages=achievementPublishMapper.getPublishPagesById(id);
		achievementObjects.setKeywords(keywords);
		achievementObjects.setPublishPages(publishPages);
		result.setData(achievementObjects);
//		AchievementResultObject achievementResultObject=new AchievementResultObject()
		return result;
	}
	/**
	 * 个人成果详情详情
	 */
	@RequestMapping(value = "/userDetail", method = RequestMethod.GET)
	private Result userDetail(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}
		res.setData(achievementService.selectUserOwnerDetail(id));
		return res;
	}

	/**
	 * 组织用户成果详情详情
	 */
	@RequestMapping(value = "/orgDetail", method = RequestMethod.GET)
	private Result orgDetail(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}
		res.setData(achievementService.selectOrgOwnerDetail(id));
		return res;
	}

	/**
	 * 修改成果
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Result update(@Valid InputAchievement ia, BindingResult bindingResult,
			@RequestParam(name = "keywords[]", required = false) String[] keywords,
			@RequestParam(name = "publishPages[]", required = false)  String[] publishPages) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					AchievementFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(ia.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "需求ID"));
			return res;
		}

//		if (!AchievementAuditStatus.CREATE.getCode().equals(ia.getAuditStatus())
//				&& !AchievementAuditStatus.SUBMIT.getCode().equals(ia.getAuditStatus())
//				&& !AchievementAuditStatus.UNAUDITED.getCode().equals(ia.getAuditStatus())) {
//			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "当前状态无法提交审核！"));
//			return res;
//		}
		List<String> webPages = new ArrayList<String>();
		List<String> appPages = new ArrayList<String>();
		PageConstants.putAchievement(publishPages, webPages, appPages);
		res = disposeInputAchievement(res, ia, keywords,publishPages);
		if (!res.getError().isEmpty()) {
			return res;
		}
		if(webPages.size()==0 && appPages.size() == 0){

			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "页面参数错误","页面参数"));
			return res;
		}
		if(TokenManager.getUserId() ==null) {
			res.getError().add(buildError(ErrorConstants.NON_LOGIN, "", ""));return res;
		}
		Achievement a = new Achievement();
		BeanUtils.copyProperties(ia, a);
		a.setOwnerId(TokenManager.getUserId());
		res.setData(achievementService.updateAchievement(a, keywords, null,webPages,appPages));
		return res;
	}
	/**
	 * 刷新发布时间
	 * @param id
	 * @param auditStatus
	 * @return
	 */
	@RequestMapping(value = "/refreshPublish", method = RequestMethod.POST)
	public Result refreshPublish(String id,Integer auditStatus){
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}
		if (null == auditStatus) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "成果状态错误", "成果状态"));
			return res;
		}
		if (AchievementAuditStatus.AUDITED.getCode() != auditStatus) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "当前状态无法刷新发布，"));
			return res;
		}
		Achievement a = new Achievement();
		a.setId(id);
		a.setReleaseDate(new Date());
//		a.setAuditStatus(auditStatus);
		achievementService.updateByPrimaryKeySelective(a);
		return res;
	}
	
	/**
	 * 提交审核
	 * @param id
	 * @param auditStatus
	 * @return
	 */
	@RequestMapping(value = "/commit", method = RequestMethod.POST)
	public Result refreshAuditStatus(String id){
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}
		AchievementResultObject achievementResultObject=achievementService.getAchievementDetailById(id);
		if(achievementResultObject==null) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果ID", "成果ID"));
			return res;
		}
		if (AchievementAuditStatus.CREATE.getCode() != achievementResultObject.getAuditStatus() && AchievementAuditStatus.REVOKE.getCode()!=achievementResultObject.getAuditStatus()
				&&AchievementAuditStatus.UNAUDITED.getCode()!=achievementResultObject.getAuditStatus()) {
		res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "当前状态无法提交审核，"));
		return res;
	} 
		Achievement a = new Achievement();
		a.setId(id);
		a.setAuditStatus(AchievementAuditStatus.SUBMIT.getCode());
		achievementService.updateByPrimaryKeySelective(a);
		return res;
	}
	/**
	 * 下载文本文件
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public Result download(HttpServletResponse response, String id, String sign) {
		Result res = new Result();

		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技成果ID"));
			return res;
		}

		Achievement a = achievementService.selectByPrimaryKey(id);
		if (null == a) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技成果ID"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		/*if (attachmentType == AttachmentType.ACHIEVEMENT_MATURITY_TEXT_FILE) {
			downloadUnPrivateFile(response, a.getMaturityTextFileDownloadFileName(), a.getMaturityTextFileUrl());
		} else if (attachmentType == AttachmentType.ACHIEVEMENT_TECH_PLAN) {
			downloadUnPrivateFile(response, a.getTechPlanDownloadFileName(), a.getTechPlanUrl());
		} else if (attachmentType == AttachmentType.ACHIEVEMENT_BUSINESS_PLAN) {
			downloadUnPrivateFile(response, a.getBusinessPlanDownloadFileName(), a.getBusinessPlanUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}*/

		return res;
	}

	/**
	 * 文本文件上传
	 */
	@RequestMapping(value = "/uploadTextFile", method = RequestMethod.POST)
	public Result uploadTextFile(HttpServletRequest req, String sign) {
		Result res = new Result();

		AttachmentType attachmentType = AttachmentType.getField(sign);

		/*if (attachmentType == AttachmentType.ACHIEVEMENT_MATURITY_TEXT_FILE
				|| attachmentType == AttachmentType.ACHIEVEMENT_TECH_PLAN
				|| attachmentType == AttachmentType.ACHIEVEMENT_BUSINESS_PLAN) {
			res.setData(handleFiles(res, "/achievement/", false, req, sign, "achievement"));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}*/
		return res;
	}

	/**
	 * 图片上传
	 */
	@RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
	public Result uploadPicture(HttpServletRequest req, String sign) {
		Result res = new Result();

		AttachmentType attachmentType = AttachmentType.getField(sign);

		if (attachmentType == AttachmentType.ACHIEVEMENT_PICTURE
				) {
			res.setData(handleFiles(res, "/achievement/", false, req, sign, "achievement"));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	private Result delete(@RequestParam(name = "ids[]", required = false) String[] ids) {
		Result res = new Result();
		if (ids == null || ids.length != 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
		} else {
			/*List<AchievementOrder> list = achievementOrderService.selectAchievementOrderByAchievementId(ids[0]);
			for (AchievementOrder order : list) {
				if (!AchievementOrderStatus.UNPAYED.getCode().equals(order.getStatus())) {
					res.getError().add(buildError("", "当前科技成果有订单，无法删除！"));
					return res;
				}
			}*/
			res.setData(achievementService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	private Result disposeInputAchievement(Result res, InputAchievement ia, String[] keywords,String[] publishPages) {
		if (StringUtils.isBlank(ia.getName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到成果名称", "成果名称"));
			return res;
		}

		if (null == ia.getCategory()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到数据类别", "数据类别"));
			return res;
		}

		if (StringUtils.isBlank(ia.getKeyword())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}

		if (null == keywords || keywords.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到关键词", "关键词"));
			return res;
		}
		
	
		for (int i = 0; i < keywords.length; i++) {
			if (AFTConstants.KEYWORDLENTH < keywords[i].length()) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "关键词长度"));
				return res;
			}
		}
		return res;
	}

}
