package com.goafanti.techproject.controller;

import java.text.ParseException;
import java.util.Iterator;
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.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.CopyrightFields;
import com.goafanti.common.enums.TechProjectFields;
import com.goafanti.common.enums.TechProjectStatus;
import com.goafanti.common.model.TechProject;
import com.goafanti.common.model.TechProjectLog;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.techproject.bo.InputTechProject;
import com.goafanti.techproject.bo.TechProjectDetailBo;
import com.goafanti.techproject.service.TechProjectLogService;
import com.goafanti.techproject.service.TechProjectService;
import com.goafanti.techproject.service.TechWebsiteService;

@Controller
@RequestMapping(value = "/api/user/techproject")
public class UserTechProjectApiController extends CertifyApiController {
	@Resource
	private TechProjectService		techProjectService;
	@Resource
	private TechWebsiteService		techWebsiteService;
	@Resource
	private TechProjectLogService	techProjectLogService;

	/**
	 * 获取科技部门
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getDepartment", method = RequestMethod.GET)
	public Result getDepartment() {
		Result res = new Result();
		res.setData(techWebsiteService.getDepartment(TokenManager.getUserId()));
		return res;
	}

	/**
	 * 科技项目申报列表
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/listClientTechProject", method = RequestMethod.GET)
	public Result listClientTechProject(String pageNo, String pageSize) {
		Result res = new Result();

		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(techProjectService.listClientTechProject(TokenManager.getUserId(), pNo, pSize));
		return res;
	}

	/**
	 * 科技项目申报
	 * 
	 * @return
	 */
	@RequestMapping(value = "/applyTechProject", method = RequestMethod.POST)
	public Result applyTechProject(@Valid InputTechProject techProject, BindingResult bindingResult) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					CopyrightFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		TechProject tp = new TechProject();
		BeanUtils.copyProperties(techProject, tp);
		tp.setUid(TokenManager.getUserId());
		techProjectService.insertTechProject(tp, curUser.getAid());
		return res;
	}

	/**
	 * 科技项目申报详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/techProjectDetial", method = RequestMethod.POST)
	public Result techProjectDetial(String pid) {
		Result res = new Result();
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "科技项目ID"));
		} else {
			TechProjectDetailBo tpd = techProjectService.selectProjectDetail(pid);
			if (null != tpd.getUid() && tpd.getUid().equals(TokenManager.getUserId())) {
				res.setData(tpd);
			} else {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技项目ID"));
			}
		}
		return res;
	}

	/**
	 * 科技项目状态流转
	 * 
	 * @param pid
	 * @return
	 */
	@RequestMapping(value = "/techProjectLog", method = RequestMethod.POST)
	public Result techProjectLog(String pid) {
		Result res = new Result();
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "科技项目ID"));
			return res;
		}
		TechProject tp = techProjectService.selectByPrimaryKey(pid);
		if (StringUtils.isNotBlank(tp.getUid()) && tp.getUid().equals(TokenManager.getUserId())) {
			List<TechProjectLog> list = techProjectLogService.selectTechProjectLogByPid(pid);
			for (Iterator<TechProjectLog> log = list.iterator() ; log.hasNext();) {
				Integer state = log.next().getState();
				if (TechProjectStatus.getStatus(state) == TechProjectStatus.SIGN
						|| TechProjectStatus.getStatus(state) == TechProjectStatus.CIRCULATION
						|| TechProjectStatus.getStatus(state) == TechProjectStatus.SETTLEMENT) {
					log.remove();
				}
			}
			
			res.setData(list);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技项目id"));
		}
		return res;
	}
	

	/**
	 * update科技项目
	 * 
	 * @param t
	 * @param l
	 * @param recordTimeFormattedDate
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/updateTechProject", method = RequestMethod.POST)
	public Result updateTechProject(@Valid InputTechProject techProject, BindingResult bindingResult) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					TechProjectFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		if (StringUtils.isBlank(techProject.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到科技申报项目", "科技项目申报ID"));
			return res;
		}

		TechProject t = techProjectService.selectByPrimaryKey(techProject.getId());
		
		if (TechProjectStatus.CALLBACK.getCode() == t.getState()){
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前记录已退单，无法修改！"));
			return res;
		}
		
		if (TechProjectStatus.SETTLEMENT.getCode() == t.getState()){
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前记录已结款，无法修改！"));
			return res;
		}
		
		if (null != t.getUid() && t.getUid().equals(curUser.getId())) {
			TechProject tp = new TechProject();
			BeanUtils.copyProperties(techProject, tp);
			res.setData(techProjectService.updateTechProject(tp, null, null));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到科技申报项目", "科技项目申报"));
		}
		return res;
	}

	/**
	 * 科技项目申报材料上传
	 * 
	 * @param req
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result cognizanceFile(HttpServletRequest req, String id, String sign) {
		Result res = new Result();
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到科技申报项目", "科技项目申报ID"));
			return res;
		}

		TechProject t = techProjectService.selectByPrimaryKey(id);
		if (null == t) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "找不到申报项目", "科技项目申报"));
			return res;
		}
		
		if (TechProjectStatus.CALLBACK.getCode() == t.getState()){
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前记录已退单，无法修改！"));
			return res;
		}
		
		if (TechProjectStatus.SETTLEMENT.getCode() == t.getState()){
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前记录已结款，无法修改！"));
			return res;
		}
		
		AttachmentType attachmentType = AttachmentType.getField(sign);
		
		if (attachmentType == AttachmentType.TECH_PROJECT){
			res.setData(handleFiles(res, "/techProject/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 科技项目资料下载
	 * 
	 * @param id
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public Result download(String id, HttpServletResponse response) {
		Result res = new Result();
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技项目ID"));
			return res;
		}

		TechProject t = techProjectService.selectByPrimaryKey(id);
		if (null == t || !curUser.getId().equals(t.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技项目ID"));
			return res;
		}

		downloadFile(response, t.getApprovalDownloadFileName(), t.getApprovalUrl());
		return res;
	}

}
