package cn.com.countrygarden.bi.main.service.writtenExamination.impl;

import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.investment.InvestProjectInvestment;
import cn.com.countrygarden.bi.main.model.personnel.Personnel;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelTag;
import cn.com.countrygarden.bi.main.model.sharppathevaluation.PersonnelSharppathevaluation;
import cn.com.countrygarden.bi.main.model.writtenExamination.PersonnelSelectionType;
import cn.com.countrygarden.bi.main.model.writtenExamination.PersonnelSelectionscore;

import com.alibaba.druid.pool.DruidDataSource.CreateConnectionTask;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.ExcelCommon;
import cn.com.countrygarden.bi.main.util.MD5;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAdvisorMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelTagMapper;
import cn.com.countrygarden.bi.main.dao.writtenExamination.PersonnelSelectionTypeMapper;
import cn.com.countrygarden.bi.main.dao.writtenExamination.PersonnelSelectionscoreMapper;
import cn.com.countrygarden.bi.main.dto.PersonnelWrittenexaminationVO;
import cn.com.countrygarden.bi.main.dto.personnel.PersonExaminationDTO;
import cn.com.countrygarden.bi.main.dto.personnel.QueryCriteriaDTO;
import cn.com.countrygarden.bi.main.dto.sharppathevaluation.PersonnelSharppathevaluationDTO;
import cn.com.countrygarden.bi.main.dto.PersonInfoVO;
import cn.com.countrygarden.bi.main.dto.PersonnelTgDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import cn.com.countrygarden.bi.main.service.writtenExamination.PersonnelSelectionscoreService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;
import cn.com.countrygarden.bi.main.core.Response;

/**
 * 笔试表-业务逻辑层实现
 *
 * @author 汤婷
 * @email www.justintoforest@gamail.com
 * @url
 * @date 2018-10-17
 */
@Service
@Transactional
public class PersonnelSelectionscoreServiceImpl implements PersonnelSelectionscoreService {
	@Autowired
	private PersonnelSelectionscoreMapper personnelSelectionscoreMapper;
	
	 @Autowired
	    private PersonnelAdvisorMapper personnelAdvisorMapper;

	@Autowired
	private PersonnelMapper personnelMapper;
	@Autowired
	private cn.com.countrygarden.bi.main.dao.performance.bdpsndocMapper bdpsndocMapper;

	@Autowired
	private PersonnelSelectionTypeMapper personnelSelectionTypeMapper;
	@Autowired
	private ExcelCommon excelCommon;
	@Autowired
	private Environment env;

	@Autowired
	private PersonnelTagMapper personnelTagMapper;
	@Autowired
	private PersonnelCommenService personnelCommenService;

	@Override
	public Result queryById(PersonnelWrittenexaminationVO personnelWrittenexaminationVO) {
		Condition condition = null;
		condition = new Condition(Personnel.class);
		Personnel personnel = personnelMapper.selectByPrimaryKey(personnelWrittenexaminationVO.getPersonnelId());
		condition = new Condition(PersonnelSelectionType.class);
		condition.createCriteria().andEqualTo("selectType", personnelWrittenexaminationVO.getSelectType());
		List<PersonnelSelectionType> list = personnelSelectionTypeMapper.selectByCondition(condition);
		condition = new Condition(PersonnelSelectionscore.class);
		condition.createCriteria().andEqualTo("personnelId", personnelWrittenexaminationVO.getPersonnelId())
				.andEqualTo("personnelSelectionTypeId", list.get(0).getId())
				.andEqualTo("personneltagId", personnelWrittenexaminationVO.getPersonneltagId()).andEqualTo("flag", 0);
		List<PersonnelSelectionscore> scoreList = personnelSelectionscoreMapper.selectByCondition(condition);

		personnelWrittenexaminationVO.setCode(personnel.getUserId());
		personnelWrittenexaminationVO.setName(personnel.getName());
		personnelWrittenexaminationVO.setScoreList(scoreList);
		return Response.response(personnelWrittenexaminationVO);
	}

	public Result add(PersonnelWrittenexaminationVO personnelWrittenexaminationVO,
			ArrayList<PersonnelSelectionscore> writtenexaminationVOList, AccessToken accessToken) {
		// 查找选拔类型
		PersonnelSelectionType type = null;
		type = new PersonnelSelectionType();
		type.setSelectType(personnelWrittenexaminationVO.getSelectType());
		type = personnelSelectionTypeMapper.selectOne(type);
		if (type == null) {
			throw new ServiceException("没有查找到选择类型，添加失败");
		}
		// 添加选择得分
		PersonnelSelectionscore score = null;
		for (PersonnelSelectionscore voList : writtenexaminationVOList) {
			voList.setFlag(0);
			voList.setPersonnelId(personnelWrittenexaminationVO.getPersonnelId());
			voList.setPersonneltagId(personnelWrittenexaminationVO.getPersonneltagId());
			voList.setPersonnelSelectionTypeId(type.getId());
			voList.setCreatedBy(accessToken.getUserCode());
			voList.setCreatedDate(new Date());
		}
		if (writtenexaminationVOList.size() > 0) {
			int count = personnelSelectionscoreMapper.insertList(writtenexaminationVOList);
			if (count < 1) {
				throw new ServiceException("添加选拔类型失败");
			}
		}
		return Response.response("添加成功");
	}

	public Result edit(PersonnelWrittenexaminationVO personnelWrittenexaminationVO,
			ArrayList<PersonnelSelectionscore> selectionscoreList, AccessToken accessToken) {

		Condition condition = null;
		condition = new Condition(PersonnelSelectionType.class);
		condition.createCriteria().andEqualTo("selectType", personnelWrittenexaminationVO.getSelectType());
		List<PersonnelSelectionType> list = personnelSelectionTypeMapper.selectByCondition(condition);
		if (list.size() > 1) {
			throw new ServiceException("数据库存在脏数据");
		}

		condition = new Condition(PersonnelSelectionscore.class);
		condition.createCriteria().andEqualTo("personnelSelectionTypeId", list.get(0).getId())
				.andEqualTo("personnelId", personnelWrittenexaminationVO.getPersonnelId())
				.andEqualTo("personneltagId", personnelWrittenexaminationVO.getPersonneltagId()).andEqualTo("flag", 0);
		personnelSelectionscoreMapper.deleteByCondition(condition);
		// 添加选择得分
		List<PersonnelSelectionscore> scoreList = new ArrayList<PersonnelSelectionscore>();

		for (PersonnelSelectionscore voList : selectionscoreList) {
			voList.setFlag(0);
			voList.setPersonnelId(personnelWrittenexaminationVO.getPersonnelId());
			voList.setPersonneltagId(personnelWrittenexaminationVO.getPersonneltagId());
			voList.setPersonnelSelectionTypeId(list.get(0).getId());
			voList.setUpdatedBy(accessToken.getAccessToken());
			voList.setUpdatedDate(new Date());
		}

		if (selectionscoreList.size() > 0) {
			int count = personnelSelectionscoreMapper.insertList(selectionscoreList);
			if (count < 1) {
				throw new ServiceException("编辑失败");
			}
		}

		return Response.response("编辑成功");

	}

	// 上传附件
	public Result FileUpload(MultipartFile attach, PersonnelWrittenexaminationVO personnelWrittenexaminationVO,
			HttpServletRequest request) {
		// 上传文件处理
		String path = "";
		String fileName = "";
		path = env.getProperty("resident.file.path");
		String accessPath = env.getProperty("resident.file.url.base");
		if (StringUtils.isEmpty(path)) {
			path = request.getServletContext().getRealPath("");
		}
		if (!attach.isEmpty()) {
			String oldFileName = attach.getOriginalFilename();// 原文件名
			personnelWrittenexaminationVO.setAppendixName(oldFileName);
			Instant instant = Instant.now();
			LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

			fileName = attach.getOriginalFilename();

			// 文件存放路径 /uploadFile/年/月/日/时/分/秒
			String saveDirectory = "/uploadFile/" + dateTime.getYear() + "/" + dateTime.getMonthValue() + "/"
					+ dateTime.getDayOfMonth() + "/" + dateTime.getHour() + dateTime.getMinute() + dateTime.getSecond();

			String saveFileName = saveDirectory + "/" + MD5.GetMD5Code(dateTime.toString())
					+ FilenameUtils.getBaseName(fileName) + "." + FilenameUtils.getExtension(fileName);

			File dir = new File(path + saveDirectory);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File saveFile = new File(path + saveFileName);
			// 保存
			try {
				((CommonsMultipartFile) attach).getFileItem().write(saveFile);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServiceException("上传文件失败");

			}
			personnelWrittenexaminationVO.setAppendix(accessPath + saveFileName);
			// }
		}
		return Response.response(personnelWrittenexaminationVO);

	}

	public Result queryPageList(PersonInfoVO personInfoVO, int page, int size, AccessToken accessToken) {
		// 根据登录账号进行数据过滤
		Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
        List<String> userquyu= new ArrayList<>();
		
    	List<DupOrgan> result=null;

		for (Object obj : rolesMap.keySet()) {
			String key = (String) obj;
			if (key.equals("gj_admin")) {
				userquyu = null;
				rolesMap.put("identitys", null);
				break;
			} else if (key.equals("role")) {
				return null;
			} else if (key.equals("gj_Area")) {
				//List<String> liuserquyu = personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
				//userquyu = liuserquyu.get(0);
				rolesMap.put("identitys", null);
				 result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);

				for (int i = 0; i < result.size(); i++) {
					userquyu.add(result.get(i).getOrganName());
				}
			}

		}
		Page<PersonnelTgDTO> pageList = PageHelper.startPage(page, size);

		rolesMap.put("userquyu", userquyu);
		List<PersonnelTgDTO> personals = personnelSelectionscoreMapper.findExistWrittenexaminationAll(personInfoVO,
				rolesMap);
		List<PersonExaminationDTO<PersonnelSelectionscore>> results = new ArrayList<>(personals.size());
		for (PersonnelTgDTO personnel : personals) {
			// 获取制定用户的选拔分数列表
			List<PersonnelSelectionscore> personnelWrittenexaminationVOType1 = getExaminationType1(
					personnel.getPersonnelId(), personnel.getPersonneltagId());
			// 获取制定用户的晋升分数列表
			List<PersonnelSelectionscore> personnelWrittenexaminationVOType2 = getExaminationType2(
					personnel.getPersonnelId(), personnel.getPersonneltagId());
			// 构造用户数据
			results.add(new PersonExaminationDTO<PersonnelSelectionscore>(personnel, personnelWrittenexaminationVOType1,
					personnelWrittenexaminationVOType2));

		}
		if (personals.size() < 1) {
			return Response.response();
		}
		PageData data = new PageData(pageList);
		data.setData(results);
		return Response.response(data);
	}

	private List<PersonnelSelectionscore> getExaminationType1(Integer pid, Integer tagId) {
		Condition condition = new Condition(PersonnelSelectionscore.class);
		Criteria criteria = condition.createCriteria();
		criteria.andEqualTo("personnelId", pid).andEqualTo("personneltagId", tagId)
				.andEqualTo("personnelSelectionTypeId", 1).andEqualTo("flag", 0);
		condition.orderBy("id").desc();
		return personnelSelectionscoreMapper.selectByCondition(condition);
	}

	private List<PersonnelSelectionscore> getExaminationType2(Integer pid, Integer tagId) {
		Condition condition2 = new Condition(PersonnelSelectionscore.class);
		Criteria criteria2 = condition2.createCriteria();
		criteria2.andEqualTo("personnelId", pid).andEqualTo("personneltagId", tagId)
				.andEqualTo("personnelSelectionTypeId", 2).andEqualTo("flag", 0);
		condition2.orderBy("id").desc();
		return personnelSelectionscoreMapper.selectByCondition(condition2);
	}

	public Result excelImport(QueryCriteriaDTO queryCriteriaDTO, AccessToken accessToken, HttpServletResponse response)
			throws IOException {

		// excel模板路径
		String path = "";
		try {
			path = this.getClass().getClassLoader().getResource("/").toURI().getPath() + "/excel/笔试参考模板.xlsx";
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		File fi = new File(path);
		InputStream in = new FileInputStream(fi);
		// 读取excel模板
		XSSFWorkbook wb = new XSSFWorkbook(in);
		// 读取excel模板

		XSSFSheet sheet1 = wb.getSheetAt(0);
		Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
        List<String> userquyu= new ArrayList<>();
		
    	List<DupOrgan> result=null;
		for (Object obj : rolesMap.keySet()) {
			String key = (String) obj;
			if (key.equals("gj_admin")) {
				userquyu = null;
				rolesMap.put("identitys", null);
				break;
			} else if (key.equals("role")) {
				return null;
			} else if (key.equals("gj_Area")) {
//				List<String> liuserquyu = personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
//				userquyu = liuserquyu.get(0);
				rolesMap.put("identitys", null);
				 result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
					for (int i = 0; i < result.size(); i++) {
						userquyu.add(result.get(i).getOrganName());
					}
			}

		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");

		String[] personnelId;
		if (queryCriteriaDTO.getPersonnelIds() != null) {
			personnelId = queryCriteriaDTO.getPersonnelIds().split(",");
			queryCriteriaDTO.setPersonnelId(personnelId);
		}
		List<PersonnelWrittenexaminationVO> list = new ArrayList<PersonnelWrittenexaminationVO>();

		List<PersonnelWrittenexaminationVO> allList = personnelSelectionscoreMapper
				.findPersonnelWrittenexaminationVOexportExcelAll1(queryCriteriaDTO, rolesMap);
		List<PersonnelSelectionscore> newList = null;
		// is_all(1:导出全部，0：导出最新)
		if (queryCriteriaDTO.getIs_all() != null && queryCriteriaDTO.getIs_all() == 0) {
			newList = this.selectpersonnelWrittenexaminationNewest(rolesMap);
		}
		if (newList != null && newList.size() > 0) {

			for (PersonnelWrittenexaminationVO dto : allList) {
				for (PersonnelSelectionscore newDTO : newList) {
					if (dto.getPersonnelId().equals(newDTO.getPersonnelId())
							&& dto.getPersonnelSelectionTypeId() == newDTO.getPersonnelSelectionTypeId()
							&& sdf.format(dto.getSelectionTime()).equals(sdf.format(newDTO.getSelectionTime()))) {
						list.add(dto);
					}
				}
			}
		} else {
			list.addAll(allList);
		}

		if (list.size() > 0) {
			importPersonnelWrittenexaminationVO(sheet1, list);
		}
		excelCommon.downloadExcel(wb, "笔试明细表", response);

		return Response.response(list);
	}

	private void importPersonnelWrittenexaminationVO(XSSFSheet sheet, List<PersonnelWrittenexaminationVO> list) {

		int count = 2;
		int copyRow = 4;
		for (PersonnelWrittenexaminationVO dto : list) {
			excelCommon.copyRows(sheet, 4, 4, copyRow);
			copyRow++;
			count++;
			DateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // HH表示24小时制；
			XSSFCell cell = null;
			cell = sheet.getRow(count).getCell(0);// 人员编号
			cell.setCellValue(dto.getRegionName() == null ? "" : dto.getRegionName());
			cell = sheet.getRow(count).getCell(1);// 人员编号
			cell.setCellValue(dto.getCode() == null ? "" : dto.getCode());
			cell = sheet.getRow(count).getCell(2);// 人员名称
			cell.setCellValue(dto.getName() == null ? "" : dto.getName());
			cell = sheet.getRow(count).getCell(3);// 人员标签
			cell.setCellValue(dto.getName() == null ? "" : dto.getPersonneltagIdentity());
			cell = sheet.getRow(count).getCell(4);// 时间
			cell.setCellValue(dto.getSelectionTime() == null ? "" : dFormat.format(dto.getSelectionTime()));
			cell = sheet.getRow(count).getCell(5);// 得分类型
			cell.setCellValue(dto.getPersonnelSelectionTypeId() == 1 ? "选拔" : "晋升");
			cell = sheet.getRow(count).getCell(6);// 得分描述
			cell.setCellValue(dto.getSelectiondescription() == null ? "" : dto.getSelectiondescription());
			cell = sheet.getRow(count).getCell(7);// 得分
			cell.setCellValue(dto.getScore());
		}
	}

	@Override
	public Result del(Integer personnelId, Integer personneltagId) {

		Condition condition = null;
		condition = new Condition(PersonnelSelectionscore.class);
		condition.createCriteria().andEqualTo("personnelId", personnelId).andEqualTo("personneltagId", personneltagId);
		List<PersonnelSelectionscore> scoreList = personnelSelectionscoreMapper.selectByCondition(condition);
		for (PersonnelSelectionscore score : scoreList) {
			score.setFlag(1);
			personnelSelectionscoreMapper.updateByPrimaryKeySelective(score);
		}

		return Response.response();
	}

	@Override
	public Result exportExcel(String fileName, String createName, MultipartFile uploadfile, Integer radio,
			AccessToken accessToken) {

		//List<String> liuserquyu = personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());

		Workbook xwb = null;
		BufferedInputStream bf = null;
		Sheet sheet = null;
		List<PersonnelSelectionscore> personnelSelectionscoreAddList = null;
		List<PersonnelSelectionscore> personnelSelectionscoreUpdateList = null;
		List<PersonnelSelectionscore> tagList = new ArrayList<PersonnelSelectionscore>();
		Set<PersonnelSelectionscore> set = new HashSet<PersonnelSelectionscore>();
		try {
			bf = new BufferedInputStream(uploadfile.getInputStream());

			if (fileName.endsWith("xls")) { // Excel&nbsp;2003
				xwb = new HSSFWorkbook(bf);
			} else if (fileName.endsWith("xlsx")) { // Excel 2007/2010
				xwb = new XSSFWorkbook(bf);
			}
			sheet = xwb.getSheetAt(0);// 获取第几个页面0开始
			// 存放添加数据
			personnelSelectionscoreAddList = new LinkedList<PersonnelSelectionscore>();
			// 存放更新数据
			personnelSelectionscoreUpdateList = new LinkedList<PersonnelSelectionscore>();

			Personnel personnel = null;
			PersonnelTag personnelTag = null;
			PersonnelSelectionscore personnelSelectionscore = null;
			Condition condition = null;
			int number = 0;
			for (int i = 3; i <= sheet.getLastRowNum(); i++) {
				System.out.println(sheet.getLastRowNum());
				Row row = sheet.getRow(i);
				if (row == null) {

					continue;
				}
				if (!excelCommon.isRowNotEmpty(row)) {
					System.out.println("空");
					continue;
				}
				// 怎么判断是否为结束的字段.(是否为合并单元格;

				if (row.getCell(0) == null) {
					return Response.response("第" + (i + 1) + "行，人员编号为空,导入失败。");
				} else if (row.getCell(1) == null) {
					return Response.response("第" + (i + 1) + "行，人员姓名为空,导入失败。");
				} else if (row.getCell(2) == null) {
					return Response.response("第" + (i + 1) + "行，人员标签为空,添加失败。");
				} else if (row.getCell(3) == null) {
					return Response.response("第" + (i + 1) + "行，笔试类型为空,添加失败。");
				} else if (row.getCell(5) == null) {
					return Response.response("第" + (i + 1) + "行，得分不能为空,添加失败。");
				} else {
					number++;
					PersonnelWrittenexaminationVO personnelWrittenexaminationVO = this.importData(row);
					personnel = new Personnel();
					personnel = bdpsndocMapper.findByPersonInfoByCodeOrName(personnelWrittenexaminationVO.getCode(),
							personnelWrittenexaminationVO.getName());
					if (personnel == null) {
						return Response.response("第" + (i + 1) + "行用户编号为:"+personnelWrittenexaminationVO.getCode()+"+姓名在员工信息数据或工作记录数据不存在,导入失败。");

					} else {
						condition = new Condition(Personnel.class);
						condition.createCriteria().andEqualTo("userId", personnel.getUserId()).andEqualTo("name",
								personnel.getName());

						List<Personnel> personnelOne = personnelMapper.selectByCondition(condition);

						condition = new Condition(PersonnelTag.class);
						condition.createCriteria().andEqualTo("userId", personnel.getUserId()).andEqualTo("identity",
								personnelWrittenexaminationVO.getPersonneltagIdentity());
						List<PersonnelTag> personnelTagList = personnelTagMapper.selectByCondition(condition);

						if (personnelOne.size() < 1) {
							personnel.setCreatedBy(accessToken.getUserCode());
							personnel.setCreatedDate(new Date());
							personnelMapper.insertSelective(personnel);
						} else {
							personnel = personnelOne.get(0);
						}

//						String userquyu = liuserquyu.get(0);
//						String findboolean = personnelCommenService.findboolean(accessToken, personnel.getUserId(),
//								null, userquyu);
//						if (findboolean.equals("role") || findboolean.equals("0")) {
//							throw new ServiceException(
//									"第" + (i + 1) + "行的用户编号:" + personnel.getUserId() + ",导入权限不足，导入失败");
//
//						}
//
//						if (findboolean.equals("gj_admin")) {
//							userquyu = null;
//
//						} else if (findboolean.equals("gj_Area")) {
//
//							userquyu = liuserquyu.get(0);
//						} else if (personnelCommenService.findboolean(accessToken, null,
//								personnelWrittenexaminationVO.getPersonneltagIdentity(), null).equals("identitys")) {
//							userquyu = null;
//
//						}

						Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());    	
				    	 List<String> userquyu=new ArrayList<>();
				         List<DupOrgan> resuaslt=null;
				        
				    	for (Object obj : rolesMap.keySet()) {
				    		String key = (String) obj;
				    		if (key.equals("gj_admin")) {
				    			 userquyu=null;
				    			 List<PersonInfoVO> personInfoCodeOrId=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(personnel.getUserId(),null,null);
				    			 if (personInfoCodeOrId.size()==0) {
		                   				throw new ServiceException("用户编号" + personnel.getUserId() + "有误或权限不足，无法添加");
									}
				    			 rolesMap.put("identitys", null);
				    			 break;
				    		}else if (key.equals("role")) {
				    			throw new ServiceException("当前账号导入权限不足，导入失败");
							}else if (key.equals("gj_Area")) {
								//List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
								//userquyu=liuserquyu.get(0);
								resuaslt = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
								for (int q = 0; q < resuaslt.size(); q++) {
									userquyu.add(resuaslt.get(q).getOrganName());
								}
								
								List<PersonInfoVO> personInfoCodeOrId=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(personnel.getUserId(),null,userquyu);
								if (personInfoCodeOrId.size()==0) {
	                   				throw new ServiceException("用户编号" + personnel.getUserId() + "有误或权限不足，无法添加");
								}
							}
				    		
				    	}
				    	
						personnelSelectionscore = new PersonnelSelectionscore();
						PersonnelSelectionscore personnelSelectionscore1 = new PersonnelSelectionscore();
						// 处理标签
						if (personnelTagList.size() < 1) {
							// 1.用户编号+标签没有查到时
							return Response.response("第" + (i + 1) + "行用户编号为:"+personnel.getUserId()+"的人员标签不存在,导入失败。");
						} else {
							personnelTag = personnelTagList.get(0);
						}
						personnelSelectionscore.setPersonnelId(personnel.getId());
						personnelSelectionscore.setPersonneltagId(personnelTag.getId());
						personnelSelectionscore.setFlag(0);
						condition = new Condition(PersonnelSelectionType.class);
						condition.selectProperties("id");
						condition.createCriteria().andEqualTo("selectType",
								personnelWrittenexaminationVO.getSelectType());
						List<PersonnelSelectionType> type = personnelSelectionTypeMapper.selectByCondition(condition);
						if (type.size() == 1) {
							personnelSelectionscore.setPersonnelSelectionTypeId(type.get(0).getId());
						} else {
							throw new ServiceException("第" + (i + 1) + "行用户编号为:"+personnel.getUserId()+"的得分类型有误，导入失败");
						}

						List<PersonnelSelectionscore> list = personnelSelectionscoreMapper
								.select(personnelSelectionscore);

						personnelSelectionscore
								.setSelectiondescription(personnelWrittenexaminationVO.getSelectiondescription());

						personnelSelectionscore.setCreatedName(createName);
						personnelSelectionscore.setScore(personnelWrittenexaminationVO.getScore());
						personnelSelectionscore.setSelectionTime(personnelWrittenexaminationVO.getSelectionTime());

						personnelSelectionscore.setCreatedBy(accessToken.getUserCode());
						personnelSelectionscore.setCreatedDate(new Date());
						// 保存用户+标签+flag=0的数据已经存在
						if (list != null && list.size() > 0) {
							// raido==0跳过，不添加，1：覆盖原数据
							if (radio == 1) {
								personnelSelectionscore1.setPersonnelId(personnel.getId());
								personnelSelectionscore1.setPersonneltagId(personnelTag.getId());
								personnelSelectionscore1.setFlag(0);
								personnelSelectionscore1.setPersonnelSelectionTypeId(type.get(0).getId());
								set.add(personnelSelectionscore1);
								personnelSelectionscoreAddList.add(personnelSelectionscore);
							}
						} else {
							personnelSelectionscoreAddList.add(personnelSelectionscore);
						}

					}
				}
			}

			if (CollectionUtils.isNotEmpty(personnelSelectionscoreAddList)) {
				// raido==0跳过，不添加，1：覆盖原数据

				if (radio == 1 && set != null && set.size() > 0) {
					tagList = new ArrayList<PersonnelSelectionscore>(set);
					for (PersonnelSelectionscore score : tagList) {
						personnelSelectionscoreMapper.delete(score);
					}
					// personnelSelectionscoreMapper.deletePersonnelSelectionscore(tagList);
				}
				int Count = personnelSelectionscoreMapper.insertList(personnelSelectionscoreAddList);

				if (personnelSelectionscoreAddList.size() != Count) {
					try {
						throw new ServiceException("导入失败！");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			if (number == 0) {
				return Response.response("没有数据导入");
			}
		} catch (IOException e1) {
			e1.printStackTrace();
			throw new ServiceException("导入失败！请稍后重试！");
		}

		return Response.response("导入成功");

	}

	public PersonnelWrittenexaminationVO importData(Row row) {
		SimpleDateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // HH表示24小时制；
		XSSFCell cell = null;
		PersonnelWrittenexaminationVO personnelWrittenexaminationVO = new PersonnelWrittenexaminationVO();
		cell = (XSSFCell) row.getCell(0);// 0.
		cell.setCellType(CellType.STRING);
		personnelWrittenexaminationVO.setCode(cell.getStringCellValue());
		cell = (XSSFCell) row.getCell(1);// 0.
		cell.setCellType(CellType.STRING);
		personnelWrittenexaminationVO.setName(cell.getStringCellValue());

		cell = (XSSFCell) row.getCell(2);// 0.
		cell.setCellType(CellType.STRING);
		personnelWrittenexaminationVO.setPersonneltagIdentity(cell.getStringCellValue());
		cell = (XSSFCell) row.getCell(3);// 0.

		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm");

		try {
			personnelWrittenexaminationVO
					.setSelectionTime(dateformat.parse(excelCommon.getDate(cell, "yyyy/MM/dd HH:mm")));
		} catch (ParseException e) {

			throw new ServiceException("第" + (row.getRowNum() + 1) + "行用户编号为"+personnelWrittenexaminationVO.getCode()+"的时间格式不符合规范，导入失败");
		}
		cell = (XSSFCell) row.getCell(4);// 0.
		cell.setCellType(CellType.STRING);
		personnelWrittenexaminationVO.setSelectType(cell.getStringCellValue());

		if (personnelWrittenexaminationVO.getSelectType().equals("选拔")) {
			personnelWrittenexaminationVO.setSelectType("1");
		} else if (personnelWrittenexaminationVO.getSelectType().equals("晋升")) {
			personnelWrittenexaminationVO.setSelectType("2");
		} else {
			throw new ServiceException("第" + (row.getRowNum() + 1) + "行用户编号为"+personnelWrittenexaminationVO.getCode()+"的笔试类型不符合规范，导入失败");
		}
		cell = (XSSFCell) row.getCell(5);// 0.
		cell.setCellType(CellType.STRING);
		personnelWrittenexaminationVO.setSelectiondescription(cell.getStringCellValue());
		cell = (XSSFCell) row.getCell(6);// 0.
		cell.setCellType(CellType.STRING);
		try {
			personnelWrittenexaminationVO.setScore(Double.valueOf(cell.getStringCellValue()));
		} catch (NumberFormatException e) {
			throw new ServiceException("第" + (row.getRowNum() + 1) + "行用户编号为"+personnelWrittenexaminationVO.getCode()+"的分数请输入数字类型，导入失败");
		}

		return personnelWrittenexaminationVO;
	}

	public List<PersonnelSelectionscore> selectpersonnelWrittenexaminationNewest(Map<String, Object> rolesMap) {
		List<PersonnelSelectionscore> list = personnelSelectionscoreMapper
				.selectpersonnelWrittenexaminationNewest(rolesMap);
		return list;
	}

	@Override
	public Result delpiliang(String personnelId, String personneltagId, String personnelSelectionTypeId) {
		List<String> perslId = JSONArray.parseArray(personnelId, String.class);
		List<String> perstagId = JSONArray.parseArray(personneltagId, String.class);
		List<String> perselecTypeId = JSONArray.parseArray(personnelSelectionTypeId, String.class);
		
		personnelSelectionscoreMapper.delpiliang(perslId,perstagId,perselecTypeId);
		
		return Response.response("删除成功");
	}

}
