package com.goafanti.personnel.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.PersonnelChooseMapper;
import com.goafanti.common.dao.PersonnelContactMapper;
import com.goafanti.common.dao.PersonnelContractMapper;
import com.goafanti.common.dao.PersonnelDossierMapper;
import com.goafanti.common.dao.PersonnelEntryMapper;
import com.goafanti.common.dao.PersonnelLevelMapper;
import com.goafanti.common.dao.PersonnelMidMapper;
import com.goafanti.common.dao.PersonnelPromotionMapper;
import com.goafanti.common.dao.PersonnelQuitMapper;
import com.goafanti.common.dao.PersonnelWelfareMapper;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.PersonnelContact;
import com.goafanti.common.model.PersonnelDossier;
import com.goafanti.common.model.PersonnelEntry;
import com.goafanti.common.model.PersonnelMid;
import com.goafanti.common.model.PersonnelWelfare;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.personnel.bo.InputPersonnelBo;
import com.goafanti.personnel.bo.InputPersonnelChooseBo;
import com.goafanti.personnel.bo.InputPersonnelContactBo;
import com.goafanti.personnel.bo.InputPersonnelContractBo;
import com.goafanti.personnel.bo.InputPersonnelEntryBo;
import com.goafanti.personnel.bo.InputPersonnelListBo;
import com.goafanti.personnel.bo.InputPersonnelLvlBo;
import com.goafanti.personnel.bo.InputPersonnelPromotionBo;
import com.goafanti.personnel.bo.InputPersonnelQuitBo;
import com.goafanti.personnel.bo.IntpersonnelWelfareBo;
import com.goafanti.personnel.bo.OutPersonnelBo;
import com.goafanti.personnel.bo.OutPersonnelListBo;
import com.goafanti.personnel.bo.OutPersonnelLvlBo;
import com.goafanti.personnel.service.PersonnelService;

@Service
public class PersonnelServiceImpl  extends BaseMybatisDao<PersonnelDossierMapper> implements PersonnelService {
	@Autowired
	private PersonnelDossierMapper	personnelDossierMapper;
	@Autowired
	private PersonnelContactMapper	personnelContactMapper;
	@Autowired
	private PersonnelEntryMapper	personnelEntryMapper;
	@Autowired
	private PersonnelPromotionMapper	personnelPromotionMapper;
	@Autowired
	private PersonnelContractMapper	personnelContractMapper;
	@Autowired
	private PersonnelChooseMapper	personnelChooseMapper;
	@Autowired
	private PersonnelQuitMapper	personnelQuitMapper;
	@Autowired
	private PersonnelLevelMapper	personnelLevelMapper;
	@Autowired
	private PersonnelWelfareMapper	personnelWelfareMapper;
	@Autowired
	private PersonnelMidMapper	personnelMidMapper;
	@Autowired
	private AdminMapper	adminMapper;
	
	@Override
	public int addPersonnel(InputPersonnelBo i) {
		if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)) {
			Admin a=adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
			if (a!=null) {
				i.setCompany(a.getDepartmentId());
			}
		}
		return personnelDossierMapper.insertSelective(i);
	}

	@Override
	public int updatePersonnel(InputPersonnelBo i) {
		return personnelDossierMapper.updateByPrimaryKeySelective(i);
	}

	@Override
	public int updateContact(InputPersonnelContactBo i) {
		PersonnelDossier p=new PersonnelDossier();
		p.setId(i.getId());
		p.setMobile(i.getMobile());
		p.setFixedTel(i.getFixedTel());
		personnelDossierMapper.updateByPrimaryKeySelective(p);
		JSONArray ja = (JSONArray) JSON.parse(i.getContactList());
		List<PersonnelContact> list = new ArrayList<PersonnelContact>();
		if (ja != null && !ja.isEmpty()) {
			PersonnelContact pc = null;
			for (int idx = 0; idx < ja.size(); idx++) {
				pc = ja.getJSONObject(idx).toJavaObject(PersonnelContact.class);
				list.add(pc);
			}
		}
		for (PersonnelContact pc : list) {
			if (pc.getId()!=null) {
				personnelContactMapper.updateByPrimaryKeySelective(pc);
			}else {
				personnelContactMapper.insertSelective(pc);
			}
			
		}
		PersonnelContact pc =list.get(0);
		PersonnelMid m=new PersonnelMid();
		m.setId(i.getId());
		m.setEmergencyContact(pc.getEmergencyContact());
		m.setEmergencyMobile(pc.getEmergencyMobile());
		PersonnelMid pm=personnelMidMapper.selectByPrimaryKey(i.getId());
		if (pm==null||pm.getId()==null) {
			personnelMidMapper.insertSelective(m);
		}else {
			personnelMidMapper.updateByPrimaryKeySelective(m);
			
		}
		
		return 1;
	}

	@Override
	public int updateEntry(InputPersonnelEntryBo i) {
		PersonnelEntry p=personnelEntryMapper.selectByPrimaryKey(i.getId());
		if (p==null||p.getId()==null) {
			personnelEntryMapper.insertSelective(i);
		}else {
			personnelEntryMapper.updateByPrimaryKeySelective(i);
		}
		return 1;
	}

	@Override
	public int updatePromotion(InputPersonnelPromotionBo i) {
		if (i.getId()==null) {
			personnelPromotionMapper.insertSelective(i);
		}else {
			personnelPromotionMapper.updateByPrimaryKeySelective(i);
		}
		PersonnelMid p=new PersonnelMid();
		p.setId(i.getPdId());
		p.setPromotionRemarks(i.getPromotionRemarks());
		p.setPromotionTime(i.getPromotionTime());
		PersonnelMid pm=personnelMidMapper.selectByPrimaryKey(i.getPdId());
		if (pm==null||pm.getId()==null) {
			personnelMidMapper.insertSelective(p);
		}else {
			personnelMidMapper.updateByPrimaryKeySelective(p);
			
		}
		return 1;
	}

	@Override
	public int checkDoorId(Integer doorId,Integer id) {
		int i=personnelDossierMapper.checkDoorId(doorId,id);
		return i;
	}
	@Override
	public int checkEmployeeId(Integer employeeId,Integer id) {
		int i=personnelDossierMapper.checkEmployeeId(employeeId,id);
		return i;
	}

	@Override
	public int updateContract(InputPersonnelContractBo i) {
		if (i.getId()==null) {
			personnelContractMapper.insertSelective(i);
		} else {
			personnelContractMapper.updateByPrimaryKeySelective(i);
		}
		PersonnelMid p=new PersonnelMid();
		p.setId(i.getPdId());
		p.setContractStartTime(i.getStartTime());
		p.setContractEndTime(i.getEndTime());
		PersonnelMid pm=personnelMidMapper.selectByPrimaryKey(i.getPdId());
		if (pm==null||pm.getId()==null) {
			personnelMidMapper.insertSelective(p);
		}else {
			personnelMidMapper.updateByPrimaryKeySelective(p);
			
		}
		return 1;
	}

	@Override
	public int updateChoose(InputPersonnelChooseBo i) {
		if (i.getId()==null) {
			personnelChooseMapper.insertSelective(i);
		} else {
			personnelChooseMapper.updateByPrimaryKeySelective(i);
		}
		return 1;
	}

	@Override
	public int updateQuit(InputPersonnelQuitBo i) {
		if (i.getId()==null) {
			personnelQuitMapper.insertSelective(i);
		} else {
			personnelQuitMapper.updateByPrimaryKeySelective(i);
		}
		PersonnelMid p=new PersonnelMid();
		p.setId(i.getPdId());
		p.setQuitTime(i.getEffectTime());
		PersonnelMid pm=personnelMidMapper.selectByPrimaryKey(i.getPdId());
		if (pm==null||pm.getId()==null) {
			personnelMidMapper.insertSelective(p);
		}else {
			personnelMidMapper.updateByPrimaryKeySelective(p);
			
		}
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutPersonnelListBo> selectList(InputPersonnelListBo i) {
		Map<String, Object> params = new HashMap<>();
		if (i.getPageNo()==null||i.getPageNo()<1)i.setPageNo(1);
		if (i.getPageSize()==null||i.getPageSize()<1) i.setPageSize(10);
		params.put("i", i);
		if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)) {
			params.put("aid", TokenManager.getAdminId());	
		}
		Pagination<OutPersonnelListBo>p=(Pagination<OutPersonnelListBo>) findPage("selectPersonnelByList", "selectPersonnelByCount",
				params, i.getPageNo(), i.getPageSize());
		return p;
	}

	@Override
	public OutPersonnelBo selectBypdId(Integer id) {
		OutPersonnelBo op=	personnelDossierMapper.selectBypdId(id);
		op.setContactList(personnelContactMapper.selectBypdId(id));
		PersonnelEntry pe=personnelEntryMapper.selectByPrimaryKey(id);
		op.setPersonnelEntry(pe);
		op.setPromotionList(personnelPromotionMapper.selectBypdId(id));
		op.setContractList(personnelContractMapper.selectBypdId(id));
		op.setChooseList(personnelChooseMapper.selectBypdId(id));
		op.setQuitList(personnelQuitMapper.selectBypdId(id));
		op.setWelfareList(personnelWelfareMapper.selectBypdId(id));
		return op;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void exportPersonnelList(HttpServletResponse response, InputPersonnelListBo in) throws IOException {
		OutputStream out = response.getOutputStream();
		try {
			List<OutPersonnelListBo>list=(List<OutPersonnelListBo>) selectList(in).getList();
			
    		String[] comment = {"员工编号","门禁编号","姓名","员工状态","所属系统","所属公司","职位名称","等级名称","星级","入职时间","转正时间","出生日期","性别"
    				,"婚否","子女","政治面貌","学历","毕业学校","所学专业","职称/证书","晋升明细","最近晋升时间","合同","联系电话","办公室电话",
    				"身份证号码","身份证发证地","户籍所在地","现住址","紧急联系人","紧急联系人电话","离职时间","工作年限","年龄","出生月份","参保时间","停保时间",
    				"入公积金时间","停公积金时间"};
    		String fileName ="人事档案表" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
    		//type 0 变更
    		XSSFWorkbook wb =ExportExcelUtil.exportTemplateInfoS(comment,"人事档案表");
    		//根据列表编写文档
    		XSSFSheet sheet =wb.getSheetAt(0);
    		for (OutPersonnelListBo ob : (List<OutPersonnelListBo>)list) {
    			//新增一行
    			XSSFRow r = sheet.createRow(sheet.getLastRowNum()+1);
    			
    			for (int i = 0; i < comment.length; i++) {
    				//当前列的只
    				String o = "";
    				switch (comment[i]) {
//    				"员工编号","门禁编号","姓名","员工状态","所属系统","所属公司","职位名称","等级名称","星级","入职时间","转正时间","出生日期","性别"
    				case "员工编号": o = ob.getEmployeeId()==null?"":ob.getEmployeeId().toString(); break;
    				case "门禁编号": o = ob.getDoorId().toString(); break;
    				case "姓名": o = ob.getName(); break;
    				case "员工状态": o = ob.getStatusName(); break;
    				case "所属系统": o = ob.getSystemName(); break;
    				case "所属公司": o = ob.getDepName(); break;
    				case "职位名称": o = ob.getJobsName(); break;
    				case "等级名称": o = ob.getStarName(); break;
    				case "星级": o = ob.getLvlName(); break;
    				case "入职时间": o = ob.getEntryTimes(); break;
    				case "转正时间": o = ob.getPromotionTimes()==null?"":ob.getPromotionTimes(); break;
    				case "出生日期": o = ob.getBirthdays(); break;
    				case "性别": o = ob.getSex()==0?"男":"女"; break;
    				case "婚否": o = ob.getMarriageName(); break;
    				case "子女": o = ob.getSon().toString()+"/"+ob.getGirl().toString(); break;
    				case "政治面貌": o = ob.getPoliticalOutlookName(); break;
    				case "学历": o = ob.getEducationName(); break;
    				case "毕业学校": o = ob.getSchool(); break;
    				case "所学专业": o = ob.getMajor(); break;
    				case "职称/证书": o = ob.getTitle(); break;
    				case "晋升明细": o = ob.getPromotionRemarks(); break;
    				case "最近晋升时间": o = ob.getPromotionTimes(); break;
    				case "合同": if (ob.getContractStart()!=null&&ob.getContractEnd()!=null) {
    					o = ob.getContractStart()+" ~ "+ob.getContractEnd();
    				}
    				break;
    				case "联系电话": o = ob.getMobile(); break;
    				case "办公室电话": o = ob.getFixedTel(); break;
    				case "身份证号码": o = ob.getIdCard(); break;
    				case "身份证发证地": o = ob.getCertificationAuthority(); break;
    				case "户籍所在地": o = ob.getResidenceName(); break;
    				case "现住址": o = ob.getNowName(); break;
    				case "紧急联系人": o = ob.getEmergencyContact(); break;
    				case "紧急联系人电话": o = ob.getEmergencyMobile(); break;
    				case "离职时间": o = ob.getQuitTime(); break;
    				case "工作年限": o = ob.getWorkingYear()==null?"":ob.getWorkingYear().toString(); break;
    				case "年龄": o = ob.getAge()==null?"":ob.getAge().toString(); break;
    				case "出生月份": o = ob.getMonth()==null?"":ob.getMonth().toString(); break;
    				case "参保时间": o = ob.getInsuranceStartTimes(); break;
    				case "停保时间": o = ob.getInsuranceEndTimes(); break;
    				case "入公积金时间": o = ob.getFundStartTimes(); break;
    				case "停公积金时间": o = ob.getFundEndTimes(); break;
    				default: o = ""; break;
    				}
    				XSSFCell c = r.createCell(i);
    				c.setCellValue(o);
    			}
    		}
    		//返回名称及参数
			 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
			 response.setContentType("application/octet-stream;charset=utf-8");
    		 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
			throw new BusinessException(new Error("表格生成错误。"));
		}finally {
			out.flush(); 
			 out.close(); 
		}
	}
	
	

	@Override
	public List<OutPersonnelLvlBo> selectLvlList() {
		return personnelLevelMapper.selectAll();
	}

	@Override
	public int updateLvl(InputPersonnelLvlBo i) {
		if (i.getId()==null) {
			personnelLevelMapper.insertSelective(i);
		}else {
			personnelLevelMapper.updateByPrimaryKeySelective(i);
		}
		return 1;
	}

	@Override
	public int updateWelfare(IntpersonnelWelfareBo i) {
		PersonnelWelfare p=personnelWelfareMapper.selectByPrimaryKey(i.getId());
		if (p==null||p.getId()==null) {
			if (i.getType()!=null) {
				personnelWelfareMapper.insertSelective(i);
			}
		}else {
			personnelWelfareMapper.updateByPrimaryKey(i);
		}
		PersonnelMid m=new PersonnelMid();
		m.setId(i.getPdId());
		m.setWelfareAnnexUrl(i.getAnnexUrl());
		m.setWelfareAnnexName(i.getAnnexName());
		m.setWelfareRemarks(i.getRemarks());
		PersonnelMid pm=personnelMidMapper.selectByPrimaryKey(i.getPdId());
		if (i.getType()!=null) {
			if (i.getType()==0) {
				m.setInsuranceStartTime(i.getStartTime());
				m.setInsuranceEndTime(i.getEndTime());
			}else if (i.getType()==1) {
				m.setFundStartTime(i.getStartTime());
				m.setFundEndTime(i.getEndTime());
			}else if (i.getType()==2) {
				m.setEmployerStartTime(i.getStartTime());
				m.setEmployerEndTime(i.getEndTime());
			}
		}
		if (pm==null||pm.getId()==null) {
			personnelMidMapper.insertSelective(m);
		}else {
			personnelMidMapper.updateByidTime(m,i.getType());
			
		}
		return 1;
	}


}
