package com.goafanti.contract.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.validation.Valid;

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

import com.goafanti.admin.service.AdminService;
import com.goafanti.cognizance.service.OrgCognizanceService;
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.ContractFields;
import com.goafanti.common.enums.ContractLogFields;
import com.goafanti.common.enums.ContractStatus;
import com.goafanti.common.model.Contract;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.contract.bo.InputContactLog;
import com.goafanti.contract.bo.InputContract;
import com.goafanti.contract.bo.InputSaveContract;
import com.goafanti.contract.service.ContractLogService;
import com.goafanti.contract.service.ContractService;
import com.goafanti.copyright.service.CopyrightInfoService;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.patent.service.PatentInfoService;
import com.goafanti.techproject.service.TechProjectService;
import com.goafanti.user.service.UserService;

@RestController
@RequestMapping(value = "/api/admin/contract")
public class AdminContractApiController extends CertifyApiController {
	@Resource
	private ContractService			contractService;
	@Resource
	private ContractLogService		contractLogService;
	@Resource
	private UserService				userService;
	@Resource
	private OrgCognizanceService	orgCognizanceService;
	@Resource
	private AdminService			adminService;
	@Resource
	private PatentInfoService		patentInfoService;
	@Resource
	private CopyrightInfoService	copyrightInfoService;
	@Resource
	private TechProjectService		techProjectService;

	private static final Integer	SECTION_YEAR	= 4;

	/**
	 * 批量删除合同
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Result delete(@RequestParam(name = "ids[]", required = false) String[] ids) {
		Result res = new Result();
		if (ids == null || ids.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
		} else {
			res.setData(contractService.deleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	/**
	 * 合同编号下拉
	 */
	@RequestMapping(value = "/serialNumber", method = RequestMethod.GET)
	public Result contractSerialNumber() {
		Result res = new Result();
		res.setData(contractService.selectContractSerialNumber());
		return res;
	}

	/**
	 * to update 18
	 * 合同管理--创建高企认定申请
	 */
	@RequestMapping(value = "/createCognizance", method = RequestMethod.POST)
	public Result createCognizance(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		Contract c = contractService.selectByPrimaryKey(id);
		if (null == c) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "合同ID"));
			return res;
		}
		/*if (!c.getCognizanceStatus().equals(ContractBusinessStatus.UNCREATE.getCode())) {
			res.getError().add(buildError(ErrorConstants.CONTRACT_COGNIZANCE_CREATED, "", "当前合同高企认定申请已创建,无法重复创建！"));
			return res;
		}

		if (null == c.getCognizanceYear() || c.getCognizanceYear().equals(0)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到高企认定申请年份", "高企认定申请年份"));
			return res;
		}

		if (null != c.getCognizanceYear() && !c.getCognizanceYear().equals(0)) {
			if (!disposeCog(c.getId(), c.getCognizanceYear(), c.getUid(), res).getError().isEmpty()) {
				return res;
			}
		}*/

		orgCognizanceService.insertContractRecord(c);
		return res;
	}

	/**
	 * to update 18
	 * 合同管理--批量创建科技项目
	 */
	@RequestMapping(value = "/createTechProject", method = RequestMethod.POST)
	public Result createTechProject(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		Contract c = contractService.selectByPrimaryKey(id);
		if (null == c) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "合同ID"));
			return res;
		}
		/*if (!c.getTechProjectStatus().equals(ContractBusinessStatus.UNCREATE.getCode())) {
			res.getError().add(buildError(ErrorConstants.CONTRACT_TECHPROJECT_CREATED, "", "当前合同科技项目申请已创建,无法重复创建！"));
			return res;
		}

		if (c.getTechProjectNum() >= 1 && c.getTechProjectNum() <= 30) {
			techProjectService.batchInsertContractRecord(c);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著数量"));
		}*/
		return res;
	}

	/**
	 * to update 18
	 * 合同管理--批量创建软著
	 */
	@RequestMapping(value = "/createCopyright", method = RequestMethod.POST)
	public Result createCopyright(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		Contract c = contractService.selectByPrimaryKey(id);
		if (null == c) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "合同ID"));
			return res;
		}
		/*if (!c.getCopyrightStatus().equals(ContractBusinessStatus.UNCREATE.getCode())) {
			res.getError().add(buildError(ErrorConstants.CONTRACT_COPYRIGHT_CREATED, "", "当前合同软著申请已创建,无法重复创建！"));
			return res;
		}

		if (c.getCopyrightNum() >= 1 && c.getCopyrightNum() <= 30) {
			copyrightInfoService.batchInsertContractRecord(c);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著数量"));
		}*/
		return res;
	}

	/**
	 * to update 18
	 * 合同管理--创建专利
	 */
	@RequestMapping(value = "/createPatent", method = RequestMethod.POST)
	public Result createPatent(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		Contract c = contractService.selectByPrimaryKey(id);
		if (null == c) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "合同ID"));
			return res;
		}
		/*if (!c.getPatentStatus().equals(ContractBusinessStatus.UNCREATE.getCode())) {
			res.getError().add(buildError(ErrorConstants.CONTRACT_PATENT_CREATED, "", "当前合同专利申请已创建,无法重复创建！"));
			return res;
		}

		if (c.getPatentNum() >= 1 && c.getPatentNum() <= 30) {
			patentInfoService.batchInsertContractRecord(c);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "专利数量"));
		}*/
		return res;
	}

	/**
	 * 合同详情-科技项目列表
	 */
	@RequestMapping(value = "/techProject", method = RequestMethod.GET)
	public Result listTechProject(String contractId) {
		Result res = new Result();
		if (StringUtils.isBlank(contractId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		res.setData(techProjectService.listContractTechProjectByContractId(contractId));
		return res;
	}

	/**
	 * 合同详情-高企记录
	 */
	@RequestMapping(value = "/cognizance", method = RequestMethod.GET)
	public Result cognizance(String contractId) {
		Result res = new Result();
		if (StringUtils.isBlank(contractId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		res.setData(orgCognizanceService.selectContractCognizanceByContractId(contractId));
		return res;
	}

	/**
	 * 合同详情-软著列表
	 */
	@RequestMapping(value = "/copyright", method = RequestMethod.GET)
	public Result listCopyright(String contractId) {
		Result res = new Result();
		if (StringUtils.isBlank(contractId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		res.setData(copyrightInfoService.listContractCopyrightByContractId(contractId));
		return res;
	}

	/**
	 * 合同详情-专利列表
	 */
	@RequestMapping(value = "/patent", method = RequestMethod.GET)
	public Result listPatent(String contractId) {
		Result res = new Result();
		if (StringUtils.isBlank(contractId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		res.setData(patentInfoService.listContractPatentByContractId(contractId));
		return res;
	}

	/**
	 * 合同分发流转人员下拉
	 */
	@RequestMapping(value = "/principal", method = RequestMethod.GET)
	public Result getPrincipal() {
		Result res = new Result();
		res.setData(adminService.selectContractManager());
		return res;
	}

	/**
	 * 合同列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result listContract(String contractId, Integer serialNumber, Integer type, Integer status,
			String startDateFormattedDate, String endDateFormattedDate, Integer province, String unitName, String uid,
			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(contractService.getManageList(contractId, serialNumber, type, status, startDateFormattedDate,
				endDateFormattedDate, province, unitName, uid, pNo, pSize));
		return res;
	}

	/**
	 * 新增合同(保存)
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public Result applyContract(@Valid InputSaveContract contract, BindingResult bindingResult) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					ContractFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		if (StringUtils.isBlank(contract.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}

		if (null == contract.getType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "合同类型"));
			return res;
		}

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

		if (null != contract.getCognizanceYear() && !contract.getCognizanceYear().equals(0)) {
			if (!disposeCog(contract.getId(), contract.getCognizanceYear(), contract.getUid(), res).getError().isEmpty()) {
				return res;
			}
		}

		Contract c = new Contract();
		BeanUtils.copyProperties(contract, c);
		if (StringUtils.isBlank(contract.getId())) {
			res.setData(contractService.saveManageContract(c));
		} else {
			Contract ct = contractService.selectByPrimaryKey(c.getId());
			if (null != ct && !ContractStatus.COMPLETE.getCode().equals(ct.getStatus())) {
				res.setData(contractService.updateByPrimaryKeySelective(c));
			} else {
				res.getError().add(buildError("", "当前合同已完成(结款)，无法操作！"));
			}
		}
		return res;
	}

	/**
	 * 新增--提交合同
	 */
	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public Result submitContract(@Valid InputContract ic, BindingResult bindingResult, String signDateFormattedDate,
			@RequestParam(name = "principals[]", required = false) String[] principals) {
		Result res = new Result();
		if (null == principals || principals.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到流转分发用户", "流转分发用户"));
			return res;
		}

		if (StringUtils.isBlank(signDateFormattedDate)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同签订时间", "合同签订时间"));
			return res;
		}

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

		if (null == ic.getType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "合同类型"));
			return res;
		}

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

		if (null != ic.getCognizanceYear() && !ic.getCognizanceYear().equals(0)) {
			if (!disposeCog(ic.getId(), ic.getCognizanceYear(), ic.getUid(), res).getError().isEmpty()) {
				return res;
			}
		}

		Contract c = new Contract();
		BeanUtils.copyProperties(ic, c);
		if (StringUtils.isBlank(ic.getId())) {
			contractService.insertManageSubmit(c, principals, signDateFormattedDate);
		} else {
			Contract ct = contractService.selectByPrimaryKey(c.getId());
			if (null != ct && !ContractStatus.COMPLETE.getCode().equals(ct.getStatus())) {
				contractService.updateSubmit(c, principals, signDateFormattedDate);
			} else {
				res.getError().add(buildError("", "当前合同已完成(结款)，无法操作！"));
			}
		}
		return res;
	}

	/**
	 * 合同详情
	 */
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public Result detail(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		res.setData(contractService.selectContractDetail(id));
		return res;
	}

	/**
	 * 合同流转日志
	 */
	@RequestMapping(value = "/log", method = RequestMethod.GET)
	public Result log(String cid) {
		Result res = new Result();
		if (StringUtils.isBlank(cid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}
		res.setData(contractLogService.selectContractLogByCid(cid));
		return res;
	}

	/**
	 * 合同流转状态下拉
	 */
	@RequestMapping(value = "/status", method = RequestMethod.GET)
	public Result status() {
		Result res = new Result();
		res.setData(disposeStatus());
		return res;
	}

	/**
	 * 流转分发
	 */
	@RequestMapping(value = "/circulation", method = RequestMethod.POST)
	public Result circulation(@Valid InputContactLog icl, BindingResult bindingResult, String recordTimeFormattedDate,
			@RequestParam(name = "principals[]", required = false) String[] principals) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					ContractLogFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

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

		if (principals.length < 1 || null == principals) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到流转分发用户", "流转分发用户"));
			return res;
		}

		if (StringUtils.isBlank(icl.getCid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同ID", "合同ID"));
			return res;
		}

		if (null == icl.getStatus()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到合同流转分发状态", "合同流转分发状态"));
			return res;
		}

		Contract ct = contractService.selectByPrimaryKey(icl.getCid());
		if (null != ct && !ContractStatus.COMPLETE.getCode().equals(ct.getStatus())) {
			contractLogService.insertCirculation(icl, principals, recordTimeFormattedDate);
		} else {
			res.getError().add(buildError("", "当前合同已完成(结款)，无法操作！"));
		}
		return res;
	}

	//to update 18
	@SuppressWarnings("unused")
	private Result disposeCog(String id, Integer year, String uid, Result res) {
		Integer latelyYear = orgCognizanceService.selectLatelyRecordYear(uid);
		if (null != latelyYear && year - latelyYear < SECTION_YEAR) {
			res.getError()
					.add(buildError(ErrorConstants.STATUS_ERROR, "高企认定申请中或认定未到期！无法提交新申请!", "高企认定申请中或认定未到期！无法提交新申请！"));
			return res;
		}
		
		Contract c = contractService.findLatelyRecordByUid(uid);
		boolean flag = Boolean.TRUE;
		/*if (null != c) {
			if (StringUtils.isNotBlank(id)) {
				if (null != c.getCognizanceYear() && year - c.getCognizanceYear() < SECTION_YEAR
						&& !id.equals(c.getId())) {
					flag = false;
				}
			} else {
				if (null != c.getCognizanceYear() && year - c.getCognizanceYear() < SECTION_YEAR) {
					flag = false;
				}
			}
		}*/
		if (!flag) {
			res.getError().add(buildError(ErrorConstants.CONTRACT_YEAR_SECTION));
		}

		return res;
	}

	private Object disposeStatus() {
		Map<String, String> status = new TreeMap<String, String>();
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			for (ContractStatus p : ContractStatus.values()) {
				status.put(p.getCode().toString(), p.getDesc());
				status.remove(ContractStatus.CREATE.getCode().toString());
				status.remove(ContractStatus.OTHER.getCode().toString());
			}
		} else {
			/*
			 * if (TokenManager.hasPermission("ContractStatus" +
			 * ContractStatus.CREATE.getCode())) {
			 * status.put(ContractStatus.CREATE.getCode().toString(),
			 * ContractStatus.CREATE.getDesc()); } if
			 * (TokenManager.hasPermission("ContractStatus" +
			 * ContractStatus.SIGN.getCode())) {
			 * status.put(ContractStatus.SIGN.getCode().toString(),
			 * ContractStatus.SIGN.getDesc()); }
			 */
			if (TokenManager.hasPermission("ContractStatus" + ContractStatus.CIRCULATION.getCode())) {
				status.put(ContractStatus.CIRCULATION.getCode().toString(), ContractStatus.CIRCULATION.getDesc());
			}
			if (TokenManager.hasPermission("ContractStatus" + ContractStatus.COMPLETE.getCode())) {
				status.put(ContractStatus.COMPLETE.getCode().toString(), ContractStatus.COMPLETE.getDesc());
			}
		}
		return status;
	}

}
