package com.goafanti.portal.controller;

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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.goafanti.achievement.bo.InputAchievementOrder;
import com.goafanti.achievement.service.AchievementOrderLogService;
import com.goafanti.achievement.service.AchievementOrderService;
import com.goafanti.achievement.service.AchievementService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AchievementAuditStatus;
import com.goafanti.common.enums.AchievementOrderFields;
import com.goafanti.common.enums.AchievementOrderStatus;
import com.goafanti.common.enums.AchievementReleaseStatus;
import com.goafanti.common.enums.AttachmentType;
import com.goafanti.common.enums.DeleteStatus;
import com.goafanti.common.enums.DemandAuditStatus;
import com.goafanti.common.enums.DemandOrderFields;
import com.goafanti.common.enums.DemandOrderStatus;
import com.goafanti.common.enums.DemandReleaseStatus;
import com.goafanti.common.model.Achievement;
import com.goafanti.common.model.AchievementOrder;
import com.goafanti.common.model.AchievementOrderLog;
import com.goafanti.common.model.Demand;
import com.goafanti.common.model.DemandOrder;
import com.goafanti.common.model.DemandOrderLog;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demand.bo.InputDemandOrder;
import com.goafanti.demand.service.DemandOrderLogService;
import com.goafanti.demand.service.DemandOrderService;
import com.goafanti.demand.service.DemandService;

@RestController
@RequestMapping(value = "/api/user/portal/order")
public class PortalOrderApiController extends CertifyApiController {
	@Resource
	private DemandOrderService			demandOrderService;
	@Resource
	private DemandService				demandService;
	@Resource
	private DemandOrderLogService		demandOrderLogService;
	@Resource
	private AchievementService			achievementService;
	@Resource
	private AchievementOrderLogService	achievementOrderLogService;
	@Resource
	private AchievementOrderService		achievementOrderService;

	/**
	 * 科技成果Log
	 */
	@RequestMapping(value = "/achievementOrderLog", method = RequestMethod.GET)
	public Result achievementOrderLog(String achievementOrderId) {
		Result res = new Result();

		if (StringUtils.isEmpty(achievementOrderId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "科技成果订单ID"));
			return res;
		}
		AchievementOrder order = achievementOrderService.selectByPrimaryKey(achievementOrderId);
		if (null != order && TokenManager.getUserId().equals(order.getUid())) {
			res.setData(achievementOrderLogService.selectAchievementOrderLogByAchievementOrderId(achievementOrderId));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技成果订单ID"));
		}

		return res;
	}

	/**
	 * 关闭科技成果订单
	 */
	@RequestMapping(value = "/achievementShutdown", method = RequestMethod.POST)
	public Result achevementShutdown(String id) {
		Result res = new Result();

		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到订单ID", "订单ID"));
			return res;
		}

		AchievementOrder order = achievementOrderService.selectByPrimaryKey(id);
		if (null == order) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "订单ID"));
			return res;
		}

		if (!AchievementOrderStatus.UNPAYED.getCode().equals(order.getStatus())) {
			res.getError().add(buildError("", "当前状态无法撤销！"));
			return res;
		}

		res.setData(achievementOrderService.updateShutdownByUser(order));

		return res;
	}

	/**
	 * 科技成果订单列表
	 */
	@RequestMapping(value = "/achievementOrderList", method = RequestMethod.GET)
	public Result achievementOrderList(Integer status, 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(achievementOrderService.listOrderList(status, pNo, pSize));
		return res;
	}

	/**
	 * 科技成果"我要购买"
	 */
	@RequestMapping(value = "/orderAchievement", method = RequestMethod.POST)
	public Result orderAchievement(@Valid InputAchievementOrder order, BindingResult bindingResult) {
		Result res = new Result();
		if (TokenManager.getUserToken() == null) {
			res.getError().add(buildError(ErrorConstants.NON_LOGIN));
			return res;
		}
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					AchievementOrderFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		String achievementId = order.getAchievementId();
		if (StringUtils.isBlank(achievementId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到科技成果ID", "科技成果ID"));
			return res;
		}
		List<AchievementOrder> ao = achievementOrderService
				.selectAchievementOrderByUidAndAchievementId(TokenManager.getUserId(), achievementId);
		if (!ao.isEmpty()) {
			for (AchievementOrder os : ao) {
				AchievementOrderStatus status = AchievementOrderStatus.getStatus(os.getStatus());
				if (status != AchievementOrderStatus.CANCELLED || status != AchievementOrderStatus.INVALID) {
					res.getError().add(buildError("", "当前科技成果已被购买!"));
					return res;
				}
			}
		}

		Achievement a = achievementService.selectByPrimaryKey(achievementId);

		if (null == a || !AchievementAuditStatus.AUDITED.getCode().equals(a.getAuditStatus())
				|| !AchievementReleaseStatus.RELEASED.getCode().equals(a.getReleaseStatus())
				|| !DeleteStatus.UNDELETE.getCode().equals(a.getDeletedSign())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技成果ID"));
			return res;
		}
		if (TokenManager.getUserId().equals(a.getOwnerId())) {
			res.getError().add(buildError("", "无法购买本人发布科技成果!"));
			return res;
		}
		AchievementOrder achievementOrder = new AchievementOrder();
		AchievementOrderLog aol = new AchievementOrderLog();
		BeanUtils.copyProperties(order, achievementOrder);
		BeanUtils.copyProperties(order, aol);
		achievementOrderService.saveAchievementOrder(achievementOrder, aol);
		return res;
	}

	/**
	 * 科技需求订单log
	 */
	@RequestMapping(value = "/demandOrderLog", method = RequestMethod.GET)
	public Result demandOrderLog(String demandOrderId) {
		Result res = new Result();
		if (StringUtils.isEmpty(demandOrderId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "科技需求订单ID"));
			return res;
		}
		DemandOrder order = demandOrderService.selectByPrimaryKey(demandOrderId);
		if (null != order && TokenManager.getUserId().equals(order.getUid())) {
			res.setData(demandOrderLogService.selectDemandOrderLogByDemandOrderId(demandOrderId));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技需求订单ID"));
		}
		return res;
	}

	/**
	 * 科技需求订单列表
	 */
	@RequestMapping(value = "/demandOrderList", method = RequestMethod.GET)
	public Result demandOrderList(Integer status, 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(demandOrderService.listOrderList(status, pNo, pSize));
		return res;
	}

	/**
	 * 附件上传
	 */
	@RequestMapping(value = "/demandUpload", method = RequestMethod.POST)
	public Result uploadTextFile(HttpServletRequest req, String sign) {
		Result res = new Result();

		AttachmentType attachmentType = AttachmentType.getField(sign);

		/*if (attachmentType == AttachmentType.DEMAND_ORDER_FILE) {
			res.setData(handleFiles(res, "/demandOrder/", false, req, sign, TokenManager.getUserId()));
		} else {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "附件标示"));
		}*/
		return res;
	}

	/**
	 * 下载文件
	 */
	@RequestMapping(value = "/demandDownload", method = RequestMethod.GET)
	public Result download(HttpServletResponse response, String id) {
		Result res = new Result();

		if (StringUtils.isEmpty(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技需求订单ID"));
			return res;
		}

		DemandOrder order = demandOrderService.selectByPrimaryKey(id);
		if (null == order) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技需求订单ID"));
			return res;
		}

		downloadUnPrivateFile(response, order.getEnclosureDownloadFileName(), order.getEnclosureUrl());
		return res;
	}

	/**
	 * 科技需求"我要接单"
	 */
	@RequestMapping(value = "/orderDemand", method = RequestMethod.POST)
	public Result orderDemand(@Valid InputDemandOrder inputDemandOrder, BindingResult bindingResult) {
		Result res = new Result();
		if (TokenManager.getUserToken() == null) {
			res.getError().add(buildError(ErrorConstants.NON_LOGIN));
			return res;
		}
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					DemandOrderFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		String demandId = inputDemandOrder.getDemandId();
		if (StringUtils.isBlank(demandId)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到需求ID", "需求ID"));
			return res;
		}
		List<DemandOrder> demandOrder = demandOrderService.selectDemandOrderByUidAndDemandId(TokenManager.getUserId(),
				demandId);
		if (!demandOrder.isEmpty()) {
			for (DemandOrder os : demandOrder) {
				if (!DemandOrderStatus.SHUTDOWN.getCode().equals(os.getStatus())) {
					res.getError().add(buildError("", "当前科技需求已接单!"));
					return res;
				}
			}
		}
		Demand d = demandService.selectByPrimaryKey(demandId);
		if (null == d || d.getDeletedSign().equals(DeleteStatus.DELETED.getCode())
				|| !d.getAuditStatus().equals(DemandAuditStatus.AUDITED.getCode())
				|| !d.getReleaseStatus().equals(DemandReleaseStatus.RELEASED.getCode())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "科技需求ID"));
			return res;
		}
		if (TokenManager.getUserId().equals(d.getEmployerId())) {
			res.getError().add(buildError("", "无法对本人发布科技需求接单!"));
			return res;
		}

		DemandOrder order = new DemandOrder();
		DemandOrderLog dol = new DemandOrderLog();
		BeanUtils.copyProperties(inputDemandOrder, order);
		BeanUtils.copyProperties(inputDemandOrder, dol);

		demandOrderService.saveDemandOrder(order, dol);
		return res;
	}

	/**
	 * 关闭科技需求订单
	 */
	@RequestMapping(value = "/demandShutdown", method = RequestMethod.POST)
	public Result shutdown(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到订单ID", "订单ID"));
			return res;
		}

		DemandOrder order = demandOrderService.selectByPrimaryKey(id);
		if (null == order) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "订单ID"));
			return res;
		}

		if (!DemandOrderStatus.CREATE.getCode().equals(order.getStatus())) {
			res.getError().add(buildError("", "当前状态无法撤销！"));
			return res;
		}

		res.setData(demandOrderService.updateShutdownByUser(order));
		return res;
	}

}
