package com.goafanti.admin.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

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

import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.goafanti.admin.service.AdminService;
import com.goafanti.admin.service.AttachmentService;
import com.goafanti.cognizance.service.OrgIntellectualPropertyService;
import com.goafanti.cognizance.service.OrgRatepayService;
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.DeleteStatus;
import com.goafanti.common.enums.PatentAnnualFeeStatus;
import com.goafanti.common.enums.PatentApplicationFeeStatus;
import com.goafanti.common.enums.PatentCategoryStatus;
import com.goafanti.common.enums.PatentCostFields;
import com.goafanti.common.enums.PatentFundsStatus;
import com.goafanti.common.enums.PatentInfoFields;
import com.goafanti.common.enums.PatentInfoStatus;
import com.goafanti.common.enums.PatentRegistrationFields;
import com.goafanti.common.enums.PatentReimbursementStatus;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.Attachment;
import com.goafanti.common.model.DistrictGlossory;
import com.goafanti.common.model.OrgRatepay;
import com.goafanti.common.model.PatentCost;
import com.goafanti.common.model.PatentInfo;
import com.goafanti.common.model.PatentLog;
import com.goafanti.common.model.PatentRegistration;
import com.goafanti.common.model.User;
import com.goafanti.common.service.DistrictGlossoryService;
import com.goafanti.common.utils.FileUtils;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.patent.bo.InputPatentCost;
import com.goafanti.patent.bo.InputPatentInfo;
import com.goafanti.patent.bo.InputPatentRegistration;
import com.goafanti.patent.bo.PatentApplicationFeeBo;
import com.goafanti.patent.bo.PatentManageListBo;
import com.goafanti.patent.bo.PatentPendingBo;
import com.goafanti.patent.service.PatentCostService;
import com.goafanti.patent.service.PatentInfoService;
import com.goafanti.patent.service.PatentLogService;
import com.goafanti.patent.service.PatentRegistrationService;
import com.goafanti.user.service.OrganizationIdentityService;
import com.goafanti.user.service.UserService;

@RestController
@RequestMapping(value = "/api/admin/patent")
public class AdminPatentApiController extends CertifyApiController {
	@Resource
	private PatentInfoService				patentInfoService;
	@Resource
	private PatentLogService				patentLogService;
	@Resource
	private OrganizationIdentityService		organizationIdentityServivce;
	@Resource
	private PatentCostService				patentCostService;
	@Resource
	private PatentRegistrationService		patentRegistrationService;
	@Resource
	private AdminService					adminService;
	@Resource
	private OrgIntellectualPropertyService	orgIntellectualPropertyService;
	@Resource
	private UserService						userService;
	@Resource
	private AttachmentService					aftFileService;
	@Resource
	private OrgRatepayService				orgRatepayService;
	@Resource
	private OrganizationIdentityService		organizationIdentityService;
	@Resource
	private DistrictGlossoryService			districtGlossoryService;

	@Value(value = "${aesSecretKey}")
	private String							secretKey	= null;


	/**
	 * 专利批量流转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/circulation", method = RequestMethod.POST)
	public Result circulation(@RequestParam(name = "ids[]", required = false) String[] ids, @Valid InputPatentInfo pi,
			BindingResult bindingResult, String recordTimeFormattedDate) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					PatentInfoFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (ids == null || ids.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
			return res;
		}

		if (null == pi.getState()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到流转状态", "流转状态"));
			return res;
		}

		if (StringUtils.isBlank(pi.getPrincipal())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到负责人", "负责人"));
			return res;
		}

		if (StringUtils.isBlank(recordTimeFormattedDate)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到记录流转时间", "记录流转时间"));
			return res;
		}

		if (PatentInfoStatus.DELIVERD.getCode() != pi.getState()
				&& PatentInfoStatus.CIRCULATION.getCode() != pi.getState()
				&& PatentInfoStatus.SETTLEMENT.getCode() != pi.getState()) {
			res.getError().add(buildError(ErrorConstants.STATUS_ERROR, "仅派单、流转、结款可操作!"));
			return res;
		}

		PatentLog pl = new PatentLog();
		BeanUtils.copyProperties(pi, pl);

		res.setData(patentInfoService.batchCirculation(ids, recordTimeFormattedDate, pl));
		return res;
	}

	/**
	 * 专利列表
	 * 
	 * @throws ParseException
	 */
	@RequestMapping(value = "/patentList", method = RequestMethod.GET)
	public Result patentList(String contractId, Integer serialNumber, String patentNumber, String office,
			Integer locationProvince, String unitName, Integer patentCatagory, String patentName, Integer patentState,
			String uid, @RequestParam(name = "createTime[]", required = false) String[] createTime,
			@RequestParam(name = "patentApplicationDate[]", required = false) String[] patentApplicationDate,
			String author, 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(patentInfoService.getManagePatentList(contractId, serialNumber, patentNumber, office,
				locationProvince, unitName, patentCatagory, patentName, patentState, createTime, patentApplicationDate,
				author, uid, pNo, pSize));
		return res;
	}

	/**
	 * 新增专利申请
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public Result manageApplyPatent(@Valid InputPatentInfo patentInfo, BindingResult bindingResult) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					PatentInfoFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(patentInfo.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}

		if (StringUtils.isBlank(patentInfo.getSalesman())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到营销员", "营销员"));
			return res;
		}

		String salesman = patentInfo.getSalesman();

		User curUser = userService.selectByPrimaryKey(patentInfo.getUid());
		if (!checkCertify(res, curUser)) {
			return res;
		}
		PatentInfo pi = new PatentInfo();
		BeanUtils.copyProperties(patentInfo, pi);
		res.setData(patentInfoService.savePatentInfo(pi, salesman));
		return res;
	}

	/**
	 * 专利详情
	 * 
	 * @param pid
	 * @return
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public Result patentDetail(String pid) {
		Result res = new Result();
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "专利ID"));
		} else {
			res.setData(patentInfoService.selectPatentInfoDetail(pid));
		}
		return res;
	}

	/**
	 * 管理端logs
	 */
	@RequestMapping(value = "/logs", method = RequestMethod.GET)
	public Result patentProcess(String pid) {
		Result res = new Result();
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "专利ID"));
		} else {
			res.setData(patentLogService.selectProcessByPid(pid));
		}
		return res;
	}

	/**
	 * 专利详情修改保存
	 * 
	 * @throws ParseException
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Result managePatentInfo(@Valid InputPatentInfo patentInfo, BindingResult bindingResult,
			String recordTimeFormattedDate) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					PatentInfoFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(patentInfo.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		PatentInfo p = patentInfoService.selectByPrimaryKey(patentInfo.getId());
		if (null == p) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (PatentInfoStatus.CALLBACK.getCode() == p.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前申请已退单，无法修改！"));
			return res;
		}

		if (PatentInfoStatus.SETTLEMENT.getCode() == p.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前申请已结款，无法修改！"));
			return res;
		}

		Date recordTime = null;
		if (!StringUtils.isBlank(recordTimeFormattedDate)) {
			try {
				recordTime = DateUtils.parseDate(recordTimeFormattedDate, AFTConstants.YYYYMMDDHHMMSS);
			} catch (ParseException e) {
			}
		}
		PatentInfo pi = new PatentInfo();
		PatentLog pl = new PatentLog();
		pi.setId(patentInfo.getId());
		BeanUtils.copyProperties(patentInfo, pi);
		BeanUtils.copyProperties(patentInfo, pl);
		patentInfoService.updatePatentInfo(pi, pl, recordTime);
		return res;
	}

	/**
	 * 专利状态流转下拉
	 * 
	 * @return
	 */
	@RequestMapping(value = "/patentStatus", method = RequestMethod.GET)
	public Result patentStatus() {
		Result res = new Result();
		res.setData(disposePatentStatus());
		return res;
	}

	/**
	 * 上年度纳税申报报表是否存在
	 * 
	 * @param uid
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "/lastYearTax", method = RequestMethod.GET)
	public Result lastYearTax(String uid, String sign) {
		Result res = new Result();

		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType != AttachmentType.LAST_YEAR_RATEPAY) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
			return res;
		}

		Calendar cal = Calendar.getInstance();
		OrgRatepay ratepay = orgRatepayService.selectRatepayByUidAndYear(uid, cal.get(Calendar.YEAR) - 1);

		if (null == ratepay || StringUtils.isBlank(ratepay.getTaxReturnUrl())) {
			return res;
		}

		Map<String, String> map = new TreeMap<String, String>();
		map.put("id", ratepay.getId());
		map.put("year", ratepay.getYear().toString());
		res.setData(map);

		return res;
	}

	/**
	 * 专利相关材料上传(专利稿件,授权通知书,专利证书)
	 * 
	 * @param req
	 * @param uid
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result upload(HttpServletRequest req, String sign, String uid, String id) {
		Result res = new Result();

		User curUser = userService.selectByPrimaryKey(uid);
		if (!checkCertify(res, curUser)) {
			return res;
		}

		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		PatentInfo p = patentInfoService.selectByPrimaryKey(id);
		if (null == p) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (PatentInfoStatus.CALLBACK.getCode() == p.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前申请已退单，无法修改！"));
			return res;
		}

		if (PatentInfoStatus.SETTLEMENT.getCode() == p.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前申请已结款，无法修改！"));
			return res;
		}

		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PATENT_WRITING || attachmentType == AttachmentType.AUTHORIZATION_NOTICE
				|| attachmentType == AttachmentType.PATENT_CERTIFICATE) {
			res.setData(handleFiles(res, "/patent/", true, req, sign, uid));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}

		return res;
	}

	/**
	 * 新增专利申请上传专利代理委托书
	 * 
	 * @param req
	 * @param sign
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/uploadProry", method = RequestMethod.POST)
	public Result uploadProry(HttpServletRequest req, String sign, String uid) {
		Result res = new Result();

		User curUser = userService.selectByPrimaryKey(uid);
		if (!checkCertify(res, curUser)) {
			return res;
		}

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

		return res;
	}

	/**
	 * 下载专利相关材料
	 * 
	 * @param id
	 * @param sign
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public Result download(String id, String sign, HttpServletResponse response) {
		Result res = new Result();
		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "专利id"));
			return res;
		}
		PatentInfo pi = patentInfoService.selectByPrimaryKey(id);
		if (pi == null) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "专利id"));
			return res;
		}
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PATENT_PRORY_STATEMENT || attachmentType == AttachmentType.PATENT_WRITING
				|| attachmentType == AttachmentType.AUTHORIZATION_NOTICE
				|| attachmentType == AttachmentType.PATENT_CERTIFICATE) {
			if (attachmentType == AttachmentType.PATENT_WRITING) {
				downloadFile(response, pi.getPatentWritingDownloadFileName(), pi.getPatentWritingUrl());
			} else if (attachmentType == AttachmentType.AUTHORIZATION_NOTICE) {
				downloadFile(response, pi.getAuthorizationNoticeDownloadFileName(), pi.getAuthorizationNoticeUrl());
			} else if (attachmentType == AttachmentType.PATENT_CERTIFICATE) {
				downloadFile(response, pi.getPatentCertificateDownloadFileName(), pi.getPatentCertificateUrl());
			}
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 下载模版文件(专利代理委托书)
	 * 
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/downloadTemplateFile", method = RequestMethod.GET)
	public Result downloadTemplateFile(HttpServletResponse response, String sign) {
		Result res = new Result();
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.PATENT_PRORY_STATEMENT) {
			String fileName = "";
			Attachment af = aftFileService.selectAftFileBySign(sign);
			if (null == af) {
				res.getError().add(buildError(ErrorConstants.FILE_NON_EXISTENT, "", "找不到文件！"));
			} else {
				String path = af.getFilePath();
				String suffix = path.substring(path.lastIndexOf("."));
				fileName = AttachmentType.PATENT_TEMPLATE.getDesc() + suffix;
				downloadFile(response, fileName, path);
			}
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	/**
	 * 下载上年度纳税申报表
	 * 
	 * @param response
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "/downloadRatepay", method = RequestMethod.GET)
	public Result downloadRatepay(HttpServletResponse response, String id, String sign) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "纳税表ID"));
			return res;
		}

		OrgRatepay ratepay = orgRatepayService.selectByPrimaryKey(id);

		if (null == ratepay) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到上年度纳税申报表", "上年度纳税申报表"));
			return res;
		}

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

	/**
	 * 上传专利代理委托书模版
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/uploadTemplate", method = RequestMethod.POST)
	public Result uploadPatentTemplate(HttpServletRequest req, String sign) {
		Result res = new Result();
		String fileName = "";
		List<MultipartFile> files = getFiles(req);
		MultipartFile mf = files.get(0);
		String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
		if (suffix.equals(".doc") || suffix.equals(".docx")) {
			AttachmentType attachmentType = AttachmentType.getField(sign);
			if (attachmentType == AttachmentType.PATENT_PRORY_STATEMENT) {
				fileName = sign + suffix;
			} else {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
				return res;
			}
			String name = handleFile(res, req, fileName, files, mf);
			res.setData(name);
			if (!StringUtils.isBlank(name) && null == aftFileService.selectAftFileBySign(sign)) {
				Attachment f = new Attachment();
				f.setId(UUID.randomUUID().toString());
				f.setFileName(AttachmentType.PATENT_TEMPLATE.getDesc());
				f.setSign(sign);
				f.setUid(TokenManager.getAdminId());
				f.setComment(AttachmentType.PATENT_TEMPLATE.getDesc());
				f.setFilePath("/admin/" + fileName);
				f.setDeleletedSign(DeleteStatus.UNDELETE.getCode());
				aftFileService.insert(f);

			}
		} else {
			res.getError().add(buildError(ErrorConstants.FILE_PATTERN_ERROR, "文件格式错误，请重新上传！"));
		}
		return res;
	}

	/**
	 * 删除专利
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Result deletePatent(@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(patentInfoService.batchDeleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 待缴费专利管理列表
	 */
	@RequestMapping(value = "/pendingPaymentList", method = RequestMethod.GET)
	public Result managePendingPaymentList(Integer locationProvince, 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(patentInfoService.getManagePendingPaymentList(locationProvince, pNo, pSize));
		return res;
	}

	/**
	 * 年费确认缴费
	 */
	@RequestMapping(value = "/confirmPayment", method = RequestMethod.POST)
	public Result confirmPayment(String cid, String uid) {
		Result res = new Result();
		if (StringUtils.isBlank(cid) || StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}
		PatentCost cost = patentCostService.selectByPrimaryKey(cid);
		if (null == cost) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (null == cost.getPid()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		PatentInfo info = patentInfoService.selectByPrimaryKey(cost.getPid());
		if (!uid.equals(info.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (PatentInfoStatus.CALLBACK.getCode() == info.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前申请已退单，无法修改！"));
			return res;
		}

		if (PatentInfoStatus.SETTLEMENT.getCode() == info.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前申请已结款，无法修改！"));
			return res;
		}

		PatentCost patentCost = new PatentCost();
		patentCost.setId(cid);
		patentCost.setAnnualFeeState(1);
		patentCostService.updateByPrimaryKeySelective(patentCost);
		return res;
	}

	/**
	 * 补正审查通知列表
	 */
	@RequestMapping(value = "/noticeOfCorrectionList", method = RequestMethod.POST)
	public Result noticeOfCorrectionList(Date authorizedDate, Integer serialNumber, String patentNumber, String office,
			Integer locationProvince, String unitName, Integer patentCatagory, String patentName, Integer patentState,
			String author, 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(patentInfoService.getNoticeOfCorrectionList(authorizedDate, serialNumber, patentNumber, office,
				locationProvince, unitName, patentCatagory, patentName, patentState, author, pNo, pSize));
		return res;
	}

	/**
	 * 补正审查通知答复确认
	 */
	@RequestMapping(value = "/replyConfirm", method = RequestMethod.POST)
	public Result replyConfirm(String pid, String uid, Integer patentState) {
		Result res = new Result();
		if (StringUtils.isBlank(pid) || StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (null == patentState || (patentState != PatentInfoStatus.REVIEWNOTICE.getCode()
				&& patentState != PatentInfoStatus.CORRECTIONNOTICE.getCode())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "专利状态"));
			return res;
		}

		PatentInfo info = patentInfoService.selectByPrimaryKey(pid);
		if (!uid.equals(info.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}
		patentInfoService.updateNoticeOfCorrection(pid, patentState);
		return res;
	}

	/**
	 * 收发详情入口/收发纸件登记
	 */
	@RequestMapping(value = "/getRecieveSendList", method = RequestMethod.GET)
	public Result RecieveSendList(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(patentRegistrationService.getRecieveSendList(pNo, pSize));
		return res;
	}

	/**
	 * 收发登记详情编辑保存
	 * 
	 * @throws ParseException
	 */
	@RequestMapping(value = "/saveRecieveSend", method = RequestMethod.POST)
	public Result recieveSendDetail(@Valid InputPatentRegistration patentRegistrationBo, BindingResult bindingResult,
			String rid, String pid) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					PatentRegistrationFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(pid) || StringUtils.isBlank(rid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "专利记录ID", "专利记录ID"));
			return res;
		}

		PatentInfo p = patentInfoService.selectByPrimaryKey(pid);
		if (null == p) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (PatentInfoStatus.CALLBACK.getCode() == p.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前申请已退单，无法修改！"));
			return res;
		}

		if (PatentInfoStatus.SETTLEMENT.getCode() == p.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前申请已结款，无法修改！"));
			return res;
		}

		patentRegistrationService.updateByPrimaryKey(regBo2Reg(rid, pid, patentRegistrationBo));
		return res;
	}

	/**
	 * 专利申请费用管理
	 */
	@RequestMapping(value = "/getApplicationFeeList", method = RequestMethod.GET)
	public Result getApplicationFeeList(
			@RequestParam(name = "patentApplicationDate[]", required = false) String[] patentApplicationDate,
			Integer locationProvince, String pageNo, String pageSize) throws ParseException {
		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(patentCostService.getApplicationFeeList(patentApplicationDate, locationProvince, pNo, pSize));
		return res;
	}

	/**
	 * 登记申请费用
	 */
	@RequestMapping(value = "/registerApplicationFee", method = RequestMethod.POST)
	public Result registerApplicationFee(@Valid InputPatentCost patentCost, BindingResult bindingResult, String cid) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					PatentCostFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (null == cid) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "专利记录ID", "专利记录ID"));
			return res;
		}

		PatentCost cost = patentCostService.selectByPrimaryKey(cid);
		if (null == cost) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		if (null == cost.getPid()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到专利申请", "专利记录ID"));
			return res;
		}

		PatentInfo info = patentInfoService.selectByPrimaryKey(cost.getPid());

		if (PatentInfoStatus.CALLBACK.getCode() == info.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前申请已退单，无法修改！"));
			return res;
		}

		if (PatentInfoStatus.SETTLEMENT.getCode() == info.getPatentState()) {
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前申请已结款，无法修改！"));
			return res;
		}

		PatentCost pc = new PatentCost();
		BeanUtils.copyProperties(patentCost, pc);
		pc.setId(cid);
		res.setData(patentCostService.updateByPrimaryKeySelective(pc));
		return res;
	}

	/**
	 * 专利综合管理报表导出
	 * 
	 * @throws ParseException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportComposite", method = RequestMethod.GET)
	public Result exportComposite(@RequestParam(name = "contractId", required = false) String contractId,
			@RequestParam(name = "serialNumber", required = false) String serialNumber,
			@RequestParam(name = "patentNumber", required = false) String patentNumber,
			@RequestParam(name = "office", required = false) String office,
			@RequestParam(name = "locationProvince", required = false) String locationProvince,
			@RequestParam(name = "unitName", required = false) String unitName,
			@RequestParam(name = "uid", required = false) String uid,
			@RequestParam(name = "patentCatagory", required = false) String patentCatagory,
			@RequestParam(name = "patentName", required = false) String patentName,
			@RequestParam(name = "patentState", required = false) String patentState,
			@RequestParam(name = "createTime[]", required = false) String[] createTime,
			@RequestParam(name = "patentApplicationDate[]", required = false) String[] patentApplicationDate,
			@RequestParam(name = "author", required = false) String author, HttpServletResponse response)
			throws ParseException {
		Result res = new Result();

		Integer sn = (!StringUtils.isNumeric(serialNumber) ? null : Integer.parseInt(serialNumber));
		Integer pc = (!StringUtils.isNumeric(patentCatagory) ? null : Integer.parseInt(patentCatagory));
		Integer ps = (!StringUtils.isNumeric(patentState) ? null : Integer.parseInt(patentState));
		Integer lp = (!StringUtils.isNumeric(locationProvince) ? null : Integer.parseInt(locationProvince));
		List<PatentManageListBo> composites = (List<PatentManageListBo>) getManagePatentList(contractId, sn,
				patentNumber, office, lp, unitName, pc, patentName, ps, createTime, patentApplicationDate, author, uid,
				1, 1000).getList();
		if (res.getError().isEmpty()) {
			exportComosites(response, composites);
		} else {
			FileUtils.out(response, JSON.toJSONString(res));
		}
		return res;
	}

	/**
	 * 待缴年登印费专利管理报表导出
	 */
	@RequestMapping(value = "/exportPending", method = RequestMethod.GET)
	public Result exportPending(@RequestParam(name = "locationProvince", required = false) String locationProvince,
			HttpServletResponse response) {
		Result res = new Result();
		Integer lp = (!StringUtils.isNumeric(locationProvince) ? null : Integer.parseInt(locationProvince));
		@SuppressWarnings("unchecked")
		List<PatentPendingBo> pendings = (List<PatentPendingBo>) getManagePendingPaymentList(lp, 1, 1000).getList();
		if (res.getError().isEmpty()) {
			exportPendings(response, pendings);
		} else {
			FileUtils.out(response, JSON.toJSONString(res));
		}
		return res;
	}

	/**
	 * 专利申请费用管理报表导出
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportApplicationFee", method = RequestMethod.GET)
	public Result exportApplicationFee(
			@RequestParam(name = "patentApplicationDate[]", required = false) String[] patentApplicationDate,
			@RequestParam(name = "locationProvince", required = false) String locationProvince,
			HttpServletResponse response) throws ParseException {
		Result res = new Result();
		Integer lp = (!StringUtils.isNumeric(locationProvince) ? null : Integer.parseInt(locationProvince));
		List<PatentApplicationFeeBo> fees = (List<PatentApplicationFeeBo>) getApplicationFeeList(patentApplicationDate,
				lp, 1, 1000).getList();
		if (res.getError().isEmpty()) {
			exportFees(response, fees);
		} else {
			FileUtils.out(response, JSON.toJSONString(res));
		}

		return res;
	}

	/**
	 * 获取资料撰写人下拉
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getAuthor", method = RequestMethod.GET)
	public Result getAuthor() {
		Result res = new Result();
		List<Admin> list = adminService.selectPatentAuthor();
		Map<String, String> map = new TreeMap<String, String>();
		for (Admin o : list) {
			map.put(o.getId(), o.getName());
		}
		res.setData(map);
		return res;
	}

	/**
	 * 专利负责人下拉
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getPrincipal", method = RequestMethod.GET)
	public Result getPrincipal() {
		Result res = new Result();
		List<Admin> list = adminService.selectPatentPrincipal();
		Map<String, String> map = new TreeMap<String, String>();
		for (Admin o : list) {
			map.put(o.getId(), o.getName() + " " + (null == o.getPosition() ? "" : o.getPosition()));
		}
		res.setData(map);
		return res;
	}

	// 专利申请费用管理报表
	private void exportFees(HttpServletResponse response, List<PatentApplicationFeeBo> fees) {
		String sheetName = "专利申请费用管理报表";
		HSSFWorkbook workbook = createWorkbook(sheetName,
				new String[] { "编号", "申请号/专利号", "省份", "公司名称", "专利名称", "缴费状态", "申请费", "是否请款", "是否报销", "申请日", "缴费截止时间" });

		HSSFSheet sheet = workbook.getSheet(sheetName);
		Map<Integer, DistrictGlossory> districtMap = getProvinces();
		for (int i = 0; i < fees.size(); i++) {
			PatentApplicationFeeBo obj = fees.get(i);
			HSSFRow row = sheet.createRow(i + 2);// 创建所需的行数
			row.createCell(0).setCellValue(null == obj.getSerialNumber() ? "" : obj.getSerialNumber().toString());
			row.createCell(1).setCellValue(obj.getPatentNumber());
			Integer locationProvince = obj.getLocationProvince();
			row.createCell(2).setCellValue(null == locationProvince ? "" : getProvince(districtMap, locationProvince));
			row.createCell(3).setCellValue(obj.getUnitName());
			row.createCell(4).setCellValue(obj.getPatentName());
			Integer paymentState = obj.getPaymentState();
			if (null != paymentState && PatentApplicationFeeStatus.PAID.getCode().equals(paymentState)) {
				row.createCell(5).setCellValue(PatentApplicationFeeStatus.PAID.getDesc());
			} else {
				row.createCell(5).setCellValue(PatentApplicationFeeStatus.UNPAID.getDesc());
			}
			row.createCell(6).setCellValue(null == obj.getApplicationFee() ? 0 : obj.getApplicationFee());
			Integer funds = obj.getFunds();
			if (null != funds && PatentFundsStatus.YES.getCode().equals(funds)) {
				row.createCell(7).setCellValue(PatentFundsStatus.YES.getDesc());
			} else {
				row.createCell(7).setCellValue(PatentFundsStatus.NO.getDesc());
			}
			Integer reimbursement = obj.getReimbursement();
			if (null != reimbursement && PatentReimbursementStatus.YES.getCode().equals(reimbursement)) {
				row.createCell(8).setCellValue(PatentReimbursementStatus.YES.getDesc());
			} else {
				row.createCell(8).setCellValue(PatentReimbursementStatus.NO.getDesc());
			}

			row.createCell(9).setCellValue(obj.getPatentApplicationDateFormattedDate());
			row.createCell(10).setCellValue(null == obj.getPatentApplicationDateFormattedDate() ? ""
					: calDeadline(obj.getPatentApplicationDateFormattedDate()));
		}
		FileUtils.downloadExcel(response, sheetName + Calendar.getInstance().getTimeInMillis() + ".xls", workbook);
	}

	// 待缴年登印费专利管理报表
	private void exportPendings(HttpServletResponse response, List<PatentPendingBo> pendings) {
		String sheetName = "待缴年登印费专利管理报表";
		HSSFWorkbook workbook = createWorkbook(sheetName,
				new String[] { "编号", "申请号/专利号", "省份", "公司名称", "专利类型", "专利名称", "专利状态", "缴费状态", "缴费截止日期" });

		HSSFSheet sheet = workbook.getSheet(sheetName);
		Map<Integer, DistrictGlossory> districtMap = getProvinces();
		for (int i = 0; i < pendings.size(); i++) {
			PatentPendingBo obj = pendings.get(i);
			HSSFRow row = sheet.createRow(i + 2);// 创建所需的行数
			row.createCell(0).setCellValue(null == obj.getSerialNumber() ? "" : obj.getSerialNumber().toString());
			row.createCell(1).setCellValue(obj.getPatentNumber());
			Integer locationProvince = obj.getLocationProvince();
			row.createCell(2).setCellValue(null == locationProvince ? "" : getProvince(districtMap, locationProvince));
			row.createCell(3).setCellValue(obj.getUnitName());
			Integer patentCatagory = obj.getPatentCatagory();
			if (null != patentCatagory) {
				if (PatentCategoryStatus.OTHER.getCode().equals(patentCatagory)) {
					row.createCell(4).setCellValue(PatentCategoryStatus.OTHER.getDesc());
				} else if (PatentCategoryStatus.UTILITY.getCode().equals(patentCatagory)) {
					row.createCell(4).setCellValue(PatentCategoryStatus.UTILITY.getDesc());
				} else if (PatentCategoryStatus.DESIGN.getCode().equals(patentCatagory)) {
					row.createCell(4).setCellValue(PatentCategoryStatus.DESIGN.getDesc());
				} else if (PatentCategoryStatus.INVENTION.getCode().equals(patentCatagory)) {
					row.createCell(4).setCellValue(PatentCategoryStatus.INVENTION.getDesc());
				}
			} else {
				row.createCell(4).setCellValue("");
			}
			row.createCell(5).setCellValue(obj.getPatentName());
			row.createCell(6).setCellValue(null == obj.getPatentState() ? "" : switchPatState(obj.getPatentState()));
			Integer annualFeeState = obj.getAnnualFeeState();
			if (null != annualFeeState && PatentAnnualFeeStatus.PAID.getCode().equals(annualFeeState)) {
				row.createCell(7).setCellValue(PatentAnnualFeeStatus.PAID.getDesc());
			} else {
				row.createCell(7).setCellValue(PatentAnnualFeeStatus.UNPAID.getDesc());
			}
			row.createCell(8).setCellValue(null == obj.getAuthorizedDateFormattedDate() ? ""
					: calDeadline(obj.getAuthorizedDateFormattedDate()));

		}

		FileUtils.downloadExcel(response, sheetName + Calendar.getInstance().getTimeInMillis() + ".xls", workbook);
	}

	private void exportComosites(HttpServletResponse response, List<PatentManageListBo> composites) {
		String sheetName = "专利综合管理报表";
		HSSFWorkbook workbook = createWorkbook(sheetName, new String[] { "编号", "申请号/专利号", "合同编号", "事务所", "省份", "公司名称",
				"专利名称", "专利状态", "派单日", "申请日", "授权日", "资料撰写人" });
		HSSFSheet sheet = workbook.getSheet(sheetName);

		// 将查询出的数据设置到sheet对应的单元格中
		Map<Integer, DistrictGlossory> districtMap = getProvinces();
		for (int i = 0; i < composites.size(); i++) {
			PatentManageListBo obj = composites.get(i);// 遍历每个对象
			HSSFRow row = sheet.createRow(i + 2);// 创建所需的行数
			row.createCell(0).setCellValue(null == obj.getSerialNumber() ? "" : obj.getSerialNumber().toString());
			row.createCell(1).setCellValue(obj.getPatentNumber());
			row.createCell(2).setCellValue(null == obj.getContractNumber() ? "" : obj.getContractNumber().toString());
			row.createCell(3).setCellValue(obj.getOffice());
			Integer locationProvince = obj.getLocationProvince();
			row.createCell(4).setCellValue(null == locationProvince ? "" : getProvince(districtMap, locationProvince));
			row.createCell(5).setCellValue(obj.getUnitName());
			row.createCell(6).setCellValue(obj.getPatentName());
			row.createCell(7).setCellValue(null == obj.getPatentState() ? "" : switchPatState(obj.getPatentState()));
			row.createCell(8).setCellValue(obj.getCreateTimeFormattedDate());
			row.createCell(9).setCellValue(obj.getPatentApplicationFormattedDate());
			row.createCell(10).setCellValue(obj.getPatentApplicationFormattedDate());
			row.createCell(11).setCellValue(obj.getAuthor());
		}
		FileUtils.downloadExcel(response, sheetName + Calendar.getInstance().getTimeInMillis() + ".xls", workbook);

	}

	private HSSFWorkbook createWorkbook(String sheetName, String[] colNames) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(sheetName);
		// 产生表格标题行
		HSSFRow rowm = sheet.createRow(0);
		HSSFCell cellTitle = rowm.createCell(0);
		cellTitle.setCellValue(sheetName);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (colNames.length - 1)));

		HSSFRow rowRowName = sheet.createRow(1); // 在索引2的位置创建行(最顶端的行开始的第二行)

		// 将列头设置到sheet的单元格中
		for (int n = 0; n < colNames.length; n++) {
			rowRowName.createCell(n).setCellValue(colNames[n]);
		}
		return workbook;
	}

	private PatentRegistration regBo2Reg(String rid, String pid, InputPatentRegistration patentRegistrationBo) {
		PatentRegistration patentRegistration = new PatentRegistration();
		patentRegistration.setId(rid);
		patentRegistration.setAcceptanceExpressCompany(patentRegistrationBo.getAcceptanceExpressCompany());
		try {
			if (!StringUtils.isBlank(patentRegistrationBo.getAcceptanceIssueTime())) {
				patentRegistration.setAcceptanceIssueTime(
						DateUtils.parseDate(patentRegistrationBo.getAcceptanceIssueTime(), AFTConstants.YYYYMMDD));
			}
			if (!StringUtils.isBlank(patentRegistrationBo.getAcceptanceReceiveTime())) {
				patentRegistration.setAcceptanceReceiveTime(
						DateUtils.parseDate(patentRegistrationBo.getAcceptanceReceiveTime(), AFTConstants.YYYYMMDD));
			}
			patentRegistration.setAcceptanceTrackingNumber(patentRegistrationBo.getAcceptanceTrackingNumber());
			patentRegistration.setAuthorizationExpressCompany(patentRegistrationBo.getAuthorizationExpressCompany());
			if (!StringUtils.isBlank(patentRegistrationBo.getAuthorizationIssueTime())) {
				patentRegistration.setAuthorizationIssueTime(
						DateUtils.parseDate(patentRegistrationBo.getAuthorizationIssueTime(), AFTConstants.YYYYMMDD));
			}
			if (!StringUtils.isBlank(patentRegistrationBo.getAuthorizationReceiveTime())) {
				patentRegistration.setAuthorizationReceiveTime(
						DateUtils.parseDate(patentRegistrationBo.getAuthorizationReceiveTime(), AFTConstants.YYYYMMDD));
			}
			patentRegistration.setAuthorizationTrackingNumber(patentRegistrationBo.getAuthorizationTrackingNumber());
			patentRegistration.setCertificateExpressCompany(patentRegistrationBo.getCertificateExpressCompany());
			if (!StringUtils.isBlank(patentRegistrationBo.getCertificateIssueTime())) {
				patentRegistration.setCertificateIssueTime(
						DateUtils.parseDate(patentRegistrationBo.getCertificateIssueTime(), AFTConstants.YYYYMMDD));
			}
			if (!StringUtils.isBlank(patentRegistrationBo.getCertificateRecieveTime())) {
				patentRegistration.setCertificateRecieveTime(
						DateUtils.parseDate(patentRegistrationBo.getCertificateRecieveTime(), AFTConstants.YYYYMMDD));
			}
		} catch (ParseException e) {
		}
		patentRegistration.setCertificateTrackingNumber(patentRegistrationBo.getCertificateTrackingNumber());
		patentRegistration.setPid(pid);
		return patentRegistration;
	}

	// 专利申请费用管理
	private Pagination<PatentApplicationFeeBo> getApplicationFeeList(String[] patentApplicationDate,
			Integer locationProvince, Integer pNo, Integer pSize) throws ParseException {
		return patentCostService.getApplicationFeeList(patentApplicationDate, locationProvince, pNo, pSize);
	}

	// 待缴费专利管理
	private Pagination<PatentPendingBo> getManagePendingPaymentList(Integer locationProvince, Integer pNo,
			Integer pSize) {
		return patentInfoService.getManagePendingPaymentList(locationProvince, pNo, pSize);
	}

	// 管理端申请专利列表(专利综合管理)
	private Pagination<PatentManageListBo> getManagePatentList(String contractId, Integer serialNumber,
			String patentNumber, String office, Integer locationProvince, String unitName, Integer patentCatagory,
			String patentName, Integer patentState, String[] createTime, String[] patentApplicationDate, String author,
			String uid, Integer pNo, Integer pSize) throws ParseException {
		return patentInfoService.getManagePatentList(contractId, serialNumber, patentNumber, office, locationProvince,
				unitName, patentCatagory, patentName, patentState, createTime, patentApplicationDate, author, uid, pNo,
				pSize);
	}

	// 缴费截止日期
	private String calDeadline(String s) {
		String[] arr = s.split("-");
		String y = arr[0];
		String m = arr[1];
		String d = arr[2];
		if ("11".equals(arr[0])) {
			m = "01";
			y = String.valueOf(Integer.parseInt(y) + 1);
		} else if ("12".equals(arr[0])) {
			m = "02";
			y = String.valueOf(Integer.parseInt(y) + 1);
		} else {
			m = String.valueOf(Integer.parseInt(m) + 2);
		}
		return y + m + d;
	}

	// 专利状态
	private String switchPatState(Integer s) {
		String state = "";
		if (PatentInfoStatus.CREATE.getCode().equals(s)) {
			state = PatentInfoStatus.CREATE.getDesc();
		} else if (PatentInfoStatus.SIGN.getCode().equals(s)) {
			state = PatentInfoStatus.SIGN.getDesc();
		} else if (PatentInfoStatus.DELIVERD.getCode().equals(s)) {
			state = PatentInfoStatus.DELIVERD.getDesc();
		} else if (PatentInfoStatus.CIRCULATION.getCode().equals(s)) {
			state = PatentInfoStatus.CIRCULATION.getDesc();
		} else if (PatentInfoStatus.COMPOSE.getCode().equals(s)) {
			state = PatentInfoStatus.COMPOSE.getDesc();
		} else if (PatentInfoStatus.ACCEPT.getCode().equals(s)) {
			state = PatentInfoStatus.ACCEPT.getDesc();
		} else if (PatentInfoStatus.REVIEWNOTICE.getCode().equals(s)) {
			state = PatentInfoStatus.REVIEWNOTICE.getDesc();
		} else if (PatentInfoStatus.REVIEWREPLY.getCode().equals(s)) {
			state = PatentInfoStatus.REVIEWREPLY.getDesc();
		} else if (PatentInfoStatus.CORRECTIONNOTICE.getCode().equals(s)) {
			state = PatentInfoStatus.CORRECTIONNOTICE.getDesc();
		} else if (PatentInfoStatus.CORRECTIONREPLY.getCode().equals(s)) {
			state = PatentInfoStatus.CORRECTIONREPLY.getDesc();
		} else if (PatentInfoStatus.AUTHORIZE.getCode().equals(s)) {
			state = PatentInfoStatus.AUTHORIZE.getDesc();
		} else if (PatentInfoStatus.REJECT.getCode().equals(s)) {
			state = PatentInfoStatus.REJECT.getDesc();
		} else if (PatentInfoStatus.LICENSE.getCode().equals(s)) {
			state = PatentInfoStatus.LICENSE.getDesc();
		} else if (PatentInfoStatus.SETTLEMENT.getCode().equals(s)) {
			state = PatentInfoStatus.SETTLEMENT.getDesc();
		} else if (PatentInfoStatus.CREATE.getCode().equals(s)) {
			state = PatentInfoStatus.CREATE.getDesc();
		} else if (PatentInfoStatus.CALLBACK.getCode().equals(s)) {
			state = PatentInfoStatus.CALLBACK.getDesc();
		}
		return state;
	}

	private String handleFile(Result res, HttpServletRequest req, String fileName, List<MultipartFile> files,
			MultipartFile mf) {
		if (!files.isEmpty()) {
			try {
				mf.transferTo(toAdminPrivateFile(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 Map<String, String> disposePatentStatus() {
		Map<String, String> status = new TreeMap<String, String>();
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			for (PatentInfoStatus p : PatentInfoStatus.values()) {
				status.put(p.getCode().toString(), p.getDesc());
				status.remove(PatentInfoStatus.OTHER.getCode().toString());
			}
		} else {
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.CREATE.getCode())) {
				status.put(PatentInfoStatus.CREATE.getCode().toString(), PatentInfoStatus.CREATE.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.SIGN.getCode())) {
				status.put(PatentInfoStatus.SIGN.getCode().toString(), PatentInfoStatus.SIGN.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.DELIVERD.getCode())) {
				status.put(PatentInfoStatus.DELIVERD.getCode().toString(), PatentInfoStatus.DELIVERD.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.CIRCULATION.getCode())) {
				status.put(PatentInfoStatus.CIRCULATION.getCode().toString(), PatentInfoStatus.CIRCULATION.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.COMPOSE.getCode())) {
				status.put(PatentInfoStatus.COMPOSE.getCode().toString(), PatentInfoStatus.COMPOSE.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.ACCEPT.getCode())) {
				status.put(PatentInfoStatus.ACCEPT.getCode().toString(), PatentInfoStatus.ACCEPT.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.REVIEWNOTICE.getCode())) {
				status.put(PatentInfoStatus.REVIEWNOTICE.getCode().toString(), PatentInfoStatus.REVIEWNOTICE.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.REVIEWREPLY.getCode())) {
				status.put(PatentInfoStatus.REVIEWREPLY.getCode().toString(), PatentInfoStatus.REVIEWREPLY.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.CORRECTIONNOTICE.getCode())) {
				status.put(PatentInfoStatus.CORRECTIONNOTICE.getCode().toString(),
						PatentInfoStatus.CORRECTIONNOTICE.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.CORRECTIONREPLY.getCode())) {
				status.put(PatentInfoStatus.CORRECTIONREPLY.getCode().toString(),
						PatentInfoStatus.CORRECTIONREPLY.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.AUTHORIZE.getCode())) {
				status.put(PatentInfoStatus.AUTHORIZE.getCode().toString(), PatentInfoStatus.AUTHORIZE.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.REJECT.getCode())) {
				status.put(PatentInfoStatus.REJECT.getCode().toString(), PatentInfoStatus.REJECT.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.LICENSE.getCode())) {
				status.put(PatentInfoStatus.LICENSE.getCode().toString(), PatentInfoStatus.LICENSE.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.SETTLEMENT.getCode())) {
				status.put(PatentInfoStatus.SETTLEMENT.getCode().toString(), PatentInfoStatus.SETTLEMENT.getDesc());
			}
			if (TokenManager.hasPermission("PatentInfoStatus" + PatentInfoStatus.CALLBACK.getCode())) {
				status.put(PatentInfoStatus.CALLBACK.getCode().toString(), PatentInfoStatus.CALLBACK.getDesc());
			}
		}
		return status;
	}

	private String getProvince(Map<Integer, DistrictGlossory> districtMap, Integer province) {
		DistrictGlossory dg = districtMap.get(province);
		return dg == null ? "未知地区" : dg.getName();
	}

	private Map<Integer, DistrictGlossory> getProvinces() {
		List<DistrictGlossory> districts = districtGlossoryService.list(0);
		Map<Integer, DistrictGlossory> districtMap = new HashMap<>();
		for (DistrictGlossory dg : districts) {
			districtMap.put(dg.getId(), dg);
		}
		return districtMap;
	}
}
