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

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.adder.model.query.Condition;
import com.yonyou.hrcloud.berry.model.MessageResult;

import com.yonyou.hrcloud.pm.common.model.CommonValue;
import com.yonyou.hrcloud.pm.common.model.PmStaff;
import com.yonyou.hrcloud.pm.common.web.BaseController;
import com.yonyou.hrcloud.pm.helper.OrgHelper;
import com.yonyou.hrcloud.pm.helper.StaffHelper;
import com.yonyou.hrcloud.pm.ps.model.SheetIndicator;
import com.yonyou.hrcloud.pm.ps.service.ISheetIndicatorService;
import com.yonyou.hrcloud.pm.result.model.ApproveScore;
import com.yonyou.hrcloud.pm.result.service.IScoreService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    public IScoreService scoreService;

    @Autowired
	ISheetIndicatorService sheetIndiServ;

    protected static final Logger logger = LoggerFactory.getLogger(ScoreController.class);

    /**
     * 查询本人的结果列表
     *
     * @return
     */
    @RequestMapping(value = "/queryMyResultList", method = RequestMethod.GET)
    @ApiOperation(value = "查询本人的结果列表",httpMethod = "GET")
    public MessageResult queryMyResultList() {
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        String staffid = StaffHelper
                .getStaffByUserId(AppContext.getContext().getUserId());
        result.setData(scoreService.queryMyResultList(staffid, null));
        return result;
    }

	/**
	 * 查询量表指标的得分明细
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/queryIndiScoreDetail", method = RequestMethod.GET)
	@ApiOperation(value = "查询量表指标的得分明细", httpMethod = "GET")
	@ApiImplicitParam(paramType = "query", name = "params", value = "json{'sheetid':''}", required = true)
	public MessageResult queryIndicatorScoreDetail(String params) {
		// 
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		JSONObject json = JSONObject.parseObject(params);
		if (json == null || !json.containsKey("sheetid")) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		result.setData(scoreService.queryIndicatorScoreDetail(json.getString("sheetid")));
		return result;
	}

    /**
     * 查询量表的结果明细
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/queryResultDetail", method = RequestMethod.GET)
    @ApiOperation(value = "查询量表的结果明细",httpMethod = "GET")
    @ApiImplicitParam(paramType = "query", name = "params", value = "json{'sheetid':''}", required = true)
    public MessageResult querySheetResultDetail(String params) {
    	// 在移动端结果浏览的评分明细里
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        JSONObject json = JSONObject.parseObject(params);
        if (json == null || !json.containsKey("sheetid")) {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        Map<String, Object> map = new HashedMap<>();
        String sheetid = json.getString("sheetid");
        // 评分明细
        map.put("detail", scoreService.querySheetResultDetail(sheetid));
		// 结果调整说明
		List<ApproveScore> apprScore = scoreService.queryApprvoeScore(sheetid);
		for (ApproveScore item : apprScore) {
			item.setScore(null);
			item.setGradeitemid(null);
			item.setGradeitemname(null);
		}
		map.put("explain", apprScore);
        result.setData(map);
        return result;
    }

    /**
     * 查询分管人群结果列表
     *
     * @return
     */
    @RequestMapping(value = "/queryDeptResultList", method = RequestMethod.GET)
    @ApiOperation(value = "查询分管人群结果列表",httpMethod = "GET")
    public MessageResult queryDeptResultList() {
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        /**
         * staffid:ea71c29aa0d74f86a1a826d9cd01104c(历任部门主管)
         */
        String staffid = StaffHelper
                .getStaffByUserId(AppContext.getContext().getUserId());
        result.setData(scoreService.queryDeptResultList(staffid));
        return result;
    }

    /**
     * 考核方案下我的部门下考核对象列表
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/queryPsnListInDept", method = RequestMethod.GET)
    @ApiOperation(value = "考核方案下我的部门下考核对象列表",httpMethod = "GET")
    @ApiImplicitParam(paramType = "query", name = "params", value = "json{'schemeid':''}", required = true)
    public MessageResult queryPsnListInDept(String params) {
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        JSONObject json = JSONObject.parseObject(params);
        if (json == null || !json.containsKey("schemeid")) {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        String staffid = StaffHelper
                .getStaffByUserId(AppContext.getContext().getUserId());
        result.setData(scoreService.queryPsnListInDept(
                json.getString("schemeid"), staffid));
        return result;
    }

    @RequestMapping(value = "/queryPrevDeptids", method = RequestMethod.GET)
    @ApiOperation(value = "获取上一个任职部门信息",httpMethod = "GET")
    public MessageResult queryPrevDeptids() {
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        String staffid = StaffHelper
                .getStaffByUserId(AppContext.getContext().getUserId());
        result.setData(scoreService.getPrevDeptids(staffid));
        return result;
    }

    /**
     * 查询历史绩效（时间轴）
     *
     * @return
     */
    @RequestMapping(value = "/queryTimeline", method = RequestMethod.GET)
    @ApiOperation(value = "查询历史绩效（时间轴）",httpMethod = "GET")
    @ApiImplicitParam(paramType = "query", name = "params", value = "json{'isAll':'','staffId':''}", required = true)
    public MessageResult queryHPTimeline(String params) {
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        JSONObject json = JSONObject.parseObject(params);
        String staffid;
        Boolean isAll = true;
        if (json != null && json.containsKey("isAll")) {
            isAll = json.getBoolean("isAll");
        }
        //没有用户Id则查询自己历史绩效
        if(json != null &&json.containsKey("staffId")){
            staffid=json.getString("staffId");
        }else{
            staffid = StaffHelper
                    .getStaffByUserId(AppContext.getContext().getUserId());
        }
        if(json.containsKey("applyobj")){
            if(CommonValue.EnumApplyObj.org.getIndex() == json.getIntValue("applyobj")){
                result.setData(scoreService.queryHPTimeline(staffid, isAll,CommonValue.EnumApplyObj.org.getIndex()));
            }else{
                result.setData(scoreService.queryHPTimeline(staffid, isAll,CommonValue.EnumApplyObj.psn.getIndex()));
            }
        }else{
            result.setData(scoreService.queryHPTimeline(staffid, isAll));
        }
        return result;
    }

	/**
	 * 查询绩效详情
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryPerformanceDetail", method = RequestMethod.GET)
	@ApiOperation(value = "查询绩效详情", httpMethod = "GET")
	@ApiImplicitParam(paramType = "query", name = "params", value = "json{'sheetId':''}", required = true)
	public MessageResult queryPerformanceDetail(String params) {
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		JSONObject json = JSONObject.parseObject(params);
		if (json == null || !json.containsKey("sheetId")) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		String sheetid = json.getString("sheetId");
		// 20200108判断量表结果是导入的，则不允许看明细
		Condition condObj = new Condition();
		condObj.addExpression("sheetid", sheetid);
		List<SheetIndicator> indis = sheetIndiServ.querySheetIndicators(condObj, null);
		Map<String, Object> map = new HashMap<>();
		// title显示信息
		map.put("titleInfo", scoreService.queryPsnScoreInfo(sheetid));
		// 方案信息
		map.put("scheme", scoreService.querySchemeInfoBySheetid(sheetid));
		if (indis.isEmpty()) {
			// throw new AdderBusinessException("该人员在此方案没有结果详情数据",
			// "pm.i18n_pbc.result.015");
			map.put("evaluation", new ArrayList<>());
			map.put("detail", new ArrayList<>());
		} else {
			// 综合评价
			map.put("evaluation", scoreService.querySheetResultDetail(sheetid));
			// 绩效详情
			map.put("detail", scoreService.queryPerformanceDetail(sheetid));
		}
		// 当前登入人信息
		String loggerUserid = StaffHelper.getStaffByUserId(AppContext.getContext().getUserId());
		List<PmStaff> objs = StaffHelper.queryStaffByIds3(Arrays.asList(loggerUserid));
		map.put("loggedInfo", objs.get(0));
		result.setData(map);
		return result;
	}
    
/*	@RequestMapping(value = "/demo", method = RequestMethod.GET)
    public MessageResult demo(String params){
		MessageResult result = new MessageResult("操作成功!");
		if (StringUtils.isBlank(params)) {
			throw new AdderBusinessException("参数不能为空");
		}
		List<String> ids=JSONArray.parseArray(params,String.class);
		result.setData(scoreService.getLatestSchemeYear(ids));
		return  result;

	}*/

    /**
     * 查询人员绩效列表(部门/人员)
     *
     * @param params
     * @return
     */
	@RequestMapping(value = "/queryPerformanceList", method = RequestMethod.GET)
    @ApiOperation(value = "查询人员绩效列表(部门/人员)",httpMethod = "GET")
    @ApiImplicitParam(paramType = "query", name = "params", value = "{'pageIndex':'','pageSize':'','deptIds':'','queryType':''}", required = true)
	public MessageResult queryStaffPerformanceList(String params) {
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		JSONObject data = JSONObject.parseObject(params);
		if (data == null || !data.containsKey("pageIndex") || !data.containsKey("pageSize")
				|| !data.containsKey("queryType")) {
			throw new AdderBusinessException("参数不正确", "pm.i18n_okr.objective.002");
		}
		List<String> deptIds = new ArrayList<>();
		if (data.containsKey("deptIds")) {
			deptIds = JSONArray.parseArray(data.getString("deptIds"), String.class);
		}
		int pageIndex = data.getInteger("pageIndex");
		int pageSize = data.getInteger("pageSize");
		// 0:部门绩效；1：人员绩效
		int queryType = data.getInteger("queryType");
		if (queryType == 0 && (deptIds == null || deptIds.size() == 0)) {
			// 参数中没有deptids时，默认查所有权限的部门
			/*deptIds = StaffHelper.queryPrevDeptInfo(StaffHelper.getStaffByUserId(AppContext.getContext().getUserId())).stream()
					.map(staff -> {
						return staff.deptid;
					}).collect(Collectors.toList());*/
			deptIds = new ArrayList<String>();
			List<PmStaff> queryPrevDeptInfo = StaffHelper.queryPrevDeptInfo(StaffHelper.getStaffByUserId(AppContext.getContext().getUserId()));
			for(PmStaff staff : queryPrevDeptInfo){
				deptIds.add(staff.deptid);
			}
		} else if (queryType == 1) {
			// 获得当前热人员所辖所有的组织
			List<String> belongDepts = OrgHelper
					.getHasRightDeptIdList(CommonValue.EnumServiceCode.STAFFPERFORM.getCode());
			if (belongDepts != null && belongDepts.size() > 0) {
				if (deptIds == null || deptIds.size() == 0) {
					deptIds = belongDepts;
				} else {
					// 当根据deptid进行查询时，此deptid应该是 当前人员所辖组织之一（取所辖组织和查询deptId的交集）
					deptIds.retainAll(belongDepts);
				}
			} else {
				deptIds = null;
			}
		}
		String name = "";
		if (data.containsKey("name")) {
			name = data.getString("name");
			//pageIndex=0;
		}
		if (deptIds != null && deptIds.size() > 0) {
			result.setData(scoreService.queryStaffPerformance(deptIds, name, pageIndex, pageSize));
		}
		return result;
	}

    /**
     * 查询组织绩效列表(部门)
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/queryOrgPerformanceList", method = RequestMethod.GET)
    @ApiOperation(value = "查询组织绩效列表(部门)",httpMethod = "GET")
    @ApiImplicitParam(paramType = "query", name = "params", value = "{'pageIndex':'','pageSize':'','deptIds':''}", required = true)
    public MessageResult queryOrgPerformanceList(String params) {
        MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
        JSONObject data = JSONObject.parseObject(params);
        if (data == null || !data.containsKey("pageIndex") || !data.containsKey("pageSize")) {
            throw new AdderBusinessException("参数不正确", "pm.i18n_okr.objective.002");
        }
        List<String> deptIds = new ArrayList<>();
        if (data.containsKey("deptIds")) {
            deptIds = JSONArray.parseArray(data.getString("deptIds"), String.class);
        }
        int pageIndex = data.getInteger("pageIndex");
        int pageSize = data.getInteger("pageSize");
        // 获得当前热人员所辖所有的组织
        List<String> belongDepts = OrgHelper
                .getHasRightDeptIdList(CommonValue.EnumServiceCode.STAFFPERFORM.getCode());
        if (belongDepts != null && belongDepts.size() > 0) {
            if (deptIds == null || deptIds.size() == 0) {
                deptIds = belongDepts;
            } else {
                // 当根据deptid进行查询时，此deptid应该是 当前人员所辖组织之一（取所辖组织和查询deptId的交集）
                deptIds.retainAll(belongDepts);
            }
        } else {
            deptIds = null;
        }
        if (deptIds != null && deptIds.size() > 0) {
            Map<String, Object> resultData = scoreService.queryOrgPerformance(deptIds, pageIndex, pageSize);
            if(MapUtils.isNotEmpty(resultData)){
                result.setData(resultData);
            }
        }
        return result;
    }

    /**
     * 根据部门经理的所辖部门集合
     *
     * @return
     */
    @RequestMapping(value = "/queryDeptListOfStaff", method = RequestMethod.GET)
    @ApiOperation(value = "根据部门经理的所辖部门集合",httpMethod = "GET")
    public MessageResult queryDeptListOfStaff() {
        /*List<String> deptIds = StaffHelper
				.queryPrevDeptInfo(StaffHelper.getStaffByUserId(AppContext.getContext().getUserId())).stream().map(staff -> {
                    return staff.deptid;
                }).collect(Collectors.toList());*/
        List<String> deptIds = new ArrayList<String>();
        List<PmStaff> queryPrevDeptInfo = StaffHelper
				.queryPrevDeptInfo(StaffHelper.getStaffByUserId(AppContext.getContext().getUserId()));
        for(PmStaff staff : queryPrevDeptInfo){
        	deptIds.add(staff.deptid);
        }
        MessageResult result = new MessageResult("");
        result.setData(StaffHelper.queryDeptListByDeptIds(deptIds));
        return result;
    }

	/**
	 * 新增考核结果数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/insertAssessResultInfo", method = RequestMethod.POST)
	@ApiOperation(value = "新增考核结果数据", httpMethod = "POST")
	@ApiImplicitParam(name = "data", value = "保存考核结果数据的参数，参数格式:data:{'schemeid': '方案主键','staffid': '人员id','groupid': '考核对象组id','numvalue': '考核分数','text': '考核等级'}", dataType = "String", paramType = "body", required = true)
	public MessageResult insertAssessResultInfo(@RequestBody String data) {
		MessageResult result = new MessageResult("操作成功!", null, "pm.i18n_core.comm.008");
		if (data == null || data.length() == 0) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		JSONObject json = JSONObject.parseObject(StringEscapeUtils.unescapeHtml(data));
		String schemeid = json.getString("schemeid");
		String staffid = json.getString("staffid");
		String groupid = json.getString("groupid");
		String numvalue = json.getString("numvalue");
		String text = json.getString("text");
		if (StringUtils.isEmpty(schemeid) || StringUtils.isEmpty(staffid) || StringUtils.isEmpty(numvalue) || StringUtils.isEmpty(text) || StringUtils.isEmpty(groupid))
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		scoreService.insertAssessResultInfo(schemeid, staffid, groupid, numvalue, text);
		return result;
	}
}
