package cn.com.countrygarden.bi.main.service.personnel.impl;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAdvisorMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelMapper;
import cn.com.countrygarden.bi.main.dto.LabelVo;
import cn.com.countrygarden.bi.main.dto.PersonInfoVO;
import cn.com.countrygarden.bi.main.dto.PersonnelTgDTO;
import cn.com.countrygarden.bi.main.dto.personnelTagDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelpascTagidDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.personnel.Personnel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.primitives.Ints;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelTag;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelTagMapper;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelTagService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 人才标签-业务逻辑层实现
 *
 * @author 李森林
 * @email www.justintoforest@gamail.com
 * @url www.yuhi.com.cn
 * @date 2018-07-10
 */
@Service
@Transactional
public class PersonnelTagServiceImpl implements PersonnelTagService{
	
	@Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private PersonnelTagMapper personnelTagMapper;
    @Autowired
    private PersonnelMapper personnelMapper;
    
    @Autowired
    private PersonnelCommenService personnelCommenService;
    
    @Autowired
    private PersonnelAdvisorMapper personnelAdvisorMapper;

	@Override
    public Result queryPageList(LabelVo label, int page, int size,AccessToken accessToken) {
//    	List<String> userIds= personnelCommenService.findRole(accessToken);
//		if(userIds!=null) {
//			if(userIds.size()==0||userIds.get(0).equals("-1")) {
//				//没有匹配的角色或没有查找到数据
//				return Response.response();
//			}		
//		}
    	//List<String> tbHsp =personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
    	
    	
    	Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());    	
    	//String userquyu=null;
    	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")) {
				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());
				}
				
			}
    		
    	}
//    	List<personnelTagDTO> dtoper=new ArrayList<personnelTagDTO>();
//      Page<Object> object = PageHelper.startPage(page, size);
//    	if (result!=null&&result.size()!=0) {
//    		for (int i = 0; i < result.size(); i++) {
//    			List<personnelTagDTO> persapper=personnelTagMapper.selectByNameOrIdentity(label,rolesMap,result.get(i).getOrganName());
//    			if (persapper.size()!=0) {
//    				dtoper.addAll(persapper);
//				}    		
//    		}
//		}else {
//			dtoper = personnelTagMapper.selectByNameOrIdentity(label,rolesMap,null);
//		}
//    	
//        if(label!=null) {
//        	userquyu=null;
//        }        
    	Page<Object> object = PageHelper.startPage(page, size);
        List<personnelTagDTO> dto=personnelTagMapper.selectByNameOrIdentity(label,rolesMap,userquyu);
        System.out.println(dto.size());
        for (personnelTagDTO tagDTO : dto) {
            Condition condition=new Condition(PersonnelTag.class);
            condition.excludeProperties("userId");
            Example.Criteria criteria = condition.createCriteria();
            criteria.andEqualTo("userId",tagDTO.getUserId());
            if(StringUtils.isNotBlank(label.getIdentity())){
                criteria.andLike("identity","%"+label.getIdentity()+"%");
            }                
            tagDTO.setTagsList(personnelTagMapper.selectByCondition(condition));
        }
        PageData pageData = new PageData(object);
        pageData.setData(object.getResult());
        return Response.response(pageData);
    }

    @Override
    public Result queryById(Integer id) {
        personnelTagDTO dto = personnelTagMapper.selectDTOByPrimaryKey(id);
        Condition condition=new Condition(PersonnelTag.class);
        condition.excludeProperties("userId");
        condition.createCriteria().andEqualTo("userId",dto.getUserId());
        dto.setTagsList(personnelTagMapper.selectByCondition(condition));
        return Response.response(dto);
    }




    @Override
    public Result del(String uid) {
    	
    	List<PersonnelpascTagidDTO> selectdeleperid=personnelTagMapper.selectdeleperid(uid);
    	if (selectdeleperid.get(0)!=null) {
            if (selectdeleperid.get(0).getPapersonnelid()!=null||selectdeleperid.get(0).getPcpersonnelid()!=null||selectdeleperid.get(0).getPspersonnelid()!=null||selectdeleperid.get(0).getSpersonnelid()!=null) {
                return Response.responseFail("此标签和其他功能关联，不可删除");
              //throw new ServiceException("此标签和其他功能关联，不可删除");
            } else {
            	Condition condition=new Condition(Personnel.class);
                condition.createCriteria().andEqualTo("userId",uid);
                personnelMapper.deleteByCondition(condition);
                Condition condition1=new Condition(Personnel.class);
                condition1.createCriteria().andEqualTo("userId",uid);
                personnelTagMapper.deleteByCondition(condition1);
                return Response.response();
            }
        }else {
        	Condition condition=new Condition(Personnel.class);
            condition.createCriteria().andEqualTo("userId",uid);
            personnelMapper.deleteByCondition(condition);
            Condition condition1=new Condition(Personnel.class);
            condition1.createCriteria().andEqualTo("userId",uid);
            personnelTagMapper.deleteByCondition(condition1);
            return Response.response();
        }
    	
        
    }

    @Override
    public Result add(Personnel personnel, String tagsList, AccessToken accessToken) {
        Condition condition=new Condition(Personnel.class);
        condition.createCriteria().andEqualTo("userId",personnel.getUserId());
        int count = personnelMapper.selectCountByCondition(condition);
        if(count==0){
            personnel.setCreatedBy(accessToken.getUserCode());
            personnel.setCreatedDate(new Date());
            personnelMapper.insert(personnel);
        }
        personnelTagMapper.insertList(parseTagJson(tagsList,accessToken,personnel.getUserId()));
        return Response.response();
    }

    @Override
    public Result edit(Personnel personnel, String tagsList, AccessToken accessToken) {


        personnelTagMapper.deleteuserid(personnel.getUserId());
        PersonnelTag persotag=null;
        JSONArray ary = (JSONArray) JSON.parseArray(tagsList);
        for (int i = 0; i < ary.size(); i++) {
            JSONObject obj = ary.getJSONObject(i);
            persotag=new PersonnelTag();
            if (obj.getInteger("id")!=null) {
                persotag.setId(obj.getInteger("id"));
                persotag.setUserId(personnel.getUserId());
                persotag.setIdentity(obj.getString("identity"));
                persotag.setGraduates(obj.getString("graduates"));
                persotag.setCreatedBy(obj.getString("createdBy"));
                persotag.setCreatedDate(obj.getDate("createdDate"));
                personnelTagMapper.inserttag(persotag);
            }else {
                persotag=new PersonnelTag();
                persotag.setUserId(personnel.getUserId());
                persotag.setIdentity(obj.getString("identity"));
                persotag.setGraduates(obj.getString("graduates"));
                persotag.setCreatedBy(accessToken.getUserCode());
                persotag.setCreatedDate(new Date());
                personnelTagMapper.insertSelective(persotag);
            }
        }

        //personnel.setUpdatedBy(accessToken.getUserCode());
        // personnel.setUpdatedDate(new Date());
        // personnelMapper.updateByPrimaryKey(personnel);

        //Condition condition1=new Condition(Personnel.class);
        //condition1.createCriteria().andEqualTo("userId",personnel.getUserId());
        // personnelTagMapper.deleteByCondition(condition1);

        //if(StringUtils.isNotBlank(tagsList)) {
        //personnelTagMapper.insertList(parseTagJson(tagsList,accessToken,personnel.getUserId()));
        // }

        return Response.response();
    }

    @Override
    public Result excelToObject(MultipartFile mf, String fileName, Integer radio, String userCode,AccessToken accessToken) {
    	
    	List<String> cuowuxin=new ArrayList<>();
    	List<DupOrgan> result=null;
        Workbook xwb = null;
        BufferedInputStream bf = null;
        Sheet sheet = null;
        try {
            bf = new BufferedInputStream(mf.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开始
            List<Personnel> personnelList=new LinkedList<>();
            List<PersonnelTag> tagList=new LinkedList<>();
            List<Personnel> uplabelList=new LinkedList<>();
            List<String> uplabelIds=new LinkedList<>();


            for (int i = 5; i <= sheet.getPhysicalNumberOfRows(); i++) {
                Row row = sheet.getRow(i);
                //怎么判断是否为结束的字段.(是否为合并单元格;
                if (row == null){
                    break;
                }
                if (row.getCell(0) == null){
                    try {
                        throw new Exception("第" + i + "行，区域Id为空。");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                Personnel personnel = new Personnel();
                // 获取数据

                personnel.setName(row.getCell(9).getStringCellValue());

                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);

                personnel.setUserId(row.getCell(10).getStringCellValue()+"");
                personnel.setCreatedDate(new Date());
                personnel.setCreatedBy(userCode);
                
                if (personnel.getUserId().equals("")||personnel.getUserId()==null) {
					continue;
				}

                                
//              添加标签
                for (int j = 0; j <= 6; j+=2) {
    
                	
                    if(StringUtils.isBlank(row.getCell((j+1)).getStringCellValue())){
                        continue;
                    }
                    String identity=null;
				
                    String graduates=row.getCell((j+2)).getStringCellValue();
                	                  
                    Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
                    List<String> userquyu=new ArrayList<>();
                	
                   	for (Object obj : rolesMap.keySet()) {
                   		String key = (String) obj;
                   		if (key.equals("gj_admin")) {
                   			List<PersonInfoVO> personInfoCodeOrId=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(personnel.getUserId(),null,null);
                   			if (personInfoCodeOrId.size()==0) {
                   				cuowuxin.add(personnel.getUserId());
//                   				throw new ServiceException("第" + i + "行"+"用户编号" 
//                   			+ personnel.getUserId() +",姓名："+personnel.getName()+ "有误或权限不足，无法添加");
							}
                   			userquyu=null;
                   			identity=row.getCell((j+1)).getStringCellValue();
                   			 rolesMap.put("identitys", null);
                   			 break;
                   		}else if (key.equals("role")) {
                   			throw new ServiceException("当前账号权限不足，请检查确认好再导入");                
               			}else if (key.equals("gj_Area")) {
               				identity=row.getCell((j+1)).getStringCellValue();
               				result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
               				for (int q = 0;q < result.size(); q++) {
               				userquyu.add(result.get(q).getOrganName());
               				}
               				
               				if(userquyu.size()==0) {
               					throw new ServiceException("该登陆账号查找不到区域,无法添加导入");
               				}
                           	List<PersonInfoVO> personInfoCodeOrId=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(personnel.getUserId(),null,userquyu);
                           	if (personInfoCodeOrId.size()==0) {
                           		//throw new ServiceException("第" + i + "行"+"用户编号" + personnel.getUserId() +",姓名："+personnel.getName()+ "有误或权限不足，无法添加");
                           		cuowuxin.add(personnel.getUserId());
							}
                         
               			}
                   		
                   	}
                   	identity=row.getCell((j+1)).getStringCellValue();
                    
                    int count=0;
                    if(radio==1) {//覆盖前检查
                    	  List<PersonnelTgDTO> perslTgDTOs=personnelTagMapper.personneltag(personnel.getUserId(), null);
                    	  
                    	  if (perslTgDTOs.size()>0) {
							   for (int k = 0; k < perslTgDTOs.size(); k++) {
								   List<PersonnelpascTagidDTO> tagid=personnelTagMapper.tagid(perslTgDTOs.get(k).getPersonneltagId());
								   if (tagid.get(0)!=null) {
									   if (tagid.get(0).getPatagid()!=null||tagid.get(0).getPctagid()!=null||tagid.get(0).getPstagid()!=null||tagid.get(0).getStagid()!=null) {
										   cuowuxin.add(personnel.getUserId());
							            }
								   }
							}
						}
                    }
                   
                    
                    if(radio==0){//合并标签时做现有标签的检查
                        Condition condition=new Condition(PersonnelTag.class);
                        condition.createCriteria()
                                .andEqualTo("userId", personnel.getUserId())
                                .andEqualTo("identity",identity);
                                //.andEqualTo("graduates",graduates);
                        count = personnelTagMapper.selectCountByCondition(condition);
                    }
                    if(count==0){
                        tagList.add(new PersonnelTag(personnel.getUserId(),identity,graduates,userCode));
                    }
                }

                //去重操作
                Condition condition=new Condition(Personnel.class);
                condition.createCriteria().andEqualTo("userId", personnel.getUserId());
                int count = personnelMapper.selectCountByCondition(condition);
                if(count==0){
                    personnelList.add(personnel);
                }else{
                    uplabelIds.add(personnel.getUserId());
                    uplabelList.add(personnel);
                }

            }
            
            if (cuowuxin.size()!=0) {
            	//throw new ServiceException();
            	return Response.response(cuowuxin);
			}

//		处理特殊数据
            switch (radio){
                case 1: //覆盖标签数据
                    Condition condition=new Condition(PersonnelTag.class);
                    if(uplabelIds.size()!=0) {
                    	 condition.createCriteria().andIn("userId",uplabelIds);
                         personnelTagMapper.deleteByCondition(condition);
                         if(tagList!=null&&tagList.size()!=0)
                             personnelTagMapper.insertList(tagList);
                         break;
                    }else {
                    	if(tagList!=null&&tagList.size()!=0)
                    	personnelTagMapper.insertList(tagList);
                    	 break;
					}
                   
                case 0: //合并标签数据
                default:
                    if(tagList!=null&&tagList.size()!=0)
                        personnelTagMapper.insertList(tagList);
                    break;
            }
            if(CollectionUtils.isNotEmpty(personnelList)){
                //		处理新增数据
                int updateCount = personnelMapper.insertList(personnelList);

                if (personnelList.size()!=updateCount) {
                    try {
                        throw new ServiceException("导入失败！");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            
            List<Personnel> selectnull=personnelMapper.selectnull();
            for (int i = 0; i < selectnull.size(); i++) {
				   if (StringUtils.isBlank(selectnull.get(i).getUserId())||StringUtils.isBlank(selectnull.get(i).getName())) {
					   personnelMapper.deleteByPrimaryKey(selectnull.get(i).getId());
				}
			}
            return Response.response();
        } catch (IOException e1) {
            e1.printStackTrace();
            throw new ServiceException("导入失败！请稍后重试！");
        }
    }

    private List<PersonnelTag> parseTagJson(String tagsList, AccessToken accessToken, String uid){
        JSONArray array = JSON.parseArray(tagsList);
        List<PersonnelTag> tags=new LinkedList<>();
        for (int i = 0; i < array.size(); i++) {       	
            PersonnelTag tag=new PersonnelTag();
            tag.setIdentity(array.getJSONObject(i).getString("identity"));
            tag.setGraduates(array.getJSONObject(i).getString("graduates"));
            tag.setCreatedBy(accessToken.getUserCode());
            tag.setCreatedDate(new Date());
            tag.setUserId(uid);
            tags.add(tag);
        }
        return tags;
    }

    @Override
    public Result queryadByUid(String search,AccessToken accessToken) {
    	
//    	List<String> userIds= personnelCommenService.findRole(accessToken);
//		if(userIds!=null) {
//			if(userIds.size()==0||userIds.get(0).equals("-1")) {
//				//没有匹配的角色或没有查找到数据
//				return Response.response();
//			}		
//		}
    	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;
    			 rolesMap.put("identitys", null);
    			 break;
    		}else if (key.equals("role")) {
    			 userquyu=null;
    			 rolesMap.put("identitys", null);
    			 break;
			}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 i = 0; i < resuaslt.size(); i++) {
					userquyu.add(resuaslt.get(i).getOrganName());
				}
			}
    		
    	}
        List<PersonInfoVO> personInfoCodeOrId=personnelTagMapper.selectByPersonInfoByCodeOrName(search,rolesMap,userquyu);
        List<String> result=new LinkedList<>();
        for (PersonInfoVO psndoc : personInfoCodeOrId) {       	
            result.add(psndoc.getCode()+" - "+psndoc.getWorkdept()+" - "+psndoc.getName());
        }

        return Response.response(result);
    }


    public Result personneltag(String userId, String identity) {

        List<PersonnelTgDTO> perseltag=personnelTagMapper.personneltag(userId,identity);
        return Response.response(perseltag);
    }

    @Override
    public Result tagid(Integer id) {
        List<PersonnelpascTagidDTO> tagid=personnelTagMapper.tagid(id);
        if (tagid.get(0)!=null) {
            if (tagid.get(0).getPatagid()!=null||tagid.get(0).getPctagid()!=null||tagid.get(0).getPstagid()!=null||tagid.get(0).getStagid()!=null) {
                return Response.responseFail("此标签和其他功能关联，不可删除");
            } else {
                return Response.response(tagid);
            }
        }else {
            return Response.response(tagid);
        }

    }

	@Override
	public Result personneltaguserid(String userId) {
		personnelTagDTO dto = personnelTagMapper.personneltaguserid(userId);
		
		if (dto!=null) {
			 Condition condition=new Condition(PersonnelTag.class);
		        condition.excludeProperties("userId");
		        condition.createCriteria().andEqualTo("userId",dto.getUserId());
		        dto.setTagsList(personnelTagMapper.selectByCondition(condition));
		        return Response.response(dto);
		}else {
			return Response.response();
		}
        
	}

	@Override
	public Result delpiliang(String userid) {
		
		
		List<String> uertid = JSONArray.parseArray(userid, String.class);
//		String[] idIntegers;
//		String[] idArry = null;
//		if (userid!=null&&!"".equals(userid)) {
//			idIntegers=userid.split(",");
//		    idArry = new String[idIntegers.length];
//		    for (int i = 0; i < idIntegers.length; i++) {
//		    	idArry[i]=idIntegers[i];
//			}
//
//		}
//		
		for (int i = 0; i < uertid.size(); i++) {
			List<PersonnelpascTagidDTO> selectdeleperid=personnelTagMapper.selectdeleperid(uertid.get(i));
	    	if (selectdeleperid.size()!=0&&selectdeleperid.get(0)!=null) {
	            if (selectdeleperid.get(0).getPapersonnelid()!=null||selectdeleperid.get(0).getPcpersonnelid()!=null||selectdeleperid.get(0).getPspersonnelid()!=null||selectdeleperid.get(0).getSpersonnelid()!=null) {
	                //return Response.responseFail("此标签和其他功能关联，不可删除");
	              throw new ServiceException("用户编号:"+uertid.get(i)+",下的标签和其他功能关联，不可删除");
	         }
		  }
		
		}
		
		personnelTagMapper.delpingliang(uertid);
		
		personnelTagMapper.delpingliangtag(uertid);
		
		return Response.response("删除成功");
	}
	

}