package com.yonyou.hrcloud.pm.result.web;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.hrcloud.adder.context.AppContext;
import com.yonyou.hrcloud.adder.exception.AdderBusinessException;
import com.yonyou.hrcloud.berry.model.MessageResult;
import com.yonyou.hrcloud.pm.common.web.BaseController;
import com.yonyou.hrcloud.pm.helper.StaffHelper;
import com.yonyou.hrcloud.pm.pa.model.Appraise;
import com.yonyou.hrcloud.pm.pa.service.IAppraiseService;
import com.yonyou.hrcloud.pm.ps.model.Scheme;
import com.yonyou.hrcloud.pm.ps.model.Sheet;
import com.yonyou.hrcloud.pm.result.model.ApproveScore;
import com.yonyou.hrcloud.pm.result.service.IApproveScoreService;


/**
 * 结果审核控制器
 * 
 * @author Flysea
 *
 */
@RestController
@RequestMapping("/pm/result")
@Api(value = "ApproveScoreController | 结果审核控制器")
public class ApproveScoreController extends BaseController {

	@Autowired
	public IApproveScoreService appScoreService;
	
	@Autowired
    IAppraiseService apprService;

	/**
	 * 查询我的待处理方案
	 * 
	 * @param flag
	 *            0未审核；1已审核
	 * @return
	 */
	@RequestMapping(value = "/querySchemeByAuditState", method = RequestMethod.GET)
	@ApiOperation(value = "查询我的待处理方案",httpMethod = "GET")
	@ApiImplicitParam(paramType = "query", name = "flag", value = "状态值(0：未审核/1：已审核)", required = true, dataType = "Integer")
	public MessageResult querySchemeByAuditState(Integer flag) {
		if (flag == null) {
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		}
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		List<Scheme> objs = appScoreService.querySchemeByAuditState(flag);
		result.setData(objs);
		return result;
	}

	/**
	 * 查询我的待处理方案，支持多方案
	 * 
	 * @param flag
	 *            0未审核；1已审核
	 * @return
	 */
	@RequestMapping(value = "/queryMultiSchemeByAuditState", method = RequestMethod.GET)
	@ApiOperation(value = "查询我的待处理方案，支持多方案",httpMethod = "GET")
	@ApiImplicitParam(paramType = "query", name = "flag", value = "状态值(0：未审核/1：已审核)", required = true, dataType = "Integer")
	public MessageResult queryMultiSchemeByAuditState(Integer flag) {
		if (flag == null) {
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		}
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		List<Object> objs = appScoreService.queryMultiSchemeByAuditState(flag);
		result.setData(objs);
		return result;
	}

	/**
	 * 查询考核方案下人员（旧样式）
	 *
	 * @param schemeid
	 * @param flag
	 *            0未审核；1已审核
	 * @param markFlag
	 *            null全部；1未审核；2已审核
	 * @return
	 */
	@RequestMapping(value = "/queryStaffByScheme", method = RequestMethod.GET)
	@ApiOperation(value = "查询考核方案下人员（旧样式）",httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "schemeid", value = "方案id", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "flag", value = "状态值(0：未审核/1：已审核)", required = false, dataType = "Integer"),
			@ApiImplicitParam(paramType = "query", name = "markFlag", value = "状态值(null：全部/1：未审核/2：已审核)", required = false, dataType = "Integer") })
	public MessageResult queryStaffByScheme(String schemeid, Integer flag,
			Integer markFlag) {
		if (schemeid == null)
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		List<ApproveScore> objs = appScoreService.queryStaffByScheme(schemeid,
				flag, markFlag);
		result.setData(objs);
		return result;
	}

	/**
	 * 查询考核方案下人员按等级分组（新样式）
	 *
	 * @param id
	 * @param flag
	 *            0未审核方案；1已审核
	 * @param markFlag
	 *            null全部；1未审核；2已审核
	 * @return
	 */
	@RequestMapping(value = "/queryGradeStaffByScheme", method = RequestMethod.GET)
	@ApiOperation(value = "查询考核方案下人员按等级分组（新样式）",httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "id", value = "方案ID或组主键", required = true, dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "flag", value = "方案状态值(0：未审核/1：已审核)", required = false, dataType = "Integer"),
			@ApiImplicitParam(paramType = "query", name = "markFlag", value = "量表状态值(null：全部/1：未审核/2：已审核)", required = false, dataType = "Integer") })
	public MessageResult queryGradeStaffByScheme(String id, Integer flag, Integer markFlag) {
		if (id == null || flag == null)
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		JSONObject json = appScoreService.queryGradeStaffByScheme(id, flag, markFlag);
		result.setData(json);
		return result;
	}

	/**
	 * 查询量表的结果分数和等级下拉
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/queryResultScore", method = RequestMethod.POST)
	@ApiOperation(value = "查询量表的结果分数和等级下拉",httpMethod = "POST")
	@ApiImplicitParam(paramType = "body", name = "data", value = "map{'id':'','schemeid':''}", required = true)
	public MessageResult queryResultScore(@RequestBody Map<String, String> data) {
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		String id = data.get("id");
		String schemeid = data.get("schemeid");
		if (id == null || schemeid == null)
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		String staffid = StaffHelper
				.getStaffByUserId(AppContext.getContext().getUserId());
		Map<String, Object> obj = appScoreService.queryResultScoreAll(id,
				schemeid, staffid);
		result.setData(obj);
		return result;
	}

	/**
	 * 结果审核-得分明细
	 * 
	 * @param sheetid
	 * @return
	 */
	@RequestMapping(value = "/queryApproveScore", method = RequestMethod.GET)
	@ApiOperation(value = "结果审核-得分明细",httpMethod = "GET")
	@ApiImplicitParam(paramType = "query", name = "sheetid", value = "量表id", required = true, dataType = "String")
	public MessageResult queryApproveScore(String sheetid) {
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		if (sheetid == null)
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		Sheet objs = appScoreService.queryApproveScore(sheetid);
		result.setData(objs);
		return result;
	}

	/**
	 * 结果审核保存
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/saveScore", method = RequestMethod.POST)
	@ApiOperation(value = "结果审核保存",httpMethod = "POST")
	@ApiImplicitParam(paramType = "body", name = "data", value = "ApproveScore.java", required = true)
	public MessageResult saveScore(@RequestBody String data) {
		MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
		if (data == null || data.length() == 0) {
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		}
		ApproveScore appScore = JSONObject
				.parseObject(data, ApproveScore.class);
		Integer turn = apprService.getMaxAppraiseTurn(appScore.getSheetid());
		List<Appraise> apprList = apprService.queryAppraiseComment(appScore.getSheetid(), turn, true);
		BigDecimal score = appScore.getScore();
		if(apprList != null && apprList.size() > 0) {
			score = apprList.get(0).getScore();
			appScore.setScore(score);
		}
		appScoreService.saveScore(appScore);
		return result;
	}

	/**
	 * 结果审核批准
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/doResultAudit", method = RequestMethod.POST)
	@ApiOperation(value = "结果审核批准", httpMethod = "POST")
	@ApiImplicitParam(paramType = "body", name = "data", value = "json['sheetid1','sheetid2']", required = true)
	public MessageResult doResultAudit(@RequestBody String data) {
		MessageResult result = new MessageResult("审批成功!", null, "pm.i18n_pbc.comm.006");
		if (StringUtils.isEmpty(data)) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		List<String> sheetids = JSONArray.parseArray(data, String.class);
		appScoreService.doResultAudit(sheetids,
				StaffHelper.getStaffByUserId(AppContext.getContext().getUserId()));
		return result;
	}

	/**
	 * 是否需要提示不满足强分
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/getResultAuditTip", method = RequestMethod.POST)
	@ApiOperation(value = "结果审核批准", httpMethod = "POST")
	@ApiImplicitParam(paramType = "body", name = "data", value = "json['sheetid1','sheetid2']", required = true)
	public MessageResult getResultAuditTip(@RequestBody String data) {
		MessageResult result = new MessageResult("审批成功!", null, "pm.i18n_pbc.comm.006");
		if (StringUtils.isEmpty(data)) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		List<String> sheetids = JSONArray.parseArray(data, String.class);
		int ret = appScoreService.doResultAudit(sheetids,
				StaffHelper.getStaffByUserId(AppContext.getContext().getUserId()), false, true);
		result.setData(String.valueOf(ret));
		return result;
	}
	
	/**
	 * 结果审核弃审
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/doResultAbandoned", method = RequestMethod.POST)
	@ApiOperation(value = "结果审核弃审",httpMethod = "POST")
	@ApiImplicitParam(paramType = "body", name = "data", value = "json['sheetid1','sheetid2']", required = true)
	public MessageResult doResultAbandoned(@RequestBody String data) {
		MessageResult result = new MessageResult("弃审成功!",null,"pm.i18n_pbc.comm.007");
		if (StringUtils.isEmpty(data)) {
			throw new AdderBusinessException("参数不能为空","pm.i18n_core.comm.002");
		}
		List<String> sheetids = JSONArray.parseArray(data, String.class);
		appScoreService.doResultAbandoned(sheetids,
				StaffHelper.getStaffByUserId(AppContext.getContext().getUserId()));
		return result;
	}

	/**
	 * 执行自动分布
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/doDistributeAuto", method = RequestMethod.POST)
	@ApiOperation(value = "结果审核弃审",httpMethod = "POST")
	@ApiImplicitParam(paramType = "body", name = "data", value = "map{'id':'','flag':'','groupid':''}", required = true)
	public MessageResult doDistributeAuto(@RequestBody Map<String, Object> data) {
		MessageResult result = new MessageResult("自动分布成功!",null,"pm.i18n_pbc.comm.008");
		try {
			String id = (String) data.get("id");
			Integer flag = null;
			if (data.get("flag") != null
					&& StringUtils.isNotEmpty(data.get("flag").toString())) {
				flag = (Integer) data.get("flag");
			}
			Integer markFlag = null;
			if (data.get("markFlag") != null
					&& StringUtils.isNotEmpty(data.get("markFlag").toString())) {
				markFlag = (Integer) data.get("markFlag");
			}
			String groupid = (String) data.get("groupid");
			JSONArray jsonArray = appScoreService.doDistributeAuto(id, flag,
					markFlag,groupid);
			result.setData(jsonArray);

		} catch (Exception e) {
			result.setMessage(e.getMessage());
			//e.printStackTrace();
		}
		return result;
	}
}
