package com.goafanti.copyright.controller;

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

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.admin.service.AdminService;
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.Admin;
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.InputCopyright;
import com.goafanti.copyright.service.CopyrightInfoService;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.user.service.UserService;

@RestController
@RequestMapping(value = "/api/admin/copyright")
public class AdminCopyrightApiController extends CertifyApiController {
	@Resource
	private CopyrightInfoService	copyrightInfoService;
	@Resource
	private UserService				userService;
	@Resource
	private AdminService			adminService;


	@RequestMapping(value = "/circulation", method = RequestMethod.POST)
	public Result circulation(@RequestParam(name = "ids[]", required = false) String[] ids, @Valid InputCopyright ic,
			BindingResult bindingResult, String recordTimeFormattedDate) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					CopyrightFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

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

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

		if (StringUtils.isBlank(ic.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 (CopyrightStatus.DELIVERD.getCode() != ic.getStatus()
				&& CopyrightStatus.CIRCULATION.getCode() != ic.getStatus()
				&& CopyrightStatus.SETTLEMENT.getCode() != ic.getStatus()) {
			res.getError().add(buildError(ErrorConstants.STATUS_ERROR, "仅派单、流转、结款可操作!"));
			return res;
		}

		CopyrightLog cl = new CopyrightLog();
		BeanUtils.copyProperties(ic, cl);

		res.setData(copyrightInfoService.batchCirculation(ids, recordTimeFormattedDate, cl));
		return res;
	}

	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public Result newApply(@Valid InputCopyright inputInfo, BindingResult bindingResult) {
		Result res = new Result();
		if (handleBindingError(res, bindingResult)) {
			return res;
		}
		if (!checkAdminLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(inputInfo.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}
		if (StringUtils.isBlank(inputInfo.getSalesman())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到营销员", "营销员"));
			return res;
		}
		User curUser = userService.selectByPrimaryKey(inputInfo.getUid());
		if (!checkCertify(res, curUser)) {
			return res;
		}
		String salesman = inputInfo.getSalesman();
		CopyrightInfo ci = new CopyrightInfo();
		BeanUtils.copyProperties(inputInfo, ci);
		ci.setUid(curUser.getId());
		copyrightInfoService.saveCopyright(ci, salesman);
		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 (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到软著", "软著申请id"));
			return res;
		}
		CopyrightInfo oci = copyrightInfoService.selectByPrimaryKey(id);
		if (oci == null) {
			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);
		BeanUtils.copyProperties(inputInfo, cl);
		ci.setId(oci.getId());
		ci.setUid(oci.getUid());
		if (CopyrightStatus.CIRCULATION.getCode() == ci.getStatus()) {
			ci.setStatus(CopyrightStatus.DELIVERD.getCode());
		}

		cl.setCid(oci.getId());
		cl.setOperator(TokenManager.getAdminId());
		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 (!checkAdminLogin(res)) {
			return res;
		}
		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著id"));
			return res;
		}
		CopyrightInfo ci = copyrightInfoService.selectByPrimaryKey(id);
		if (ci == null) {
			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 = "/delete", method = RequestMethod.POST)
	public Result delete(@RequestParam(name = "id[]", required = false) String[] ids) {
		Result res = new Result();
		if (!checkAdminLogin(res)) {
			return res;
		}
		if (ids == null || ids.length < 1) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", ""));
		} else {
			res.setData(copyrightInfoService.batchDeleteByPrimaryKey(Arrays.asList(ids)));
		}
		return res;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result list(String contractId, Integer province, String unitName, String uid, 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();
		if (!checkAdminLogin(res)) {
			return res;
		}
		res.setData(copyrightInfoService.listMyCopyrightInfo(contractId, province, unitName, copyrightName,
				CopyrightStatus.getStatus(status), createTime, acceptTime, authTime, getPageNo(pageNo),
				getPageSize(pageSize), uid));
		return res;
	}

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

	@RequestMapping(value = "/logs", method = RequestMethod.GET)
	public Result logs(String id) {
		Result res = new Result();
		if (!checkAdminLogin(res)) {
			return res;
		}
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "软著申请id"));
		} else {
			res.setData(copyrightInfoService.findLogsByPrimaryKey(id));
		}
		return res;
	}

	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public Result download(String id, String sign, HttpServletResponse response) {
		Result res = new Result();
		if (!checkAdminLogin(res)) {
			return res;
		}
		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "软著id"));
			return res;
		}
		CopyrightInfoDetail ci = copyrightInfoService.findByPrimaryKey(id);
		if (ci == null) {
			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 = "/status", method = RequestMethod.GET)
	public Result status() {
		Result res = new Result();
		if (!checkAdminLogin(res)) {
			return res;
		}
		res.setData(disposeStatus());
		return res;
	}

	/**
	 * 软著咨询师下拉
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getConsultant", method = RequestMethod.GET)
	public Result getConsultant() {
		Result res = new Result();
		List<Admin> list = adminService.selectCopyrightConsultant();
		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.selectCopyrightPrincipal();
		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 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;
	}

	private Map<String, String> disposeStatus() {
		Map<String, String> status = new TreeMap<String, String>();
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			for (CopyrightStatus p : CopyrightStatus.values()) {
				status.put(p.getCode().toString(), p.getDesc());
				status.remove(CopyrightStatus.OTHER.getCode().toString());
			}
		} else {
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.CREATE.getCode())) {
				status.put(CopyrightStatus.CREATE.getCode().toString(), CopyrightStatus.CREATE.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.SIGN.getCode())) {
				status.put(CopyrightStatus.SIGN.getCode().toString(), CopyrightStatus.SIGN.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.DELIVERD.getCode())) {
				status.put(CopyrightStatus.DELIVERD.getCode().toString(), CopyrightStatus.DELIVERD.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.SUBMIT.getCode())) {
				status.put(CopyrightStatus.SUBMIT.getCode().toString(), CopyrightStatus.SUBMIT.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.CIRCULATION.getCode())) {
				status.put(CopyrightStatus.CIRCULATION.getCode().toString(), CopyrightStatus.CIRCULATION.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.ACCEPT.getCode())) {
				status.put(CopyrightStatus.ACCEPT.getCode().toString(), CopyrightStatus.ACCEPT.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.AMEND.getCode())) {
				status.put(CopyrightStatus.AMEND.getCode().toString(), CopyrightStatus.AMEND.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.REJECT.getCode())) {
				status.put(CopyrightStatus.REJECT.getCode().toString(), CopyrightStatus.REJECT.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.AUTHORIZED.getCode())) {
				status.put(CopyrightStatus.AUTHORIZED.getCode().toString(), CopyrightStatus.AUTHORIZED.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.SETTLEMENT.getCode())) {
				status.put(CopyrightStatus.SETTLEMENT.getCode().toString(), CopyrightStatus.SETTLEMENT.getDesc());
			}
			if (TokenManager.hasPermission("CopyrightStatus" + CopyrightStatus.CALLBACK.getCode())) {
				status.put(CopyrightStatus.CALLBACK.getCode().toString(), CopyrightStatus.CALLBACK.getDesc());
			}
		}
		return status;
	}
}
