package com.goafanti.contract.controller;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

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.cognizance.service.OrgCognizanceService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.ContractFields;
import com.goafanti.common.enums.ContractStatus;
import com.goafanti.common.model.Contract;
import com.goafanti.common.model.ContractLog;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.StringUtils;
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;

@RestController
@RequestMapping(value = "/api/user/contract")
public class UserContractApiController extends CertifyApiController {
	@Resource
	private ContractService			contractService;
	@Resource
	private OrgCognizanceService	orgCognizanceService;
	@Resource
	private ContractLogService		contractLogService;
	@Resource
	private CopyrightInfoService	copyrightInfoService;
	@Resource
	private TechProjectService		techProjectService;
	@Resource
	private PatentInfoService		patentInfoService;

	private static final Integer	SECTION_YEAR	= 4;

	/**
	 * 合同详情-科技项目列表
	 */
	@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 = "/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;
		}
		List<ContractLog> list = contractLogService.selectContractLogByCid(cid);

		for (Iterator<ContractLog> log = list.iterator(); log.hasNext();) {
			Integer status = log.next().getStatus();
			if (ContractStatus.getStatus(status) == ContractStatus.CIRCULATION) {
				log.remove();
			}
		}

		res.setData(list);
		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 = "/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 = "/update", method = RequestMethod.POST)
	public Result update(@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;
		}
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}

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

		if (null == contract.getType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "合同类型"));
			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);
		Contract ct = contractService.selectByPrimaryKey(c.getId());
		if (null != ct && ContractStatus.CREATE.getCode().equals(ct.getStatus())) {
			res.setData(contractService.updateByPrimaryKeySelective(c));
		} else {
			res.getError().add(buildError("", "当前合同为非草稿状态，无法操作！"));
		}
		return res;
	}

	/**
	 * 提交申请新合同
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public Result apply(@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 (null == contract.getType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "合同类型"));
			return res;
		}

		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		if (null != contract.getCognizanceYear() && !contract.getCognizanceYear().equals(0)) {
			if (!disposeCog(null, contract.getCognizanceYear(), contract.getUid(), res).getError().isEmpty()) {
				return res;
			}
		}

		Contract c = new Contract();
		BeanUtils.copyProperties(contract, c);

		contractService.saveContract(c);
		return res;
	}

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

	//to udpate 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;
	}
}
