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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.hrcloud.adder.context.AppContext;
import com.yonyou.hrcloud.adder.data.jdbc.DialectHelper;
import com.yonyou.hrcloud.adder.exception.AdderBusinessException;
import com.yonyou.hrcloud.adder.model.param.Sorter;
import com.yonyou.hrcloud.adder.model.query.Condition;
import com.yonyou.hrcloud.adder.model.query.Operator;
import com.yonyou.hrcloud.adder.service.IGenericService;
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.EvaAppraiser;
import com.yonyou.hrcloud.pm.ps.model.EvaGroup;
import com.yonyou.hrcloud.pm.ps.model.EvaObject;
import com.yonyou.hrcloud.pm.ps.model.EvaSetting;
import com.yonyou.hrcloud.pm.ps.model.Scheme;
import com.yonyou.hrcloud.pm.ps.model.SchemePlan;
import com.yonyou.hrcloud.pm.ps.service.IEvaGroupService;
import com.yonyou.hrcloud.pm.ps.service.IImportResultService;
import com.yonyou.hrcloud.pm.ps.service.ISchemeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
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.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 方案控制器
 *
 * @author Flysea
 */
@RestController
@RequestMapping("/pm/system")
@Api(value = "SchemeController | 方案控制器")
public class SchemeController extends BaseController {

    @Autowired
    ISchemeService schemeService;

    @Autowired
    IEvaGroupService groupService;

    @Autowired
    IImportResultService iImportResultService;
    
    @Autowired
    IGenericService daoex;

    /**
     * 查询方案列表
     *
     * @param cond
     * @return
     */
    @RequestMapping(value = "/querySchemeByConditon", method = RequestMethod.GET)
    @ApiOperation(value = "查询方案列表", httpMethod = "GET")
    @ApiImplicitParam(name = "cond", value = "查询方案列表参数，包含排序字段:sortkey,排序方式:sortorder，正序asc，倒序desc", dataType = "String", paramType = "query", required = true)
    public MessageResult querySchemeByConditon(String cond) {
        MessageResult result = new MessageResult("");
        Condition condObj = new Condition();
        Sorter sortObj = new Sorter(Direction.DESC, Arrays.asList("tdate"));
        Sorter sortObj2 = new Sorter(Direction.DESC, Arrays.asList("periodcode", "creationtime"));
        sortObj = sortObj.and(sortObj2);
        if (!StringUtils.isEmpty(cond)) {
            // 排序
            JSONObject json = JSONObject.parseObject(StringEscapeUtils.unescapeHtml(cond));
            String sortkey = json.getString("sortkey");
            String sortorder = json.getString("sortorder");
            if (sortkey != null)
                sortObj = new Sorter(Direction.fromString(sortorder), sortkey);
        }
        List<Scheme> objs = schemeService.querySchemeList(condObj, sortObj, null);
        result.setData(objs);
        return result;
    }

    @RequestMapping(value = "/querySchemeByConfig", method = RequestMethod.POST)
    @ApiOperation(value = "根据配置查看方案列表", httpMethod = "POST")
    @ApiImplicitParam(paramType = "body", name = "data", value = "map{'sortkey':'排序字段:sortkey','sortorder':'排序方式'，'periodcode':'绩效周期','schemestate':'方案状态','schemename':'方案名称','currentpage':'当前页数','pagesize':'每页方案的条数','isover':'方案是否结束'}", required = true)
    public MessageResult querySchemeByConfig(@RequestBody String data) {
        MessageResult result = new MessageResult("操作成功", null, "pm.i18n_core.comm.008");
        JSONObject obj = JSON.parseObject(StringEscapeUtils
                .unescapeHtml(data));
        if (obj.size() > 0) {
            Page<Scheme> schemes = schemeService.querySchemeListByConfig(obj);
            result.setData(schemes);
        } else {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        return result;
    }

    /**
     * 查询一个考核方案信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/querySchemeByID", method = RequestMethod.GET)
    @ApiOperation(value = "查询一个考核方案信息", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "查询考核方案信息的参数，包含方案id:id", dataType = "String", paramType = "query", required = true)
    public MessageResult querySchemeByID(String id) {
        MessageResult result = new MessageResult("");
        Scheme obj = schemeService.querySchemeByID(id, true);
        result.setData(obj);
        return result;
    }

	/**
	 * 保存方案
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/saveScheme", method = RequestMethod.POST)
	@ApiOperation(value = "保存方案", httpMethod = "POST")
	@ApiImplicitParam(name = "data", value = "保存方案的参数，参数格式:data:{'id': '主键','schemename': '方案名称','remark': '说明','schememode': 1,     //0=pbc，1=360'periodid': '周期id','periodcode': '周期编码','gradeid': '考核等级id','scoreruleid': '评分规则id','scoreway': 1,   //总分汇总方式，1=加权求和，2=算术求和'isresultaudited': true,   //考核结果需要审核'isturn': true,    //严格按照考核轮次顺序考评'ismergemsg': false,    //前面多人时只收到最后一条消息'oevaAppraiser':[{'id':'考核流程主键','dimid':'考核人类别id','staffid':'人员id','turn':'轮次','weight': 0.1,   //'权重''isapprove':true,  //是否指标审核'schemeid':'方案主键'}]}", dataType = "String", paramType = "body", required = true)
	public MessageResult saveScheme(@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");
		}
		JSONObject json = JSONObject.parseObject(StringEscapeUtils.unescapeHtml(data));
		Scheme scheme = new Scheme();
		boolean newScheme = true;
		if (json.get("id") != null) {
			newScheme = false;
			scheme = schemeService.querySchemeByID(json.get("id").toString(), true);
			super.IsExist(scheme);
		}
		if (json.get("schemecode") != null)
			scheme.setSchemecode(json.getString("schemecode"));
		scheme.setSchemename(json.get("schemename").toString());
		scheme.setRemark(json.getString("remark"));
		scheme.setPeriodid(json.get("periodid").toString());
		scheme.setPeriodcode(json.get("periodcode").toString());
		scheme.setGradeid(json.get("gradeid").toString());
		scheme.setScoreruleid(json.get("scoreruleid").toString());
		scheme.setSchememode((int) json.get("schememode"));
		if (json.getBoolean("isresultconfirm") != null) {
			scheme.setIsresultconfirm(json.getBoolean("isresultconfirm")); // 结果是否需要员工确认
		}
		if (json.getBoolean("isdoubleweight") != null)
			scheme.setIsdoubleweight(json.getBooleanValue("isdoubleweight"));
		// add by zengcl 新增导入结果字段
        if (json.getBoolean("isimportresult") != null){
            scheme.setIsimportresult(json.getBooleanValue("isimportresult"));
        }
        if (json.getBoolean("isaccount") != null){
            scheme.setIsaccount(json.getBooleanValue("isaccount"));
        }
        if (json.getBoolean("isviewresult") != null){
            scheme.setIsviewresult(json.getBooleanValue("isviewresult"));
            if(json.getBoolean("isviewresult")) {
            	scheme.setIsresultconfirm(false);
            }
        }
		if (CommonValue.EnumSchemeMode.valueOf(scheme.getSchememode()) == null)
			throw new AdderBusinessException("参数有误！", "pm.i18n_core.comm.009");
		scheme.setScoreway((int) json.get("scoreway"));
		scheme.setIsresultaudited(Boolean.parseBoolean(json.get("isresultaudited").toString()));
		scheme.setIsturn(Boolean.parseBoolean(json.get("isturn").toString()));
		scheme.setIsmergemsg(Boolean.parseBoolean(json.get("ismergemsg").toString()));
		if (json.get("applyobj") == null)
			scheme.setApplyobj(CommonValue.EnumApplyObj.psn.getIndex());
		else
			scheme.setApplyobj((int) json.get("applyobj"));
		if (json.get("isallowfillup") == null)
			scheme.setIsallowfillup(true);
		else
			scheme.setIsallowfillup(Boolean.parseBoolean(json.get("isallowfillup").toString()));
		if (json.get("indisource") != null) {
			scheme.setIndisource(json.getIntValue("indisource"));
			if (scheme.getIndisource() > 0)
				scheme.setIsallowfillup(false);
		} else if (!scheme.isIsallowfillup()) {
			// 如果指标来源没传，且不能填报，指标来源设置为HR统一设置
			scheme.setIndisource(1);
		}
		if (StringUtils.isEmpty(json.getString("orgid")))
			scheme.setOrgid(CommonValue.EnumDataBaseSpecial.Empty.getSymbol());
		else
			scheme.setOrgid(json.getString("orgid"));
		if (json.getString("tagid") != null)
			scheme.setTagid(json.getString("tagid"));
		if (json.get("oevaAppraiser") != null) {
			List<EvaAppraiser> evaAppraisers = JSONArray.parseArray(json.get("oevaAppraiser").toString(),
					EvaAppraiser.class);
			scheme.setOEvaAppraiser(evaAppraisers);
		}
		// 是否允许创建中期回顾方案，默认是不允许
		if (json.getBoolean("isallowmtr") != null)
			scheme.setIsallowmtr(json.getBooleanValue("isallowmtr"));
		// 是否支持考核评分，默认是支持，只有中期回顾方案才会有不支持的情况
		if (json.getBoolean("isallowcalc") != null
				&& scheme.getSchememode() == CommonValue.EnumSchemeMode.pm_mtr.getIndex())
			scheme.setIsallowcalc(json.getBooleanValue("isallowcalc"));
        if (newScheme) {
			// 新方案
			scheme.setAbstentionmode(CommonValue.EnumAbstentionMode.mode2.getIndex());
			scheme.setSchemestate(CommonValue.EnumSchemeState.State2.ordinal());
			schemeService.insert(scheme);
		} else {
			schemeService.update(scheme);
		}
		result.setData(scheme);
		return result;
	}

    /**
     * 修改一个方案的名称或说明
     *
     * @param data
     * @return
     */
	@RequestMapping(value = "/saveSchemeInfo", method = RequestMethod.POST)
	@ApiOperation(value = "修改一个方案的名称或说明", httpMethod = "POST")
	@ApiImplicitParam(name = "data", value = "方案名称、方案说明", dataType = "Map", paramType = "body", required = true)
	public MessageResult saveSchemeInfo(@RequestBody Map<String, String> data) {
		if (data == null || data.isEmpty()) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
		schemeService.saveSchemeInfo(data.get("id"), data.get("name"), data.get("remark"));
		return result;
	}
    
    /**
     * 查询一个考核对象组信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryEvaGroupByID", method = RequestMethod.GET)
    @ApiOperation(value = "查询一个考核对象组信息", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "查询考核对象组信息的参数，参数包含考核对象组的id:id", dataType = "String", paramType = "query", required = true)
    public MessageResult queryEvaGroupByID(String id) {
        MessageResult result = new MessageResult("");
        EvaGroup obj = groupService.queryEvaGroupByID(id, true);
        result.setData(obj);
        return result;
    }

	/**
	 * 导出考核对象到excel
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/exportEvaObject", method = RequestMethod.GET)
	@ApiOperation(value = "查询一个考核对象组信息", httpMethod = "GET")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", name = "schemeid", value = "方案id", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "evagroupIds", value = "考核对象组id集合", required = true, dataType = "String") })
	public MessageResult exportEvaObject(HttpServletRequest request, HttpServletResponse response, String schemeid,
			String[] evagroupIds) {
		// MessageResult result = new MessageResult("下载成功");
		String scheme_id = groupService.exportEvaObject(request, response, schemeid, evagroupIds);
		// result.setData(obj);
		return null;
	}

    /**
     * 保存考核对象组
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/saveEvaGroup", method = RequestMethod.POST)
    @ApiOperation(value = "保存考核对象组", httpMethod = "POST")
    @ApiImplicitParam(name = "data", value = "保存考核对象组的参数，参数格式:data:{'id': '主键','groupcode': '组编码','groupname': '组名称','schemeid': '方案id'}", dataType = "Map", paramType = "body", required = true)
    public MessageResult saveEvaGroup(@RequestBody Map<String, Object> data) {
        MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
        if (data == null || data.size() == 0) {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        EvaGroup group = new EvaGroup();
        boolean newScheme = true;
        if (data.get("id") != null) {
            group = groupService.queryEvaGroupByID(data.get("id").toString(),
                    false);
            newScheme = false;
        }
        group.setSchemeid(data.get("schemeid").toString());
        if (data.get("groupcode") != null)
            group.setGroupcode(data.get("groupcode").toString());
        group.setGroupname(data.get("groupname").toString());
        if (newScheme) {
            groupService.insert(group);
        } else {
            groupService.update(group);
        }
        result.setData(group);
        return result;
    }

    /**
     * 新增考核对象组
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/addEvaGroup", method = RequestMethod.POST)
    @ApiOperation(value = "新增考核对象组", httpMethod = "POST")
    @ApiImplicitParam(name = "data", value = "新增考核对象组的参数，参数格式:data:{'id': ['123','456'],   //参照id数组'type': 3,    //1部门2岗位3人员4项目'schemeid': '方案id','projectname': '第一个项目名称',}", dataType = "Map", paramType = "body", required = true)
    public MessageResult addEvaGroup(@RequestBody Map<String, Object> data) {
        MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
        if (data == null || data.size() == 0) {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        EvaGroup group = new EvaGroup();
        group.setSchemeid(data.get("schemeid").toString());
        String groupname = "新建分组";
        String lang = AppContext.getContext().getLocale().toString().toLowerCase();
        switch (lang) {
            case "zh_tw":
                groupname = "新建分組";
                break;
            case "en_us":
                groupname = "New grouping";
                break;
        }
        group.setGroupname(groupname);
        List<EvaObject> objs = new ArrayList<EvaObject>();
        // 1部门2职位3人员4项目5组织绩效
        List<String> staffs = null;
        List<String> ids = (List<String>) data.get("id");
        if (data.get("type").equals(3)) {
            staffs = ids;
        } else if (data.get("type").equals(1)) {
            staffs = groupService.queryStaffListByIds(ids, 1);
            if (!ids.isEmpty()) {
                //OrgHelper orgH = OrgHelper;
                for (String item : ids) {
                    String deptname = OrgHelper.queryDeptName(item);
                    if (deptname.length() > 0) {
                        group.setGroupname(deptname);
                        break;
                    }
                }
                //orgH = null;
            }
        } else if (data.get("type").equals(2)) {
            staffs = groupService.queryStaffListByIds(ids, 2);
		} else if (data.get("type").equals(4)) {
			String projectname = data.get("projectname").toString();
			group.setGroupname(projectname);
			// 项目传过来的是userid
            staffs = StaffHelper.getStaffListByUserIdList(ids);
		} else if (data.get("type").equals(5)) {
			// 组织绩效
	        groupService.insert(group);
	        result.setData(group);
	        return result;
		} else
            throw new AdderBusinessException("类型不正确", "pm.i18n_core.comm.006");
        if (staffs == null || staffs.size() == 0)
            throw new AdderBusinessException("未查询到人员", "pm.i18n_core.comm.007");
        removeDuplicate(staffs);
        for (String staffid : staffs) {
            EvaObject newObj = new EvaObject();
            newObj.setSchemeid(group.getSchemeid());
            newObj.setStaffid(staffid);
            objs.add(newObj);
        }
        group.setOEvaObjects(objs);
        groupService.insert2(group);
        result.setData(group);
        return result;
    }

    /**
     * 新增考核对象组  (考核监控) 
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/addEvaGroupForMonitor", method = RequestMethod.POST)
    @ApiOperation(value = "新增考核对象组", httpMethod = "POST")
    @ApiImplicitParam(name = "data", value = "新增考核对象组的参数，参数格式:data:{'id': ['123','456'],   //参照id数组'type': 3,    //1部门2岗位3人员4项目'schemeid': '方案id','projectname': '第一个项目名称',}", dataType = "Map", paramType = "body", required = true)
    public MessageResult addEvaGroupForMonitor(@RequestBody Map<String, Object> data) {
        MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
        if (data == null || data.size() == 0) {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        EvaGroup group = new EvaGroup();
        group.setSchemeid(data.get("schemeid").toString());
        String groupname = "新建分组";
        String lang = AppContext.getContext().getLocale().toString().toLowerCase();
        switch (lang) {
            case "zh_tw":
                groupname = "新建分組";
                break;
            case "en_us":
                groupname = "New grouping";
                break;
        }
        group.setGroupname(groupname);
        List<EvaObject> objs = new ArrayList<EvaObject>();
        // 1部门2职位3人员4项目5组织绩效
        List<String> staffs = null;
        List<String> ids = (List<String>) data.get("id");
        if (data.get("type").equals(3)) {
            staffs = ids;
        } else if (data.get("type").equals(1)) {
            staffs = groupService.queryStaffListByIds(ids, 1);
            if (!ids.isEmpty()) {
                for (String item : ids) {
                    String deptname = OrgHelper.queryDeptName(item);
                    if (deptname.length() > 0) {
                        group.setGroupname(deptname);
                        break;
                    }
                }
            }
        } else if (data.get("type").equals(2)) {
            staffs = groupService.queryStaffListByIds(ids, 2);
		} else if (data.get("type").equals(4)) {
			String projectname = data.get("projectname").toString();
			group.setGroupname(projectname);
			// 项目传过来的是userid
			staffs = StaffHelper.getStaffListByUserIdList(ids);
		} else if (data.get("type").equals(5)) {
			// 组织绩效
	        groupService.insert(group);
	        result.setData(group);
	        return result;
		} else
            throw new AdderBusinessException("类型不正确", "pm.i18n_core.comm.006");
        if (staffs == null || staffs.size() == 0)
            throw new AdderBusinessException("未查询到人员", "pm.i18n_core.comm.007");
        removeDuplicate(staffs);
 		Map<String, PmStaff> staffMap = StaffHelper.queryStaffByIds(staffs);
        for (String staffid : staffs) {
            EvaObject newObj = new EvaObject();
            newObj.setSchemeid(group.getSchemeid());
            newObj.setStaffid(staffid);
            newObj.setStaff(staffMap.get(staffid));
            objs.add(newObj);
        }
        group.setOEvaObjects(objs);
        groupService.insert(group); //  只保存组，不保存考核对象。
        result.setData(group);
        return result;
    }
   
    /**
	 * 考核监控根据考核对象staffid获取人员信息
	 * 
	 * @param id
	 *            staffid
	 * @return
	 */
	@RequestMapping(value = "/queryEvaStaff", method = RequestMethod.POST)
	@ApiOperation(value = "根据staffid获取人员信息", httpMethod = "POST")
	@ApiImplicitParam(name = "id", value = "人员id,即staffid", required = true, paramType = "query", dataType = "String")
	public MessageResult queryEvaStaff(@RequestBody JSONObject param) {
		String schemeid = param.getString("schemeid");
		List<String> staffid = param.getObject("staffid", List.class);
		if(StringUtils.isEmpty(schemeid) || staffid == null || staffid.size() <= 0){
			throw new AdderBusinessException("不正确的参数","pm.i18n_pbc.pa.001");
		}
		// 查询重复的人。
		Map<String, PmStaff> staffList = StaffHelper.queryStaffByIds(staffid);
		Condition evaobj_cond = new Condition();
    	evaobj_cond.addExpression("schemeid", schemeid);
    	evaobj_cond.addExpression("staffid", staffid, Operator.IN);
    	List<EvaObject> evaobject_exit = groupService.queryEvaObjectByConditon(evaobj_cond,null);
    	StringBuffer name_exit = new StringBuffer();
    	for(EvaObject obj_exit : evaobject_exit){
    		String evastaffid = obj_exit.getStaffid();
    		PmStaff pmStaff = staffList.get(evastaffid);
    		if(name_exit.length() > 0){
    			name_exit.append(",").append(pmStaff.name);	
    		} else {
    			name_exit.append(pmStaff.name);
    		}
    		staffList.remove(evastaffid);
    	}
    	// 组织返回数据
    	HashMap<String,Object> hashMap = new HashMap<String,Object>();
    	String msg = "";
    	if(staffList.size() <= 0){
    		hashMap.put("state", "error");
    		msg= "添加的考核对象都已处于考核组内，请重新选择";
    	} else if(evaobject_exit.size() > 0) {
    		hashMap.put("state", "warn");
    		msg = "操作成功，但下列考核对象已处于考核组内,"+ name_exit.toString();
    	} else {
    		hashMap.put("state", "success");
    		msg = "操作成功";
    	}
    	hashMap.put("msg", msg);
    	hashMap.put("data", staffList.values());
    	// 返回数据
    	MessageResult result = new MessageResult("操作成功");
    	result.setData(hashMap);
    	result.setMessage(msg);
		return result;
	}
    
    /**
     * 保存考核对象（批量）
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/saveEvaObject", method = RequestMethod.POST)
    @ApiOperation(value = "保存考核对象（批量）", httpMethod = "POST")
    @ApiImplicitParam(name = "data", value = "保存考核对象（批量）的参数，参数格式:data:[{'id': '主键',   //新增是null'groupid': '组id','staffid': '人员id','schemeid': '方案id',}]", dataType = "String", paramType = "body", required = true)
    public MessageResult saveEvaObject(@RequestBody String data) {
        MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
        if (data == null || data.trim().length() == 0) {
            throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
        }
        JSONArray jsonArray = JSONArray.parseArray(StringEscapeUtils
                .unescapeHtml(data));
        List<EvaObject> objs = new ArrayList<EvaObject>();
        for (Object json : jsonArray) {
            JSONObject resultJson = JSONObject.parseObject(json.toString());
            EvaObject newObj = new EvaObject();
            newObj.setGroupid(resultJson.getString("groupid"));
            newObj.setSchemeid(resultJson.getString("schemeid"));
            newObj.setStaffid(resultJson.getString("staffid"));
            objs.add(newObj);
        }
        groupService.insertObject(objs);
        return result;
    }

	/**
	 * 保存组织考核考核对象（批量）
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/saveEvaObjectForOrg", method = RequestMethod.POST)
	@ApiOperation(value = "保存组织考核考核对象（批量）", httpMethod = "POST")
	@ApiImplicitParam(name = "data", value = "保存考核对象（批量）的参数，参数格式:data:[{'id': '主键',   //新增是null'groupid': '组id','staffid': '人员id','schemeid': '方案id',}]", dataType = "String", paramType = "body", required = true)
	public MessageResult saveEvaObjectForOrg(@RequestBody String data) {
		MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
		if (data == null || data.trim().length() == 0) {
			throw new AdderBusinessException("参数不能为空", "pm.i18n_core.comm.002");
		}
		JSONArray jsonArray = JSONArray.parseArray(StringEscapeUtils.unescapeHtml(data));
		groupService.addObjectForOrg(jsonArray);
		return result;
	}
    
    /**
     * 针对考核对象的考核人与审核人保存（批量）
     * 
     * @param data
     * @return
     */
    @RequestMapping(value = "/saveObjectAppraiser", method = RequestMethod.POST)
    @ApiOperation(value = "保存考核对象（批量）", httpMethod = "POST")
    @ApiImplicitParam(name = "data", value = "保存考核对象（批量）的参数，参数格式:data:[{'id': '主键',   //新增是null'groupid': '组id','staffid': '人员id','schemeid': '方案id',}]", dataType = "String", paramType = "body", required = true)
    public MessageResult saveObjectAppraiser(@RequestBody JSONObject data) {
    	MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
    	Scheme scheme = schemeService.saveObjectAppraiser(data);
    	result.setData(scheme);
        return result;
    }
    
    /**
     * 针对考核对象的考核人与审核人保存（批量）
     * 
     * @param data
     * @return
     */
    @RequestMapping(value = "/queryObjectAppraiser", method = RequestMethod.POST)
    @ApiOperation(value = "保存考核对象（批量）", httpMethod = "POST")
    @ApiImplicitParam(name = "data", value = "保存考核对象（批量）的参数，参数格式:data:[{'id': '主键',   //新增是null'groupid': '组id','staffid': '人员id','schemeid': '方案id',}]", dataType = "String", paramType = "body", required = true)
    public MessageResult queryObjectAppraiser(@RequestBody ArrayList<String> evaobject_ids) {
    	MessageResult result = new MessageResult("操作成功", null, "pm.i18n_core.comm.008");
    	List<EvaSetting> objectApprover = schemeService.getObjectApprover(evaobject_ids);
    	List<EvaSetting> objectAppraiser = schemeService.getObjectAppraiser(evaobject_ids);
    	HashMap<String,Object> data = new HashMap<String,Object>();
    	data.put("objectApprover", objectApprover);
    	data.put("objectAppraiser", objectAppraiser);
    	result.setData(data);
        return result;
    }

	/**
	 * 查询方案计划
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/querySchemePlan", method = RequestMethod.GET)
	@ApiOperation(value = "查询方案计划", httpMethod = "GET")
	@ApiImplicitParam(name = "schemeid", value = "方案主键id", dataType = "String", paramType = "query", required = true)
	public MessageResult querySchemePlan(String schemeid, Integer step) {
		MessageResult result = new MessageResult("");
		result.setData(schemeService.querySchemePlan(schemeid, step));
		return result;
	}
	
	/**
	 * 保存方案计划
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/saveSchemePlan", method = RequestMethod.POST)
	@ApiOperation(value = "保存方案计划", httpMethod = "POST")
	@ApiImplicitParam(name = "data", value = "参数格式:data:{'schemeid': '方案主键', ''  }", dataType = "String", paramType = "body", required = true)
	public MessageResult saveSchemePlan(@RequestBody JSONObject data) {
		MessageResult result = new MessageResult("保存成功!", null, "pm.i18n_core.comm.001");
		SchemePlan plan = new SchemePlan();
		plan.setId(data.getString("id"));
		plan.setSchemeid(data.getString("schemeid"));
		long lsDate = data.getLongValue("sdate");
		if (lsDate == 0)
			plan.setSdate(new Date());
		else
			plan.setSdate(new Date(lsDate));
		if (data.getLong("edate") != null)
			plan.setEdate(new Date(data.getLongValue("edate")));
		if (data.getInteger("workstep") != null)
			plan.setWorkstep(data.getInteger("workstep"));
		schemeService.saveSchemePlan(plan);
		result.setData(schemeService.querySchemePlan(plan.getSchemeid(), plan.getWorkstep()));
		return result;
	}
    
	/**
	 * 空接口（单点验证）
	 * 
	 * @return
	 */
	@RequestMapping(value = "/emptyRequest", method = RequestMethod.GET)
	public MessageResult emptyRequest() {
		MessageResult result = new MessageResult("操作成功", null, "pm.i18n_core.comm.008");
		return result;
	}
	
    /**
     * 将传入的人员集合中重复的去重
     *
     * @param list
     */
    private static void removeDuplicate(List<String> list) {
        LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
    }
    
    /**
     * add by zengcl 导入结果
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/resultImport", method = RequestMethod.POST)
    @ApiOperation(value = "通过导入Excel添加成绩", httpMethod = "POST")
    public MessageResult resultImport(HttpServletRequest request, HttpServletResponse response) {
        MessageResult result = new MessageResult("操作成功！", null, "pm.i18n_core.comm.008");
        String dbType = DialectHelper.getDBType();
        String url = iImportResultService.indicatorLibImport(request, response);
        Map<String,Object> dt = new HashMap<String,Object>();
        if(StringUtils.isNotEmpty(url)){
            dt.put("state",500);
            dt.put("url",url);
            dt.put("msg", "导入文件中存在错误数据,请检查后重新导入,");
            dt.put("dbType", dbType);
        } else {
            dt.put("state",200);
            dt.put("url","");
            dt.put("msg", "导入成功");
            dt.put("dbType", dbType);
        }
        result.setData(dt);
        return result;
    }

    /**
     *  add by zengcl 20201212 导出模板
     * @param request
     * @param response
     * @param schemeid
     * @return
     */
    @RequestMapping(value = "/exportTemplateBySchemeId", method = RequestMethod.GET)
    @ApiOperation(value = "根据该方案id导出模板", httpMethod = "GET")
    @ApiImplicitParam(name = "schemeid", value = "方案id", dataType = "String", paramType = "query", required = true)
    public MessageResult exportTemplateBySchemeId(HttpServletRequest request, HttpServletResponse
            response, String schemeid) {
        if (StringUtils.isNotEmpty(schemeid)) {
            Scheme scheme = daoex.load(Scheme.class, schemeid);
            schemeService.exportTemplateBySchemeId(request,response,scheme);
        } else {
            throw new AdderBusinessException("不正确的参数", "pm.i18n_pbc.pa.001");
        }
        return null;
    }

}
