package com.goafanti.cognizance.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.goafanti.cognizance.bo.ActivityNumberBo;
import com.goafanti.cognizance.bo.AnnualReportBo;
import com.goafanti.cognizance.bo.CognizanceDetailBo;
import com.goafanti.cognizance.bo.InputApplyCognizance;
import com.goafanti.cognizance.bo.InputOrgActivity;
import com.goafanti.cognizance.bo.InputOrgActivityCost;
import com.goafanti.cognizance.bo.InputOrgAnnualReport;
import com.goafanti.cognizance.bo.InputOrgCognizance;
import com.goafanti.cognizance.bo.InputOrgFinance;
import com.goafanti.cognizance.bo.InputOrgHonorDatum;
import com.goafanti.cognizance.bo.InputOrgIntellectualProperty;
import com.goafanti.cognizance.bo.InputOrgRatepay;
import com.goafanti.cognizance.bo.InputOrgStandard;
import com.goafanti.cognizance.bo.InputOrgTechAchievement;
import com.goafanti.cognizance.bo.InputOrgTechCenter;
import com.goafanti.cognizance.bo.InputOrgTechCenterDetail;
import com.goafanti.cognizance.bo.InputOrgTechProduct;
import com.goafanti.cognizance.bo.OrgIntellectualPropertyDetailBo;
import com.goafanti.cognizance.service.OrgActivityCostService;
import com.goafanti.cognizance.service.OrgActivityService;
import com.goafanti.cognizance.service.OrgAnnualReportService;
import com.goafanti.cognizance.service.OrgCognizanceLogService;
import com.goafanti.cognizance.service.OrgCognizanceService;
import com.goafanti.cognizance.service.OrgFinanceService;
import com.goafanti.cognizance.service.OrgHonorDatumService;
import com.goafanti.cognizance.service.OrgIntellectualPropertyService;
import com.goafanti.cognizance.service.OrgRatepayService;
import com.goafanti.cognizance.service.OrgStandardService;
import com.goafanti.cognizance.service.OrgTechAchievementService;
import com.goafanti.cognizance.service.OrgTechCenterDetailService;
import com.goafanti.cognizance.service.OrgTechCenterService;
import com.goafanti.cognizance.service.OrgTechProductService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.CognizanceApplyFields;
import com.goafanti.common.enums.DeleteStatus;
import com.goafanti.common.enums.FinanceRatepayFields;
import com.goafanti.common.enums.IntellectualPropertyType;
import com.goafanti.common.enums.OrgActivityFields;
import com.goafanti.common.enums.OrgAnnualReportFields;
import com.goafanti.common.enums.OrgCognizanceFields;
import com.goafanti.common.enums.OrgCognizanceStatus;
import com.goafanti.common.enums.OrgFinanceFields;
import com.goafanti.common.enums.OrgHonorDatumFields;
import com.goafanti.common.enums.OrgIntellectualPropertyFields;
import com.goafanti.common.enums.OrgRatepayFields;
import com.goafanti.common.enums.OrgStandardFields;
import com.goafanti.common.enums.OrgTechAchievementFields;
import com.goafanti.common.enums.OrgTechCenterDetailFields;
import com.goafanti.common.enums.OrgTechCenterFields;
import com.goafanti.common.enums.OrgTechProductFields;
import com.goafanti.common.model.OrgActivity;
import com.goafanti.common.model.OrgActivityCost;
import com.goafanti.common.model.OrgAnnualReport;
import com.goafanti.common.model.OrgCognizance;
import com.goafanti.common.model.OrgCognizanceLog;
import com.goafanti.common.model.OrgFinance;
import com.goafanti.common.model.OrgHonorDatum;
import com.goafanti.common.model.OrgHumanResource;
import com.goafanti.common.model.OrgIntellectualProperty;
import com.goafanti.common.model.OrgRatepay;
import com.goafanti.common.model.OrgStandard;
import com.goafanti.common.model.OrgTechAchievement;
import com.goafanti.common.model.OrgTechCenter;
import com.goafanti.common.model.OrgTechCenterDetail;
import com.goafanti.common.model.OrgTechProduct;
import com.goafanti.common.model.PatentInfo;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.FileUtils;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.copyright.bo.CopyrightInfoDetail;
import com.goafanti.copyright.service.CopyrightInfoService;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.patent.service.PatentInfoService;
import com.goafanti.user.service.OrgHumanResourceService;
import com.goafanti.user.service.OrganizationIdentityService;
import com.goafanti.user.service.UserService;

@Controller
@RequestMapping(value = "/api/user/cognizance")
public class UserCognizanceApiController extends CertifyApiController {
	@Resource
	private UserService						userService;
	@Resource
	private OrgStandardService				orgStandardService;
	@Resource
	private OrgActivityService				orgActivityService;
	@Resource
	private OrgIntellectualPropertyService	orgIntellectualPropertyService;
	@Resource
	private OrganizationIdentityService		organizationIdentityService;
	@Resource
	private OrgTechProductService			orgTechProductService;
	@Resource
	private OrgActivityCostService			orgActivityCostService;
	@Resource
	private OrgRatepayService				orgRatepayService;
	@Resource
	private OrgFinanceService				orgFinanceService;
	@Resource
	private OrgTechAchievementService		orgTechAchievementService;
	@Resource
	private OrgHonorDatumService			orgHonorDatumService;
	@Resource
	private OrgTechCenterService			orgTechCenterService;
	@Resource
	private OrgTechCenterDetailService		orgTechCenterDetailService;
	@Resource
	private OrgCognizanceService			orgCognizanceService;
	@Resource
	private OrgAnnualReportService			orgAnnualReportService;
	@Resource
	private OrgCognizanceLogService			orgCognizanceLogService;
	@Resource
	private OrgHumanResourceService			orgHumanResourceService;
	@Resource
	private PatentInfoService				patentInfoService;
	@Resource
	private CopyrightInfoService			copyrightInfoService;

	/**
	 * 研发活动详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/activityDetail", method = RequestMethod.GET)
	public Result activityDetail(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "研发活动id"));
			return res;
		}
		Calendar a = Calendar.getInstance();
		res.setData(orgActivityService.selectDetailByIdAndYear(id, a.get(Calendar.YEAR) - 1));
		return res;

	}

	/**
	 * 财务报表详情（获取同年度纳税申报表重复数据）
	 * 
	 * @return
	 */
	@RequestMapping(value = "/financeDetail", method = RequestMethod.GET)
	public Result financeDetail(Integer year) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (null == year) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到年份", "年份"));
			return res;
		}
		OrgRatepay ratepay = orgRatepayService.selectRatepayByUidAndYear(TokenManager.getUserId(), year);
		if (null != ratepay) {
			Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
			map.put(FinanceRatepayFields.GROSSPROFIT.getCode(), ratepay.getGrossProfit());
			map.put(FinanceRatepayFields.MANAGEMENTCOST.getCode(), ratepay.getManagementCost());
			map.put(FinanceRatepayFields.OPERATINGPROFIT.getCode(), ratepay.getOperatingProfit());
			map.put(FinanceRatepayFields.RESEARCHCOST.getCode(), ratepay.getResearchCost());
			res.setData(map);
		}
		return res;
	}

	/**
	 * 企业纳税信息详情(获取同年度财务报表重复数据)
	 * 
	 * @param uid
	 * @param year
	 * @return
	 */
	@RequestMapping(value = "/ratepayDetail", method = RequestMethod.GET)
	public Result ratepayDetail(Integer year) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (null == year) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到年份", "年份"));
			return res;
		}
		OrgFinance of = orgFinanceService.selectFinanceByUidAndYear(TokenManager.getUserId(), year);
		if (null != of) {
			Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
			map.put(FinanceRatepayFields.GROSSPROFIT.getCode(), of.getGrossProfit());
			map.put(FinanceRatepayFields.MANAGEMENTCOST.getCode(), of.getManagementCost());
			map.put(FinanceRatepayFields.OPERATINGPROFIT.getCode(), of.getOperatingProfit());
			map.put(FinanceRatepayFields.RESEARCHCOST.getCode(), of.getResearchCost());
			res.setData(map);
		}
		return res;
	}

	/**
	 * 知识产权详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/intellectualDetail", method = RequestMethod.GET)
	public Result intellectualDetail(String id, Integer type) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "知识产权ID"));
			return res;
		}

		if (null == type) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "知识产权TYPE"));
			return res;
		}
		OrgIntellectualProperty oip = orgIntellectualPropertyService.selectByPrimaryKey(id);
		if (null == oip) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权ID"));
			return res;
		}
		if (IntellectualPropertyType.PATENT.getCode() == type) {
			res.setData(orgIntellectualPropertyService.selectPatentTypeDetail(id));
		} else if (IntellectualPropertyType.COPYRIGHT.getCode() == type) {
			res.setData(orgIntellectualPropertyService.selectCopyrightTypeDetail(id));
		} else if (IntellectualPropertyType.COMMON.getCode() == type) {
			OrgIntellectualPropertyDetailBo oipdb = new OrgIntellectualPropertyDetailBo();
			BeanUtils.copyProperties(oip, oipdb);
			res.setData(oipdb);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权TYPE"));
		}
		return res;
	}

	/**
	 * 知识产权稿件下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadManuscript", method = RequestMethod.GET)
	public Result downloadManuscript(HttpServletResponse response, String sign, String id, Integer type) {
		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;
		}

		if (null == type) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "知识产权TYPE"));
			return res;
		}

		OrgIntellectualProperty olp = orgIntellectualPropertyService.selectByPrimaryKey(id);
		if (olp == null) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权ID"));
			return res;
		}

		String fileName = null;
		String downloadUrl = null;
		if (IntellectualPropertyType.PATENT.getCode() == type) {
			PatentInfo pi = patentInfoService.selectByPrimaryKey(olp.getPid());
			if (null == pi) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权ID及TYPE"));
				return res;
			}
			fileName = pi.getPatentWritingDownloadFileName();
			downloadUrl = pi.getPatentWritingUrl();
		} else if (IntellectualPropertyType.COPYRIGHT.getCode() == type) {
			CopyrightInfoDetail ci = copyrightInfoService.findByPrimaryKey(olp.getPid());
			if (null == ci) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权ID及TYPE"));
				return res;
			}
			fileName = ci.getApplicationUrlDownloadFileName();
			downloadUrl = ci.getApplicationUrl();
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权TYPE"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.MANUSCRIPT) {
			downloadFile(response, fileName, downloadUrl);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 删除知识产权记录
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteIntellectual", method = RequestMethod.POST)
	public Result deleteIntellectual(@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 {
			res.setData(orgIntellectualPropertyService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除标准制定情况记录
	 * 
	 * @param id
	 *            记录id
	 * @return
	 */
	@RequestMapping(value = "/deleteStandard", method = RequestMethod.POST)
	public Result deleteStandard(@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 {
			res.setData(orgStandardService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除企业研究开发活动情况
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteActivity", method = RequestMethod.POST)
	public Result deleteActivity(@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 {
			res.setData(orgActivityService.deleteByPrimaryKey(Arrays.asList(ids)));
			orgActivityCostService.deleteByAid(Arrays.asList(ids));
		}
		return res;
	}

	/**
	 * 删除企业年度研究开发费用结构明细记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteActivityCost", method = RequestMethod.POST)
	public Result deleteActivityCost(@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 {
			res.setData(orgActivityCostService.batchDeleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除技术中心明细
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteOrgTechCenterDetail", method = RequestMethod.POST)
	public Result deleteOrgTechCenterDetail(@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 {
			res.setData(orgTechCenterDetailService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除上年度高新技术产品（服务）情况记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteTechProduct", method = RequestMethod.POST)
	public Result deleteTechProduct(@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 {
			res.setData(orgTechProductService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 刪除企业纳税申报信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteRatepay", method = RequestMethod.POST)
	public Result deleteRatepay(@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 {
			res.setData(orgRatepayService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除财务报表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteFinance", method = RequestMethod.POST)
	public Result deleteFinance(@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 {
			res.setData(orgFinanceService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除科技成果转化情况
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteAchievement", method = RequestMethod.POST)
	public Result deleteAchievement(@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 {
			res.setData(orgTechAchievementService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 删除企业荣誉及其他证明材料
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteHonor", method = RequestMethod.POST)
	public Result deleteHonor(@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 {
			res.setData(orgHonorDatumService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 企业花名册上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadRoster", method = RequestMethod.POST)
	public Result uploadRoster(HttpServletRequest req, String sign, String year) {
		Result res = new Result();

		if (StringUtils.isBlank(year)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示年份"));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.ROSTER) {
			sign = sign + "_" + year;
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 企业社保情况表上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadSocialSecurity", method = RequestMethod.POST)
	public Result uploadSocialSecurity(HttpServletRequest req, String sign, String year) {
		Result res = new Result();

		if (StringUtils.isBlank(year)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示年份"));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.SOCIAL_SECURITY) {
			sign = sign + "_" + year;
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 企业花名册及社保情况表下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadHumanResource", method = RequestMethod.GET)
	public Result downloadHumanResource(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgHumanResource ohr = orgHumanResourceService.selectByPrimaryKey(id);
		if (ohr == null || !curUser.getId().equals(ohr.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "企业人员情况id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.ROSTER) {
			downloadFile(response, ohr.getRosterDownloadFileName(), ohr.getRosterUrl());
		} else if (attachmentType == AttachmentType.SOCIAL_SECURITY) {
			downloadFile(response, ohr.getSocialSecurityDownloadFileName(), ohr.getSocialSecurityUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 知识产权证书上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadPropertyRight", method = RequestMethod.POST)
	public Result uploadPropertyRight(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PROPERTY_RIGHT) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 知识产权证书下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadPropertyRight", method = RequestMethod.GET)
	public Result downloadPropertyRight(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgIntellectualProperty olp = orgIntellectualPropertyService.selectByPrimaryKey(id);
		if (olp == null || !curUser.getId().equals(olp.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "知识产权id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PROPERTY_RIGHT) {
			downloadFile(response, olp.getPropertyRightDownloadFileName(), olp.getPropertyRightUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 高新技术产品台帐上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadTecProduct", method = RequestMethod.POST)
	public Result uploadTecProduct(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.TECH_PRODUCT) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 高新技术产品台帐下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadTecProduct", method = RequestMethod.GET)
	public Result downloadTecProduct(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgTechProduct otp = orgTechProductService.selectByPrimaryKey(id);
		if (otp == null || !curUser.getId().equals(otp.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "高新技术产品id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.TECH_PRODUCT) {
			downloadFile(response, otp.getAccountDownloadFileName(), otp.getAccountUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 研发活动立项证明材料上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadProof", method = RequestMethod.POST)
	public Result uploadProof(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PROOF) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 研发活动立项证明材料下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadProof", method = RequestMethod.GET)
	public Result downloadProof(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgActivity oa = orgActivityService.selectOrgActivityByPrimaryKey(id);
		if (oa == null || !curUser.getId().equals(oa.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "研发活动id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PROOF) {
			downloadFile(response, oa.getProofDownloadFileName(), oa.getProofUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 研发活动费用台帐上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadActivityCost", method = RequestMethod.POST)
	public Result uploadActivityCost(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.ACTIVITY_COST_ACCOUNT) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 研发活动费用台帐下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadActivityCost", method = RequestMethod.GET)
	public Result downloadActivityCost(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgActivityCost oac = orgActivityCostService.selectByPrimaryKey(id);
		if (oac == null || !curUser.getId().equals(oac.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", " 研发活动费用id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.ACTIVITY_COST_ACCOUNT) {
			downloadFile(response, oac.getAccountDownloadFileName(), oac.getAccountUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 实名认证--企业上年度纳税申报表上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadLastYearRatepay", method = RequestMethod.POST)
	public Result uploadLastYearRatepay(HttpServletRequest req, String sign) {
		Result res = new Result();

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.RATEPAY) {
			Calendar now = Calendar.getInstance();
			sign = sign + "_" + (now.get(Calendar.YEAR) - 1);
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 企业纳税申报表上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadRatepay", method = RequestMethod.POST)
	public Result uploadRatepay(HttpServletRequest req, String sign, String year) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(year)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示年份"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.RATEPAY) {
			sign = sign + "_" + year;
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 企业纳税申报表下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadRatepay", method = RequestMethod.GET)
	public Result downloadRatepay(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgRatepay ratepay = orgRatepayService.selectByPrimaryKey(id);
		if (ratepay == null || !TokenManager.getUserId().equals(ratepay.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "企业纳税申报id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.RATEPAY) {
			downloadFile(response, ratepay.getTaxReturnDownloadFileName(), ratepay.getTaxReturnUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 企业财务报表上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadFinance", method = RequestMethod.POST)
	public Result uploadFinance(HttpServletRequest req, String sign, String year) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(year)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示年份"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.FINANCE) {
			sign = sign + "_" + year;
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 企业财务报表下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadFinance", method = RequestMethod.GET)
	public Result downloadFinance(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgFinance of = orgFinanceService.selectByPrimaryKey(id);
		if (of == null || !curUser.getId().equals(of.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "企业财务报表id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.FINANCE) {
			downloadFile(response, of.getFinanceDownloadFileName(), of.getFinanceUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 科技成果附件上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadAchievement", method = RequestMethod.POST)
	public Result uploadAchievement(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.ACHIEVEMENT) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 科技成果附件下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadAchievement", method = RequestMethod.GET)
	public Result downloadAchievement(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgTechAchievement ota = orgTechAchievementService.selectByPrimaryKey(id);
		if (ota == null || !curUser.getId().equals(ota.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技成果id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.ACHIEVEMENT) {
			downloadFile(response, ota.getEnclosureDownloadFileName(), ota.getEnclosureUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 荣誉及其他证明材料上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadHonor", method = RequestMethod.POST)
	public Result uploadHonor(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.HONOR) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 荣誉及其他证明材料下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadHonor", method = RequestMethod.GET)
	public Result downloadHonor(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgHonorDatum ohd = orgHonorDatumService.selectByPrimaryKey(id);
		if (ohd == null || !curUser.getId().equals(ohd.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "荣誉及其他证明材料id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.HONOR) {
			downloadFile(response, ohd.getEnclosureDownloadFileName(), ohd.getEnclosureUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 研发部门制度上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadInstitution", method = RequestMethod.POST)
	public Result uploadInstitution(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.INSTITUTION) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 研发部门制度下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadInstitution", method = RequestMethod.GET)
	public Result downloadInstitution(HttpServletResponse response, String sign, String id) {
		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;
		}
		OrgTechCenter otc = orgTechCenterService.selectByPrimaryKey(id);
		if (otc == null || !curUser.getId().equals(otc.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "研发部门id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.INSTITUTION) {
			downloadFile(response, otc.getSystemDownloadFileName(), otc.getSystemUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 产学研技术中心协议上传
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadProtocol", method = RequestMethod.POST)
	public Result uploadProtocol(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PROTOCOL) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 产学研技术中心协议下载
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadProtocol", method = RequestMethod.GET)
	public Result downloadProtocol(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgTechCenterDetail otcd = orgTechCenterDetailService.selectByPrimaryKey(id);
		if (otcd == null) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "产学研技术中心id"));
			return res;
		}
		OrgTechCenter otc = orgTechCenterService.selectByPrimaryKey(otcd.getCid());

		if (otc == null || !curUser.getId().equals(otc.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "产学研技术中心id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PROTOCOL) {
			downloadFile(response, otcd.getProtocolDownloadFileName(), otcd.getProtocolUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 企业研究开发活动情况表入口
	 * 
	 * @param activityNumber
	 * @param activityName
	 * @param startDate
	 * @param endDate
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/activityList", method = RequestMethod.POST)
	public Result activityList(String activityNumber, String activityName, String startDateFormattedDate,
			String endDateFormattedDate, String pageNo, String pageSize) throws ParseException {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(orgActivityService.listOrgActivity(activityNumber, activityName, startDateFormattedDate,
				endDateFormattedDate, pNo, pSize, TokenManager.getUserId()));
		return res;
	}

	/**
	 * 企业研究开发活动情况新增、修改
	 * 
	 * @param orgActivity
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/activity", method = RequestMethod.POST)
	public Result activity(@Valid InputOrgActivity orgActivity, BindingResult bindingResult,
			String startDateFormattedDate, String endDateFormattedDate) throws ParseException {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgActivityFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(orgActivity.getActivityNumber())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "研发活动编号"));
			return res;
		}

		if (StringUtils.isBlank(startDateFormattedDate)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "开始时间"));
			return res;
		}

		if (StringUtils.isBlank(endDateFormattedDate)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "结束时间"));
			return res;
		}

		try {
			orgActivity.setStartDate(DateUtils.parseDate(startDateFormattedDate, AFTConstants.YYYYMMDD));
		} catch (ParseException e) {
		}

		try {
			orgActivity.setEndDate(DateUtils.parseDate(endDateFormattedDate, AFTConstants.YYYYMMDD));
		} catch (ParseException e) {
		}

		OrgActivity oa = new OrgActivity();
		BeanUtils.copyProperties(orgActivity, oa);

		if (StringUtils.isBlank(oa.getId())) {
			oa.setId(UUID.randomUUID().toString());
			oa.setUid(TokenManager.getUserId());
			oa.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgActivityService.insert(oa);
		} else {
			orgActivityService.updateOrgActivity(oa);
		}
		res.setData(oa);
		return res;
	}

	/**
	 * 企业年度研究开发费用结构明细表列表入口
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/activityCostList", method = RequestMethod.POST)
	public Result activityCostList(String activityNumber, String startDateFormattedDate, String endDateFormattedDate,
			String pageNo, String pageSize, Integer year) throws ParseException {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(orgActivityCostService.listOrgActivityCost(activityNumber, startDateFormattedDate,
				endDateFormattedDate, pNo, pSize, TokenManager.getUserId(), year));
		return res;
	}

	/**
	 * 企业年度研究开发费用结构明细表(新增+修改)
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/activityCost", method = RequestMethod.POST)
	public Result activityCost(@Valid InputOrgActivityCost orgActivityCost, BindingResult bindingResult,
			String signDateFormattedDate) throws ParseException {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgActivityFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(orgActivityCost.getAid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "项目ID"));
			return res;
		}

		if (null == orgActivityCost.getYear()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "费用年份"));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (!StringUtils.isBlank(signDateFormattedDate)) {
			orgActivityCost.setSignDate(DateUtils.parseDate(signDateFormattedDate, AFTConstants.YYYYMMDDHHMMSS));
		}

		OrgActivityCost oac = new OrgActivityCost();
		BeanUtils.copyProperties(orgActivityCost, oac);
		OrgActivityCost ccc = orgActivityCostService.selectOrgActivityCostByUidAndAidAndYear(oac.getAid(),
				TokenManager.getUserId(), orgActivityCost.getYear());
		OrgActivity ac = orgActivityService.selectOrgActivityByPrimaryKey(oac.getAid());
		if (StringUtils.isBlank(oac.getId())) {
			if (null != ccc) {
				res.getError().add(buildError(ErrorConstants.DUPLICATE_DATA_ERROR, "该研究项目费用详情已录入!"));
				return res;
			}

			res = disposeActivityYear(res, ac, oac);
			if (!res.getError().isEmpty()) {
				return res;
			}

			oac.setStartDate(ac.getStartDate());
			oac.setEndDate(ac.getEndDate());
			oac.setId(UUID.randomUUID().toString());
			oac.setUid(TokenManager.getUserId());
			oac.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgActivityCostService.insert(oac);
		} else {
			if (null != ccc && !ccc.getId().equals(oac.getId())) {
				res.getError().add(buildError(ErrorConstants.DUPLICATE_DATA_ERROR, "该研究项目费用详情已录入!"));
				return res;
			}
			res = disposeActivityYear(res, ac, oac);
			if (!res.getError().isEmpty()) {
				return res;
			}
			orgActivityCostService.updateByPrimaryKeySelective(oac);
		}
		return res;
	}

	/**
	 * 企业参与国家标准或行业标准制定情况明细入口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/standard", method = RequestMethod.POST)
	public Result standard(Integer year, String standardName, String standardNumber, Integer standardLevel, Integer participateWay,
			String pageNo, String pageSize) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(orgStandardService.listOrgStandard(year, standardName, standardNumber, standardLevel, participateWay, pNo,
				pSize, TokenManager.getUserId()));
		return res;
	}

	/**
	 * 企业参与国家标准或行业标准制定情况明细修改保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/developStandard", method = RequestMethod.POST)
	public Result developStandard(@Valid InputOrgStandard orgStandard, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgStandardFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (null == orgStandard.getYear()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "年份"));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		OrgStandard os = new OrgStandard();
		BeanUtils.copyProperties(orgStandard, os);

		if (StringUtils.isBlank(os.getId())) {
			os.setId(UUID.randomUUID().toString());
			os.setUid(TokenManager.getUserId());
			os.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			os.setCreateTime(now.getTime());
			orgStandardService.insert(os);
		} else {
			orgStandardService.updateByPrimaryKeySelective(os);
		}
		res.setData(orgStandard);
		return res;
	}

	/**
	 * 上传标准制定附件
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadStandard", method = RequestMethod.POST)
	public Result uploadStandard(HttpServletRequest req, String sign) {
		Result res = new Result();

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.STANDARD) {
			res.setData(handleFiles(res, "/cognizance/", true, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 下载标准制定
	 * 
	 * @param response
	 * @param sign
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/downloadStandard", method = RequestMethod.GET)
	public Result downloadStandard(HttpServletResponse response, String sign, String id) {
		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;
		}

		OrgStandard os = orgStandardService.selectByPrimaryKey(id);
		if (os == null || !curUser.getId().equals(os.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "标准指定id"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.STANDARD) {
			downloadFile(response, os.getStandardDownloadFileName(), os.getEnclosureUrl());
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 用户端录入+修改知识产权信息(专利+软著)
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/intellectual", method = RequestMethod.POST)
	public Result intellectual(@Valid InputOrgIntellectualProperty orgIntellectualProperty, BindingResult bindingResult,
			String authorizationDateFormattedDate) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgIntellectualPropertyFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(orgIntellectualProperty.getIntellectualPropertyNumber())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "知识产权编号", "知识产权编号"));
			return res;
		}
		
		if (null == orgIntellectualProperty.getCatagory()){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到类别", "类别"));
			return res;
		}

		OrgIntellectualProperty p = orgIntellectualPropertyService.findByUidAndIntellectualPropertyNumber(
				TokenManager.getUserId(), orgIntellectualProperty.getIntellectualPropertyNumber());

		if (!StringUtils.isBlank(authorizationDateFormattedDate)) {
			try {
				orgIntellectualProperty.setAuthorizationDate(
						DateUtils.parseDate(authorizationDateFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}
		OrgIntellectualProperty oip = new OrgIntellectualProperty();
		BeanUtils.copyProperties(orgIntellectualProperty, oip);

		if (StringUtils.isBlank(oip.getId())) {
			if (null != p) {
				res.getError().add(buildError("", "当前知识产权编号已录入，无法重复提交！"));
				return res;
			}
			oip.setId(UUID.randomUUID().toString());
			oip.setUid(TokenManager.getUserId());
			oip.setEvaluationCategory((oip.getCatagory() >= 2 && oip.getCatagory() <= 4) ? 1 : 0);
			oip.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			oip.setType(IntellectualPropertyType.COMMON.getCode());
			res.setData(orgIntellectualPropertyService.insert(oip));
		} else {
			if (null != p && !p.getId().equals(oip.getId())) {
				res.getError().add(buildError("", "当前知识产权编号已录入，无法重复提交！"));
				return res;
			}
			oip.setEvaluationCategory((oip.getCatagory() >= 2 && oip.getCatagory() <= 4) ? 1 : 0);
			res.setData(orgIntellectualPropertyService.updateByPrimaryKeySelective(oip));
		}
		return res;
	}

	/**
	 * 用户知识产权列表
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */

	@RequestMapping(value = "/intellectualList", method = RequestMethod.GET)
	public Result intellectualList(String pageNo, String pageSize, String startDate, String endDate) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

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

	/**
	 * 上年度高新技术产品（服务）情况列表
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/techProductList", method = RequestMethod.GET)
	public Result techProductList(String pageNo, String pageSize) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

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

	/**
	 * 上年度高新技术产品（服务）情况(新增+修改)
	 * 
	 * @param orgTechProduct
	 * @return
	 */
	@RequestMapping(value = "/techProduct", method = RequestMethod.POST)
	public Result techProduct(@Valid InputOrgTechProduct orgTechProduct, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgTechProductFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(orgTechProduct.getSerialNumber())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到产品编号", "产品编号"));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		OrgTechProduct otp = new OrgTechProduct();
		BeanUtils.copyProperties(orgTechProduct, otp);

		if (StringUtils.isBlank(otp.getId())) {
			OrgTechProduct product = orgTechProductService.findBySerialNumberAndUid(otp.getSerialNumber(),
					TokenManager.getUserId());
			if (null != product) {
				res.getError().add(buildError("", "产品编号重复，无法保存！"));
				return res;
			}
			otp.setId(UUID.randomUUID().toString());
			otp.setUid(TokenManager.getUserId());
			otp.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			otp.setCreateTime(now.getTime());
			otp.setYear(Calendar.getInstance().get(Calendar.YEAR) - 1);
			orgTechProductService.insert(otp);
		} else {
			orgTechProductService.updateByPrimaryKeySelective(otp);
		}
		res.setData(otp);
		return res;
	}

	/**
	 * 企业纳税申报信息入口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/ratepay", method = RequestMethod.GET)
	public Result ratepay(Integer year, String pageNo, String pageSize) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}

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

	/**
	 * 企业纳税申报信息录入+修改
	 */
	@RequestMapping(value = "/disposeRatepay", method = RequestMethod.POST)
	public Result disposeRatepay(@Valid InputOrgRatepay orgRatepay, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgRatepayFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (null == orgRatepay.getYear()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到年份", "年份"));
			return res;
		}

		OrgRatepay rate = new OrgRatepay();
		BeanUtils.copyProperties(orgRatepay, rate);

		if (StringUtils.isBlank(rate.getId())) {
			if (null == orgRatepayService.selectRatepayByUidAndYear(TokenManager.getUserId(), rate.getYear())) {
				rate.setId(UUID.randomUUID().toString());
				rate.setUid(TokenManager.getUserId());
				rate.setDeletedSign(DeleteStatus.UNDELETE.getCode());
				orgRatepayService.insert(rate);
			} else {
				res.getError().add(buildError(ErrorConstants.DUPLICATE_DATA_ERROR, "当年度纳税申报表已录入!"));
				return res;
			}
		} else {
			orgRatepayService.updateByPrimaryKeySelective(rate);
		}
		return res;
	}

	/**
	 * 财务报表信息入口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/finance", method = RequestMethod.GET)
	public Result finance(Integer year, String pageNo, String pageSize) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}

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

	/**
	 * 财务报表录入+修改
	 * 
	 * @param orgFinance
	 * @return
	 */
	@RequestMapping(value = "/disposeFinance", method = RequestMethod.POST)
	public Result disposeFinance(@Valid InputOrgFinance orgFinance, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgFinanceFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (null == orgFinance.getYear()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到年份", "年份"));
			return res;
		}

		OrgFinance of = new OrgFinance();
		BeanUtils.copyProperties(orgFinance, of);

		if (StringUtils.isBlank(of.getId())) {
			if (null == orgFinanceService.selectFinanceByUidAndYear(TokenManager.getUserId(), of.getYear())) {
				of.setId(UUID.randomUUID().toString());
				of.setUid(TokenManager.getUserId());
				of.setDeletedSign(DeleteStatus.UNDELETE.getCode());
				orgFinanceService.insert(of);
			} else {
				res.getError().add(buildError(ErrorConstants.DUPLICATE_DATA_ERROR, "当年度财务报表已录入!"));
				return res;
			}
		} else {
			orgFinanceService.updateByPrimaryKeySelective(of);
		}
		return res;
	}

	/**
	 * 获取当前用户已录入项目标号列表
	 * 
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/activityNumber", method = RequestMethod.GET)
	public Result listActivityNumber() {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}

		List<ActivityNumberBo> activityNumberBo = orgActivityService
				.selectOrgActivityNumberBoByUid(TokenManager.getUserId());
		res.setData(activityNumberBo);
		return res;
	}

	/**
	 * 高企相关材料上传
	 * 
	 * @param req
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result cognizanceFile(HttpServletRequest req, String sign, String uid) {
		Result res = new Result();
		if (!checkAdminLogin(res)) {
			return res;
		}

		res.setData(handleFile(res, "/cognizance/", true, req, sign, uid));
		return res;
	}

	/**
	 * 科技成果转化情况列表入口
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/achievementList", method = RequestMethod.GET)
	public Result achievementList(String pageNo, String pageSize) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

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

	/**
	 * 科技成果转化情况新增+修改
	 * 
	 * @param achievement
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/disposeAchievement", method = RequestMethod.POST)
	public Result disposeAchievement(@Valid InputOrgTechAchievement achievement, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgTechAchievementFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		OrgTechAchievement ota = new OrgTechAchievement();
		BeanUtils.copyProperties(achievement, ota);

		if (StringUtils.isBlank(ota.getId())) {
			ota.setId(UUID.randomUUID().toString());
			ota.setUid(TokenManager.getUserId());
			ota.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgTechAchievementService.insert(ota);
		} else {
			orgTechAchievementService.updateByPrimaryKeySelective(ota);
		}
		return res;
	}

	/**
	 * 企业荣誉及其他证明材料列表入口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/honorList", method = RequestMethod.GET)
	public Result honorList(String pageNo, String pageSize) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}

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

	/**
	 * 企业荣誉及其他证明材料新增+修改
	 * 
	 * @param achievement
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/disposeHonor", method = RequestMethod.POST)
	public Result disposeHonor(@Valid InputOrgHonorDatum honor, BindingResult bindingResult,
			String issuingTimeFormattedDate) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgHonorDatumFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (!StringUtils.isBlank(issuingTimeFormattedDate)) {
			try {
				honor.setIssuingTime(DateUtils.parseDate(issuingTimeFormattedDate, AFTConstants.YYYYMMDDHHMMSS));
			} catch (ParseException e) {
			}
		}

		if (null == honor.getYear()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "年份"));
			return res;
		}

		OrgHonorDatum ohd = new OrgHonorDatum();
		BeanUtils.copyProperties(honor, ohd);

		if (StringUtils.isBlank(ohd.getId())) {
			ohd.setId(UUID.randomUUID().toString());
			ohd.setUid(TokenManager.getUserId());
			ohd.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgHonorDatumService.insert(ohd);
		} else {
			orgHonorDatumService.updateByPrimaryKeySelective(ohd);
		}
		return res;
	}

	/**
	 * 技术中心入口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/center", method = RequestMethod.GET)
	public Result center() {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		res.setData(orgTechCenterService.selectOrgTechCenterByUid(TokenManager.getUserId()));
		return res;
	}

	/**
	 * 技术中心新增+修改
	 * 
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/disposeCenter", method = RequestMethod.POST)
	public Result disposeCenter(@Valid InputOrgTechCenter orgTechCenter, BindingResult bindingResult,
			String foundingTimeFormattedDate) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgTechCenterFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		
		if (StringUtils.isBlank(orgTechCenter.getCenterName())){
			res.getError().add(buildError(ErrorConstants.DATA_EMPTY_ERROR, "", "研发部门名称"));
			return res;
		}

		if (!StringUtils.isBlank(foundingTimeFormattedDate)) {
			try {
				orgTechCenter.setFoundingTime(DateUtils.parseDate(foundingTimeFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		OrgTechCenter otc = new OrgTechCenter();
		BeanUtils.copyProperties(orgTechCenter, otc);

		if (StringUtils.isBlank(otc.getId())) {
			otc.setId(UUID.randomUUID().toString());
			otc.setUid(TokenManager.getUserId());
			otc.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgTechCenterService.insert(otc);
		} else {
			orgTechCenterService.updateByPrimaryKeySelective(otc);
		}
		return res;
	}

	/**
	 * 技术中心明细列表入口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/centerDetail", method = RequestMethod.POST)
	public Result centerDetail(String pageNo, String pageSize, String cid) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(orgTechCenterDetailService.listOrgTechCenterDetail(pNo, pSize, cid));
		return res;
	}

	/**
	 * 技术中心明细新增+修改
	 * 
	 * @param orgTechCenterDetail
	 * @param projectTimeFormattedDate
	 * @param termTimeFormattedDate
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/disposeCenterDetail", method = RequestMethod.POST)
	public Result disposeCenterDetail(@Valid InputOrgTechCenterDetail orgTechCenterDetail, BindingResult bindingResult,
			String projectTimeFormattedDate, String termStartTimeFormattedDate, String termEndTimeFormattedDate) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgTechCenterDetailFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(orgTechCenterDetail.getCid())) {
			res.getError().add(buildError(ErrorConstants.STATUS_ERROR, "研发部门相关信息未保存，无法保存！"));
			return res;
		}

		if (!StringUtils.isBlank(projectTimeFormattedDate)) {
			try {
				orgTechCenterDetail
						.setProjectTime(DateUtils.parseDate(projectTimeFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}
		if (!StringUtils.isBlank(termStartTimeFormattedDate)) {
			try {
				orgTechCenterDetail
						.setTermStartTime(DateUtils.parseDate(termStartTimeFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		if (!StringUtils.isBlank(termEndTimeFormattedDate)) {
			try {
				orgTechCenterDetail
						.setTermEndTime(DateUtils.parseDate(termEndTimeFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		OrgTechCenterDetail otcd = new OrgTechCenterDetail();
		BeanUtils.copyProperties(orgTechCenterDetail, otcd);

		if (StringUtils.isBlank(otcd.getId())) {
			otcd.setId(UUID.randomUUID().toString());
			otcd.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgTechCenterDetailService.insert(otcd);
		} else {
			orgTechCenterDetailService.updateByPrimaryKeySelective(otcd);
		}
		return res;
	}

	/**
	 * 获取公司联系人
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getContacts", method = RequestMethod.GET)
	public Result getContacts() {
		Result res = new Result();
		res.setData(organizationIdentityService.selectContactsByUserId(TokenManager.getUserId()));
		return res;
	}

	/**
	 * 高企认定列表入口
	 * 
	 */
	@RequestMapping(value = "/listCognizance", method = RequestMethod.POST)
	public Result listCognizance(String contractId, Integer locationProvince, String pageNo, String pageSize) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(orgCognizanceService.listCognizance(contractId, TokenManager.getUserId(), null, locationProvince,
				pNo, pSize));

		return res;
	}

	/**
	 * 申请高企认定
	 * 
	 * @return
	 */
	@RequestMapping(value = "/applyCognizance", method = RequestMethod.POST)
	public Result applyCognizance(@Valid InputApplyCognizance cog, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					CognizanceApplyFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (null == cog.getYear()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "年份"));
			return res;
		}

		Integer latelyYear = orgCognizanceService.selectLatelyRecordYear(cog.getUid());
		if (null != latelyYear && cog.getYear() - latelyYear < 4) {
			res.getError()
					.add(buildError(ErrorConstants.STATUS_ERROR, "高企认定申请中或认定未到期！无法提交新申请!", "高企认定申请中或认定未到期！无法提交新申请!"));
			return res;
		}

		OrgCognizance oc = new OrgCognizance();
		BeanUtils.copyProperties(cog, oc);
		oc.setUid(TokenManager.getUserId());
		orgCognizanceService.insertCognizance(oc, curUser.getAid());
		return res;
	}

	/**
	 * 高企认定详情入口
	 * 
	 * @param uid
	 * @param cid
	 * @return
	 */
	@RequestMapping(value = "/cognizanceDetail", method = RequestMethod.POST)
	public Result cognizanceDetail(String cid, Integer year) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(cid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "高企ID"));
			return res;
		}

		if (null == year) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "年份"));
			return res;
		}

		res.setData(handleCognizanceDetail(TokenManager.getUserId(), cid, year));
		return res;
	}

	/**
	 * 高企认定流转状态
	 * 
	 * @param cid
	 * @return
	 */
	@RequestMapping(value = "/cognizanceLog", method = RequestMethod.POST)
	public Result cognizanceLog(String cid) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}

		if (StringUtils.isBlank(cid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "高企ID"));
			return res;
		}
		List<OrgCognizanceLog> list = orgCognizanceLogService.selectOrgCognizanceLogByCid(cid);
		for (Iterator<OrgCognizanceLog> log = list.iterator(); log.hasNext();) {
			Integer state = log.next().getState();
			if (OrgCognizanceStatus.getStatus(state) == OrgCognizanceStatus.SIGN
					|| OrgCognizanceStatus.getStatus(state) == OrgCognizanceStatus.CIRCULATION
					|| OrgCognizanceStatus.getStatus(state) == OrgCognizanceStatus.SETTLEMENT) {
				log.remove();
			}
		}

		res.setData(list);
		return res;
	}

	/**
	 * 保存高企认定详情
	 */
	@RequestMapping(value = "/disposeCognizanceDetail", method = RequestMethod.POST)
	public Result disposeCognizanceDetail(@Valid InputOrgCognizance cog, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgCognizanceFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(cog.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到", "高企认定"));
			return res;
		}

		OrgCognizance o = orgCognizanceService.selectByPrimaryKey(cog.getId());

		if (null == o) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到", "高企认定"));
			return res;
		}

		if (OrgCognizanceStatus.CALLBACK.getCode() == o.getState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前记录已退单，无法修改！"));
			return res;
		}

		if (OrgCognizanceStatus.SETTLEMENT.getCode() == o.getState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前记录已结款，无法修改！"));
			return res;
		}

		OrgCognizance oc = new OrgCognizance();
		BeanUtils.copyProperties(cog, oc);

		orgCognizanceService.updateByPrimaryKeySelective(oc);
		return res;
	}

	/**
	 * 年报列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/annualReport", method = RequestMethod.POST)
	public Result annualReport(Integer year, Integer state, String pageSize, String pageNo) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

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

	/**
	 * 企业年报详情
	 * 
	 * @param uid
	 * @param year
	 * @return
	 */
	@RequestMapping(value = "/annualReportDetail", method = RequestMethod.POST)
	public Result annualReportDetail(Integer year) {
		Result res = new Result();

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (null == year) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "年份"));
			return res;
		}

		res.setData(handleAnnualReport(TokenManager.getUserId(), year));
		return res;
	}

	/**
	 * 高企年报新增+修改
	 * 
	 * @param orgAnnualReport
	 * @return
	 */
	@RequestMapping(value = "/disposeAnnualReport", method = RequestMethod.POST)
	public Result disposeAnnualReport(@Valid InputOrgAnnualReport orgAnnualReport, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrgAnnualReportFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (!checkUserLogin(res)) {
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

		OrgAnnualReport oar = new OrgAnnualReport();
		BeanUtils.copyProperties(orgAnnualReport, oar);

		if (StringUtils.isBlank(oar.getId())) {
			if (null != orgAnnualReportService.selectAnnualReportByYearAndUid(oar.getYear(),
					TokenManager.getUserId())) {
				res.getError().add(buildError(ErrorConstants.DUPLICATE_DATA_ERROR, "当年企业年报已录入!"));
				return res;
			}
			oar.setId(UUID.randomUUID().toString());
			oar.setUid(TokenManager.getUserId());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			oar.setCreateTime(now.getTime());
			oar.setLastUpdateTime(oar.getCreateTime());
			oar.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			orgAnnualReportService.insert(oar);

		} else {
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			oar.setLastUpdateTime(now.getTime());
			orgAnnualReportService.updateByPrimaryKeySelective(oar);
		}
		return res;
	}

	private String handleFile(Result res, String path, boolean isPrivate, HttpServletRequest req, String sign,
			String uid) {
		List<MultipartFile> files = getFiles(req);
		MultipartFile mf = files.get(0);

		String fileName = FileUtils.mosaicFileName(mf, isPrivate, sign, path,
				StringUtils.isBlank(uid) ? TokenManager.getUserId() : uid);
		if (!files.isEmpty()) {
			try {
				mf.transferTo(toPrivateFile(fileName));
				LoggerUtils.debug(getClass(), fileName + " 文件上传成功");
			} catch (IllegalStateException | IOException e) {
				LoggerUtils.error(getClass(), "文件上传失败", e);
				res.getError().add(buildError("", "文件上传失败!"));
				return "";
			}
		} else {
			res.getError().add(buildError("", "文件上传失败!"));
			return "";
		}
		return fileName;
	}

	// 高企认定
	private CognizanceDetailBo handleCognizanceDetail(String uid, String cid, Integer year) {
		return orgCognizanceService.selectCognizanceDetailBo(uid, cid, year);
	}

	// 年报详情
	private AnnualReportBo handleAnnualReport(String uid, Integer year) {
		return orgAnnualReportService.selectAnnualReportBo(uid, year);
	}

	private Result disposeActivityYear(Result res, OrgActivity ac, OrgActivityCost oac) {
		Calendar c = Calendar.getInstance();
		c.setTime(ac.getStartDate());
		Integer s = c.get(Calendar.YEAR);
		c.setTime(ac.getEndDate());
		Integer e = c.get(Calendar.YEAR);
		if (oac.getYear() < s || oac.getYear() > e) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "年份"));
			return res;
		}
		return res;
	}

}
