/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workstaff.service;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.entity.WorkStaffEducation;
import com.jeeplus.modules.workstaffachiveslog.entity.WorkStaffAchivesLog;
import com.jeeplus.modules.workstaffachiveslog.service.WorkStaffAchivesLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workstaff.entity.WorkStaffTraining;
import com.jeeplus.modules.workstaff.dao.WorkStaffTrainingDao;
import org.springframework.web.multipart.MultipartFile;

/**
 * 培训经历Service
 * @author ssrh
 * @version 2018-07-27
 */
@Service
@Transactional(readOnly = true)
public class WorkStaffTrainingService extends CrudService<WorkStaffTrainingDao, WorkStaffTraining> {
    @Autowired
    private WorkStaffAchivesLogService workStaffAchivesLogService;
    @Autowired
    private UserDao userDao;
	public WorkStaffTraining get(String id) {
		return super.get(id);
	}
	
	public List<WorkStaffTraining> findList(WorkStaffTraining workStaffTraining) {
		return super.findList(workStaffTraining);
	}
	
	public Page<WorkStaffTraining> findPage(Page<WorkStaffTraining> page, WorkStaffTraining workStaffTraining) {
		return super.findPage(page, workStaffTraining);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkStaffTraining workStaffTraining) {
		super.save(workStaffTraining);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkStaffTraining workStaffTraining) {
		super.delete(workStaffTraining);
	}


    public boolean save(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return false;
        }
        List<WorkStaffTraining> list = workStaffBasicInfo.getTrainingList();
        if(list==null||list.size()<=0){
            return false;
        }
        boolean flag=false;
        for (WorkStaffTraining entity : list) {
            if(entity!=null&&"1".equals(entity.getDelFlag())&&StringUtils.isBlank(entity.getId())){
                continue;
            }
            if(entity!=null&&"1".equals(entity.getDelFlag())){
                dao.deleteByLogic(entity);
                continue;
            }
            if (entity!=null){
                if(entity.getFile()!=null&&!entity.getFile().isEmpty()&&entity.getFile().getSize()>0){
                    MultipartFile file = entity.getFile();
                    entity.setFileName(file.getOriginalFilename());
                    entity.setFilePath(this.uploadFile(file,entity.getFilePath()));
                }
                entity.setStaff(workStaffBasicInfo.getId());
                this.save(entity);
                if(first){
                    entity.setId(null);
                    entity.setFilePath("");
                }
                flag = true;
            }
        }
        return flag;
    }

    public String uploadFile(MultipartFile file, String filePath){
        String date = DateUtils.formatDate(new Date(),"yyMMddHHmm");
        try {
            if (file != null && file.getSize() > 0) {
                String path = new StringBuilder("/employeeInfo/").append(date)
                        .append(file.getOriginalFilename()).toString();
                InputStream inputStream = file.getInputStream();
                BOSClientUtil bosClientUtil = new BOSClientUtil();
                String url = bosClientUtil.upload(path, inputStream);
                return url;
            }
        }catch (Exception e){
            logger.error("上传文件失败！");
        }
        return null;
    }

    public void query(WorkStaffBasicInfo workStaffBasicInfo) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return;
        }
        WorkStaffTraining entity = new WorkStaffTraining();
        entity.setStaff(workStaffBasicInfo.getId());
        workStaffBasicInfo.setTrainingList(this.findList(entity));
    }

    private static Map<String,String> EDU_MAP = Maps.newHashMap();//教育经历

    static{//教育经历
        EDU_MAP.put("name", "培训名称");
        EDU_MAP.put("agency", "培训机构");
        EDU_MAP.put("address", "培训地点");
        EDU_MAP.put("startDate", "培训起始日期");
        EDU_MAP.put("endDate", "培训终止日期");
        EDU_MAP.put("type", "培训类型");
        EDU_MAP.put("hours", "学时");
        EDU_MAP.put("certificate", "所获证书");
        EDU_MAP.put("filePath", "文件");
        EDU_MAP.put("fileName", "文件名");
        EDU_MAP.put("remarks", "备注");
    }
    public boolean saveApply(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return false;
        }
        List<WorkStaffTraining> list = workStaffBasicInfo.getTrainingList();
        if(list==null||list.size()<=0){
            return false;
        }
        boolean flag = false;
        User u=userDao.get(workStaffBasicInfo.getUserId());
        for (WorkStaffTraining entity : list) {
            entity.setStaff(workStaffBasicInfo.getId());
            WorkStaffTraining workStaffTraining=dao.get(entity.getId());
            if(workStaffTraining==null){
                entity.setCreateBy(u);
                entity.setCreateDate(new Date());
                entity.setUpdateBy(u);
                entity.setUpdateDate(new Date());
                dao.insert(entity);
            }else{
                this.save(entity);
            }
            if(entity!=null&&"1".equals(entity.getDelFlag())){
                dao.deleteByLogic(entity);
                continue;
            }
            flag =true;
        }
        dao.updateFalt(workStaffBasicInfo.getId());
        return flag;
    }

    public void querys(WorkStaffBasicInfo workStaffBasicInfo) {
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return;
        }
        WorkStaffTraining entity = new WorkStaffTraining();
        entity.setStaff(workStaffBasicInfo.getId());
        List<WorkStaffTraining> list=this.findList(entity);
        List<WorkStaffTraining> newList=Lists.newArrayList();
        if(list!=null&&list.size()>0){//修改
            for(WorkStaffTraining workStaffTraining:list){
                Class<? extends WorkStaffTraining> newClass = workStaffTraining.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    String name = field.getName();
                    if("name".equals(name)||"agency".equals(name)||"address".equals(name)||"startDate".equals(name)||"endDate".equals(name)
                            || "type".equals(name)||"hours".equals(name)||"certificate".equals(name)||"filePath".equals(name)
                            ||"fileName".equals(name)||"remarks".equals(name)){
                        String setMethod = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
                        String getMethod = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                        WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                        workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                        workStaffAchivesLog.setModule("培训经历");
                        workStaffAchivesLog.setSonId(workStaffTraining.getId());
                        workStaffAchivesLog.setFields(name);
                        workStaffAchivesLog.setType("修改");
                        workStaffAchivesLog.setState("1");
                        List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
                        try {
                            Object newInvoke = newClass.getMethod(getMethod).invoke(workStaffTraining);//修改后
                            if(newInvoke instanceof String){
                                Method setReadOnly = workStaffTraining.getClass().getMethod(setMethod, String.class);
                                if(logs!=null&&logs.size()>0){
                                    setReadOnly.invoke(workStaffTraining,logs.get(0).getNewKey());
                                }
                            }
                            if(newInvoke instanceof Date){//日期
                                Method setReadOnly = workStaffTraining.getClass().getMethod(setMethod, Date.class);
                                if(logs!=null&&logs.size()>0){
                                    Date myDate = dateFormat1.parse(logs.get(0).getNewKey());
                                    setReadOnly.invoke(workStaffTraining,myDate);
                                }
                            }
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                newList.add(workStaffTraining);
            }
        }
        //新增
        WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
        workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
        workStaffAchivesLog.setModule("培训经历");
        workStaffAchivesLog.setType("新增");
        workStaffAchivesLog.setState("1");
        List<WorkStaffAchivesLog> sonIds=workStaffAchivesLogService.findSonId(workStaffAchivesLog);
        if(sonIds!=null&&sonIds.size()>0){
            for(WorkStaffAchivesLog w:sonIds){
                workStaffAchivesLog.setSonId(w.getSonId());
                WorkStaffTraining workStaffTraining = new WorkStaffTraining();
                workStaffTraining.setId(w.getSonId());
                workStaffTraining.setDelFlag("0");
                workStaffTraining.setStaff(workStaffBasicInfo.getId());
                Class<? extends WorkStaffTraining> newClass = workStaffTraining.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    String name = field.getName();
                    if("name".equals(name)||"agency".equals(name)||"address".equals(name)||"startDate".equals(name)||"endDate".equals(name)
                            || "type".equals(name)||"hours".equals(name)||"certificate".equals(name)||"filePath".equals(name)
                            ||"fileName".equals(name)||"remarks".equals(name)){
                        String setMethod = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
                        String getMethod = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                        workStaffAchivesLog.setFields(name);
                        List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
                        try {
                            if("startDate".equals(name)||"endDate".equals(name)){//日期
                                Method setReadOnly = workStaffTraining.getClass().getMethod(setMethod, Date.class);
                                if(logs!=null&&logs.size()>0){
                                    Date myDate = dateFormat1.parse(logs.get(0).getNewKey());
                                    setReadOnly.invoke(workStaffTraining,myDate);
                                }
                            }else{
                                Method setReadOnly = workStaffTraining.getClass().getMethod(setMethod, String.class);
                                if(logs!=null&&logs.size()>0){
                                    setReadOnly.invoke(workStaffTraining,logs.get(0).getNewKey());
                                }
                            }
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                newList.add(workStaffTraining);
            }
        }
        //删除
        WorkStaffAchivesLog delLog=new WorkStaffAchivesLog();
        delLog.setStaffId(workStaffBasicInfo.getId());
        delLog.setModule("培训经历");
        delLog.setType("删除");
        workStaffAchivesLog.setState("1");
        List<WorkStaffAchivesLog> dellogs=workStaffAchivesLogService.findList(delLog);
        if(dellogs!=null&&dellogs.size()>0){
            for(WorkStaffAchivesLog w:dellogs){
                newList.remove(dao.get(w.getSonId()));
            }
        }
        workStaffBasicInfo.setTrainingList(newList);
    }
    @Transactional(readOnly = false)
    public void saveEdu(WorkStaffBasicInfo workStaffBasicInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<WorkStaffTraining> trainingList =workStaffBasicInfo.getTrainingList();
        if(trainingList!=null&&trainingList.size()>0){
            for(WorkStaffTraining newTraining:trainingList){
                Class<? extends WorkStaffTraining> newClass = newTraining.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                if(newTraining.getId()!=null&&!"1".equals(newTraining.getDelFlag())&&!"".equals(newTraining.getId())){
                    if(newTraining.getFile()!=null&&!newTraining.getFile().isEmpty()&&newTraining.getFile().getSize()>0){
                        MultipartFile file = newTraining.getFile();
                        newTraining.setFilePath(this.uploadFile(file,newTraining.getFilePath()));
                    }
                    WorkStaffTraining oldTraining=this.get(newTraining.getId());
                    if(oldTraining!=null){
                        Class<? extends WorkStaffTraining> oldClass = oldTraining.getClass();
                        for (Field field : declaredFields) {
                            String name = field.getName();
                            if("name".equals(name)||"agency".equals(name)||"address".equals(name)||"startDate".equals(name)||"endDate".equals(name)
                                    || "type".equals(name)||"hours".equals(name)||"certificate".equals(name)||"filePath".equals(name)
                                    ||"fileName".equals(name)||"remarks".equals(name)){
                                String methodName = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                                WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                                workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                                workStaffAchivesLog.setModule("培训经历");
                                workStaffAchivesLog.setSonId(newTraining.getId());
                                workStaffAchivesLog.setFields(name);
                                workStaffAchivesLog.setState("1");
                                try {
                                    Object newInvoke = newClass.getMethod(methodName).invoke(newTraining);//修改后
                                    Object oldInvoke = oldClass.getMethod(methodName).invoke(oldTraining);//修改前
                                    String describes=EDU_MAP.get(name);
                                    if(newInvoke instanceof String){
                                        String newValue=newInvoke.toString();
                                        String oldValue=oldInvoke.toString();
                                        if(!newValue.equals(oldValue)){
                                            if("type".equals(name)){
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "培训经历",describes,name,
                                                        DictUtils.getMainDictLabel(oldValue,"training_type",""),
                                                        DictUtils.getMainDictLabel(newValue,"training_type",""),
                                                        oldValue,newValue,newTraining.getId(),"修改");
                                            }else{
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "培训经历",describes,name,
                                                        oldInvoke.toString(),newInvoke.toString(),
                                                        oldInvoke.toString(),newInvoke.toString(),newTraining.getId(),"修改");
                                            }
                                        }
                                    }
                                    if(newInvoke instanceof Date){//日期
                                        String newDate="";
                                        String oldDate="";
                                        if(newInvoke!=null){
                                            newDate=sdf.format(newInvoke);
                                        }
                                        if (oldInvoke!=null){
                                            oldDate=sdf.format(oldInvoke);
                                        }
                                        if(!newDate.equals(oldDate)){
                                            workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                    "培训经历",describes,name,
                                                    oldDate,newDate,oldDate,newDate,newTraining.getId(),"修改");
                                        }
                                    }
                                } catch (NoSuchMethodException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }
                }else if((newTraining.getId()==null||"".equals(newTraining.getId()))&&"0".equals(newTraining.getDelFlag())){//新增
                    if(newTraining.getFile()!=null&&!newTraining.getFile().isEmpty()&&newTraining.getFile().getSize()>0){
                        MultipartFile file = newTraining.getFile();
                        newTraining.setFilePath(this.uploadFile(file,newTraining.getFilePath()));
                    }
                    String newId=IdGen.uuid();
                    for (Field field : declaredFields) {
                        String name = field.getName();
                        if("name".equals(name)||"agency".equals(name)||"address".equals(name)||"startDate".equals(name)||"endDate".equals(name)
                                || "type".equals(name)||"hours".equals(name)||"certificate".equals(name)||"filePath".equals(name)
                                ||"fileName".equals(name)||"remarks".equals(name)){
                            String methodName = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                            WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                            workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                            workStaffAchivesLog.setModule("培训经历");
                            workStaffAchivesLog.setSonId(newId);
                            workStaffAchivesLog.setFields(name);
                            workStaffAchivesLog.setState("1");
                            try {
                                Object newInvoke = newClass.getMethod(methodName).invoke(newTraining);//修改后
                                String describes=EDU_MAP.get(name);
                                if(newInvoke instanceof String){
                                    String newValue=newInvoke.toString();
                                    if("type".equals(name)){
                                        workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                "培训经历",describes,name,
                                                "",
                                                DictUtils.getMainDictLabel(newValue,"training_type",""),
                                                "",newValue,newId,"新增");
                                    }else{
                                        workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                "培训经历",describes,name,
                                                "",newInvoke.toString(),
                                                "",newInvoke.toString(),newId,"新增");
                                    }
                                }
                                if(newInvoke instanceof Date){//日期
                                    String newDate=sdf.format(newInvoke);
                                    workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                            "培训经历",describes,name,
                                            "",newDate,"",newDate,newId,"新增");
                                };
                            } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }else if(newTraining.getId()!=null&&"1".equals(newTraining.getDelFlag())&&!"".equals(newTraining.getId())){//删除
                    WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                    workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                    workStaffAchivesLog.setModule("培训经历");
                    workStaffAchivesLog.setSonId(newTraining.getId());
                    workStaffAchivesLog.setType("删除");
                    workStaffAchivesLog.setState("1");
                    workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                            "培训经历","","",
                            "","",
                            "","",newTraining.getId(),"删除");
                }
            }
        }
    }
}