package com.goafanti.copyright.controller;


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

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
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.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.CopyrightFields;
import com.goafanti.common.enums.CopyrightStatus;
import com.goafanti.common.model.CopyrightInfo;
import com.goafanti.common.model.CopyrightLog;
import com.goafanti.common.model.User;
import com.goafanti.copyright.bo.CopyrightInfoDetail;
import com.goafanti.copyright.bo.CopyrightLogBo;
import com.goafanti.copyright.bo.InputCopyright;
import com.goafanti.copyright.service.CopyrightInfoService;
import com.goafanti.core.shiro.token.TokenManager;

@RestController
@RequestMapping(value = "/api/user/copyright")
public class UserCopyrightApiController extends CertifyApiController {
	@Resource
	private CopyrightInfoService copyrightInfoService;

	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public Result newApply(@Valid InputCopyright inputInfo, BindingResult bindingResult) {
		Result res = new Result();
		if (handleBindingError(res, bindingResult)) {
			return res;
		}
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		CopyrightInfo ci = new CopyrightInfo();
		BeanUtils.copyProperties(inputInfo, ci);
		ci.setUid(curUser.getId());
		ci.setPrincipal(curUser.getAid());
		copyrightInfoService.insert(ci, curUser.getAid());
		res.setData(ci);
		return res;
	}

	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public Result modify(String id, @Valid InputCopyright inputInfo, BindingResult bindingResult) {
		Result res = new Result();
		if (handleBindingError(res, bindingResult)) {
			return res;
		}
		if (!checkUserLogin(res)) {
			return res;
		}
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到软著", "软著申请id"));
			return res;
		}
		CopyrightInfo oci = copyrightInfoService.selectByPrimaryKey(id);
		if (oci == null || !oci.getUid().equals(curUser.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "找不到软著", "软著申请"));
			return res;
		}
		
		if (CopyrightStatus.CALLBACK.getCode() == oci.getStatus()){
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前记录已退单，无法修改！"));
			return res;
		}
		
		if (CopyrightStatus.SETTLEMENT.getCode() == oci.getStatus()){
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前记录已结款，无法修改！"));
			return res;
		}

		CopyrightInfo ci = new CopyrightInfo();
		CopyrightLog cl = new CopyrightLog();
		BeanUtils.copyProperties(oci, ci);
		BeanUtils.copyProperties(inputInfo, ci);
		ci.setId(oci.getId());
		ci.setUid(oci.getUid());
		copyrightInfoService.updateByPrimaryKeySelective(ci, cl);
		res.setData(1);
		return res;
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result upload(String id, String sign, HttpServletRequest req) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著id"));
			return res;
		}
		CopyrightInfo ci = copyrightInfoService.selectByPrimaryKey(id);
		if (ci == null || !curUser.getId().equals(ci.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著id"));
			return res;
		}
		
		if (CopyrightStatus.CALLBACK.getCode() == ci.getStatus()){
			res.getError().add(buildError(ErrorConstants.RECORD_CALLBACK, "当前记录已退单，无法修改！"));
			return res;
		}
		
		if (CopyrightStatus.SETTLEMENT.getCode() == ci.getStatus()){
			res.getError().add(buildError(ErrorConstants.RECORD_SETTLEMENT, "当前记录已结款，无法修改！"));
			return res;
		}
		
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.COPYRIGHT_APPLY || attachmentType == AttachmentType.COPYRIGHT_AUTH) {
			String filePath = handleFile(res, true, req, attachmentType.getCode(), ci.getUid(), ci.getId());
			if (attachmentType == AttachmentType.COPYRIGHT_APPLY) {
				ci.setApplicationUrl(filePath);
			} else if (attachmentType == AttachmentType.COPYRIGHT_AUTH) {
				ci.setCertificateUrl(filePath);
			}
			copyrightInfoService.updateByPrimaryKey(ci);
			res.setData(filePath);
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result list(String contractId, Integer province, String unitName, String copyrightName, String status, String pageNo,
			String pageSize, @RequestParam(name = "createTime[]", required = false) String[] createTime,
			@RequestParam(name = "acceptTime[]", required = false) String[] acceptTime,
			@RequestParam(name = "authTime[]", required = false) String[] authTime) {
		Result res = new Result();
		res.setData(copyrightInfoService.listMyCopyrightInfo(contractId, province, unitName, copyrightName,
				CopyrightStatus.getStatus(status), createTime, acceptTime, authTime, getPageNo(pageNo),
				getPageSize(pageSize), TokenManager.getUserId()));
		return res;
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public Result detail(String id) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "公司"));
		} else {
			CopyrightInfoDetail cid = copyrightInfoService.findByPrimaryKey(id);
			if (cid.getUid().equals(TokenManager.getUserId())) {
				res.setData(cid);
			} else {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "公司"));
			}
		}
		return res;
	}

	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public Result download(String id, String sign, HttpServletResponse response) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		User curUser = TokenManager.getUserToken();
		if (!checkCertify(res, curUser)) {
			return res;
		}
		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著id"));
			return res;
		}
		CopyrightInfoDetail ci = copyrightInfoService.findByPrimaryKey(id);
		if (ci == null || !curUser.getId().equals(ci.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著id"));
			return res;
		}
		AttachmentType attachmentType = AttachmentType.getField(sign);
		if (attachmentType == AttachmentType.COPYRIGHT_APPLY || attachmentType == AttachmentType.COPYRIGHT_AUTH) {
			if (attachmentType == AttachmentType.COPYRIGHT_APPLY) {
				downloadFile(response, ci.getApplicationUrlDownloadFileName(), ci.getApplicationUrl());
			} else if (attachmentType == AttachmentType.COPYRIGHT_AUTH) {
				downloadFile(response, ci.getCertificateUrlDownloadFileName(), ci.getCertificateUrl());
			}
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}
		return res;
	}

	@RequestMapping(value = "/logs", method = RequestMethod.GET)
	public Result logs(String id) {
		Result res = new Result();
		if (!checkUserLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "软著申请id"));
			return res;
		}
		CopyrightInfo oci = copyrightInfoService.selectByPrimaryKey(id);
		if (oci == null || !oci.getUid().equals(TokenManager.getUserId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著申请id"));
			return res;
		}
		List<CopyrightLogBo> list = copyrightInfoService.findLogsByPrimaryKey(id);
		for (Iterator<CopyrightLogBo> log = list.iterator() ; log.hasNext();) {
			Integer status = log.next().getStatus();
			if (CopyrightStatus.getStatus(status) == CopyrightStatus.SIGN 
					|| CopyrightStatus.getStatus(status) == CopyrightStatus.CIRCULATION
					|| CopyrightStatus.getStatus(status) == CopyrightStatus.SETTLEMENT) {
				log.remove();
			}
		}
		res.setData(list);
		return res;
	}
	
	

	

	private boolean handleBindingError(Result res, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			for (FieldError fe : bindingResult.getFieldErrors()) {
				Class<?> clazz = bindingResult.getFieldType(fe.getField());
				if (clazz != null && "java.util.Date".equals(clazz.getName())) {
					res.getError()
							.add(buildError(ErrorConstants.PARAM_PATTERN_ERROR, "日期格式错误",
									CopyrightFields.getFieldDesc(fe.getField()), AFTConstants.YYYYMMDDHHMMSS)
											.field(fe.getField()));
				} else {
					res.getError()
							.add(buildErrorByMsg(fe.getDefaultMessage(), CopyrightFields.getFieldDesc(fe.getField()))
									.field(fe.getField()));
				}
			}
			return true;
		}
		return false;
	}
	
	
}
