package com.goafanti.patent.controller;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.goafanti.admin.service.AdminService;
import com.goafanti.admin.service.AttachmentService;
import com.goafanti.cognizance.service.OrgIntellectualPropertyService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.PatentInfoFields;
import com.goafanti.common.enums.PatentInfoStatus;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.Attachment;
import com.goafanti.common.model.PatentInfo;
import com.goafanti.common.model.PatentLog;
import com.goafanti.common.model.User;
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.InputPatentInfo;
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;

@Controller
@RequestMapping(value = "/api/user/patent")
public class UserPatentApiController 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 OrganizationIdentityService		organizationIdentityService;
	

	@Value(value = "${upload.private.path}")
	private String							uploadPrivatePath	= null;

	/**
	 * 专利相关材料上传
	 * 
	 * @param req
	 * @param uid
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result upload(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.PATENT_WRITING || attachmentType == AttachmentType.AUTHORIZATION_NOTICE
				|| attachmentType == AttachmentType.PATENT_CERTIFICATE) {
			res.setData(handleFiles(res, "/patent/", true, req, sign, TokenManager.getUserId()));
		} else if (attachmentType == AttachmentType.PATENT_PRORY_STATEMENT) {
			res.setData(handleFile(res, "/identity/", true, req, sign));
		} 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 (!checkUserLogin(res)) {
			return res;
		}
		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();
		if (!checkUserLogin(res)) {
			return res;
		}
		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;
	}

	/**
	 * 用户端专利申请
	 */
	@RequestMapping(value = "/clientApplyPatent", method = RequestMethod.POST)
	public Result clientApplyPatent(@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 (!checkUserLogin(res)) {
			return res;
		}

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

		String aid = curUser.getAid();
		PatentInfo pi = new PatentInfo();
		BeanUtils.copyProperties(patentInfo, pi);
		pi.setUid(TokenManager.getUserId());
		res.setData(patentInfoService.insertPatentInfo(pi, aid));
		return res;
	}

	/**
	 * 用户端专利详情
	 * 
	 */
	@RequestMapping(value = "/clientPatentInfo", method = RequestMethod.GET)
	public Result clientPatentInfo(String pid) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "专利ID"));
		} else {
			PatentInfo pi = patentInfoService.selectByPrimaryKey(pid);
			if (null != pi.getUid() && pi.getUid().equals(TokenManager.getUserId())) {
				res.setData(pi);
			} else {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "专利ID"));
			}
		}
		res.setData(patentInfoService.selectByPrimaryKey(pid));
		return res;
	}

	/**
	 * 用户端申请专利列表
	 */
	@RequestMapping(value = "/clientApplyList", method = RequestMethod.GET)
	public Result clientApplyList(String patentNumber, String patentName, Integer patentCatagory, Integer patentState,
			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(getClientApplyList(res, patentNumber, patentName, patentCatagory, patentState, pNo, pSize));
		return res;
	}

	/**
	 * 用户端logs
	 */
	@RequestMapping(value = "/patentProcess", method = RequestMethod.GET)
	public Result patentProcess(String pid) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "专利ID"));
			return res;
		}
		PatentInfo pi = patentInfoService.selectByPrimaryKey(pid);
		if (null != pi.getUid() && pi.getUid().equals(TokenManager.getUserId())) {
			List<PatentLog> list = patentLogService.selectProcessByPid(pid);
			for (Iterator<PatentLog> log = list.iterator(); log.hasNext();) {
				Integer state = log.next().getState();
				if (PatentInfoStatus.getStatus(state) == PatentInfoStatus.SIGN
						|| PatentInfoStatus.getStatus(state) == PatentInfoStatus.CIRCULATION
						|| PatentInfoStatus.getStatus(state) == PatentInfoStatus.SETTLEMENT) {
					log.remove();
				}
			}

			res.setData(list);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "专利id"));
		}
		return res;
	}

	/**
	 * 用户确认申报材料
	 * 
	 * @return
	 */
	@RequestMapping(value = "/clientConfirm", method = RequestMethod.POST)
	public Result clientConfirmApplicationMaterials(String pid) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(pid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "专利d"));
			return res;
		}
		PatentInfo p = new PatentInfo();
		p.setId(pid);
		p.setConfirmState(1);
		res.setData(patentInfoService.updateByPrimaryKeySelective(p));
		return res;
	}

	/**
	 * 获取公司
	 *//*
		 * @RequestMapping(value = "/getUnitNames", method = RequestMethod.GET)
		 * public Result getUnitNames() { Result res = new Result();
		 * List<OrganizationIdentity> list =
		 * organizationIdentityServivce.selectAllOrgIndentity(); Map<String,
		 * String> map = new TreeMap<String, String>(); for
		 * (OrganizationIdentity o : list) { map.put(o.getUid(),
		 * o.getUnitName()); } res.setData(map); return res; }
		 */

	/**
	 * 获取管理员
	 */
	@RequestMapping(value = "/getAdmin", method = RequestMethod.GET)
	public Result getAdmin() {
		Result res = new Result();
		List<Admin> admin = adminService.selectAllAdmin();
		Map<String, String> map = new LinkedHashMap<String, String>();
		for (Admin a : admin) {
			map.put(a.getId(), a.getName());
		}
		res.setData(map);
		return res;
	}

	// 用户端申请专利列表
	private Pagination<PatentInfo> getClientApplyList(Result res, String patentNumber, String patentName,
			Integer patentCatagory, Integer patentState, Integer pNo, Integer pSize) {
		return patentInfoService.getClientApplyList(TokenManager.getUserId(), patentNumber, patentName, patentCatagory,
				patentState, pNo, pSize);
	}
	
	/**
	 * 查询部门下的员工
	 */
	@RequestMapping(value = "/selectDepartmentStaff", method = RequestMethod.GET)
	public Result selectDepartmentStaff(String departmentId,String name){
		Result res = new Result();
		if (StringUtils.isBlank(departmentId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "部门"));
			return res;
		}
		return res.data(adminService.selectDepartmentStaff(departmentId,name));
	}
}
