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

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.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.WorkStaffLanguages;
import com.jeeplus.modules.workstaff.dao.WorkStaffLanguagesDao;
import org.springframework.web.multipart.MultipartFile;

/**
 * 外语信息Service
 * @author ssrh
 * @version 2018-07-27
 */
@Service
@Transactional(readOnly = true)
public class WorkStaffLanguagesService extends CrudService<WorkStaffLanguagesDao, WorkStaffLanguages> {
    @Autowired
    private WorkStaffAchivesLogService workStaffAchivesLogService;
    @Autowired
    private UserDao userDao;
	public WorkStaffLanguages get(String id) {
		return super.get(id);
	}
	
	public List<WorkStaffLanguages> findList(WorkStaffLanguages workStaffLanguages) {
		return super.findList(workStaffLanguages);
	}
	
	public Page<WorkStaffLanguages> findPage(Page<WorkStaffLanguages> page, WorkStaffLanguages workStaffLanguages) {
		return super.findPage(page, workStaffLanguages);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkStaffLanguages workStaffLanguages) {
		super.save(workStaffLanguages);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkStaffLanguages workStaffLanguages) {
		super.delete(workStaffLanguages);
	}


    public boolean save(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return false;
        }
        List<WorkStaffLanguages> list = workStaffBasicInfo.getLanguageList();
        if(list==null||list.size()<=0){
            return false;
        }
        boolean flag=false;
        for (WorkStaffLanguages 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.setStaffId(workStaffBasicInfo.getId());
                this.save(entity);
                if(first){
                    entity.setId(null);
                    entity.setFilePath("");
                }
                flag = true;
            }
        }
        return flag;
    }

    public String uploadFile(MultipartFile file, String filePath) {
        if (file != null && !file.isEmpty() &&file.getSize()>0) {
            String key = "";
            if (StringUtils.isNotBlank(filePath)) {
                String aliyunUrl = Global.getAliyunUrl();
                String aliDownloadUrl = Global.getAliDownloadUrl();
                String cons = "";
                if (filePath.contains(aliyunUrl)) {
                    cons = aliyunUrl;
                } else if (filePath.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")) {
                    cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
                } else {
                    cons = aliDownloadUrl;
                }
                String[] arr = filePath.split(cons + "/");
                key = arr[1];
            }
            try {
                OSSClientUtil ossUtil1 = new OSSClientUtil();
                if (StringUtils.isNotBlank(key)) {
                    ossUtil1.deleteSingleObject(key);
                }
            }catch (Exception e){
                logger.error("oss删除文件失败！");
            }
            try {
                OSSClientUtil ossUtil = new OSSClientUtil();
                String path = Global.getStaffBasicFilePath()+ DateUtils.formatDate(new Date(), null)+"/";
                String newName = System.currentTimeMillis()+"-"+file.getOriginalFilename();
                ossUtil.uploadFile2OSS(file.getInputStream(),path,newName);
                return  Global.getAliDownloadUrl() + "/" + path + newName;
            } catch (Exception e) {
                logger.error("oss上传文件失败！");
            }
        }
        return filePath;
    }

    public void query(WorkStaffBasicInfo workStaffBasicInfo) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return;
        }
        WorkStaffLanguages entity = new WorkStaffLanguages();
        entity.setStaffId(workStaffBasicInfo.getId());
        workStaffBasicInfo.setLanguageList(this.findList(entity));
    }

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

    static{//教育经历
        EDU_MAP.put("language", "语种");
        EDU_MAP.put("proficiency", "熟练程度");
        EDU_MAP.put("certificate", "证书名称");
        EDU_MAP.put("certifDate", "获证日期");
        EDU_MAP.put("filePath", "文件");
        EDU_MAP.put("fileName", "文件名");
    }
    public boolean saveApply(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return false;
        }
        List<WorkStaffLanguages> list = workStaffBasicInfo.getLanguageList();
        if(list==null||list.size()<=0){
            return false;
        }
        boolean flag = false;
        User u=userDao.get(workStaffBasicInfo.getUserId());
        for (WorkStaffLanguages entity : list) {
            entity.setStaffId(workStaffBasicInfo.getId());
            WorkStaffLanguages workStaffLanguages=dao.get(entity.getId());
            if(workStaffLanguages==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;
        }
        WorkStaffLanguages entity = new WorkStaffLanguages();
        entity.setStaffId(workStaffBasicInfo.getId());
        List<WorkStaffLanguages> list=this.findList(entity);
        List<WorkStaffLanguages> newList=Lists.newArrayList();
        if(list!=null&&list.size()>0){//修改
            for(WorkStaffLanguages workStaffLanguages:list){
                Class<? extends WorkStaffLanguages> newClass = workStaffLanguages.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    String name = field.getName();
                    if("language".equals(name)||"proficiency".equals(name)||"certificate".equals(name)||"certifDate".equals(name)||"filePath".equals(name)
                            || "fileName".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(workStaffLanguages.getId());
                        workStaffAchivesLog.setFields(name);
                        workStaffAchivesLog.setType("修改");
                        workStaffAchivesLog.setState("1");
                        List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
                        try {
                            Object newInvoke = newClass.getMethod(getMethod).invoke(workStaffLanguages);//修改后
                            if(newInvoke instanceof String){
                                Method setReadOnly = workStaffLanguages.getClass().getMethod(setMethod, String.class);
                                if(logs!=null&&logs.size()>0){
                                    setReadOnly.invoke(workStaffLanguages,logs.get(0).getNewKey());
                                }
                            }
                            if(newInvoke instanceof Date){//日期
                                Method setReadOnly = workStaffLanguages.getClass().getMethod(setMethod, Date.class);
                                if(logs!=null&&logs.size()>0){
                                    Date myDate = dateFormat1.parse(logs.get(0).getNewKey());
                                    setReadOnly.invoke(workStaffLanguages,myDate);
                                }
                            }
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                newList.add(workStaffLanguages);
            }
        }
        //新增
        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());
                WorkStaffLanguages workStaffLanguages = new WorkStaffLanguages();
                workStaffLanguages.setId(w.getSonId());
                workStaffLanguages.setDelFlag("0");
                workStaffLanguages.setStaffId(workStaffBasicInfo.getId());
                Class<? extends WorkStaffLanguages> newClass = workStaffLanguages.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    String name = field.getName();
                    if("language".equals(name)||"proficiency".equals(name)||"certificate".equals(name)||"certifDate".equals(name)||"filePath".equals(name)
                            || "fileName".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("certifDate".equals(name)){//日期
                                Method setReadOnly = workStaffLanguages.getClass().getMethod(setMethod, Date.class);
                                if(logs!=null&&logs.size()>0){
                                    Date myDate = dateFormat1.parse(logs.get(0).getNewKey());
                                    setReadOnly.invoke(workStaffLanguages,myDate);
                                }
                            }else{
                                Method setReadOnly = workStaffLanguages.getClass().getMethod(setMethod, String.class);
                                if(logs!=null&&logs.size()>0){
                                    setReadOnly.invoke(workStaffLanguages,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(workStaffLanguages);
            }
        }
        //删除
        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.setLanguageList(newList);
    }
    @Transactional(readOnly = false)
    public void saveEdu(WorkStaffBasicInfo workStaffBasicInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<WorkStaffLanguages> languagesList =workStaffBasicInfo.getLanguageList();
        if(languagesList!=null&&languagesList.size()>0){
            for(WorkStaffLanguages newLanguages:languagesList){
                Class<? extends WorkStaffLanguages> newClass = newLanguages.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                if(newLanguages.getId()!=null&&!"1".equals(newLanguages.getDelFlag())&&!"".equals(newLanguages.getId())){
                    if(newLanguages.getFile()!=null&&!newLanguages.getFile().isEmpty()&&newLanguages.getFile().getSize()>0){
                        MultipartFile file = newLanguages.getFile();
                        newLanguages.setFilePath(this.uploadFile(file,newLanguages.getFilePath()));
                    }
                    WorkStaffLanguages oldLanguages=this.get(newLanguages.getId());
                    if(oldLanguages!=null){
                        Class<? extends WorkStaffLanguages> oldClass = oldLanguages.getClass();
                        for (Field field : declaredFields) {
                            String name = field.getName();
                            if("language".equals(name)||"proficiency".equals(name)||"certificate".equals(name)||"certifDate".equals(name)||"filePath".equals(name)
                                    || "fileName".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(newLanguages.getId());
                                workStaffAchivesLog.setFields(name);
                                workStaffAchivesLog.setState("1");
                                try {
                                    Object newInvoke = newClass.getMethod(methodName).invoke(newLanguages);//修改后
                                    Object oldInvoke = oldClass.getMethod(methodName).invoke(oldLanguages);//修改前
                                    String describes=EDU_MAP.get(name);
                                    if(newInvoke instanceof String){
                                        String newValue=newInvoke.toString();
                                        String oldValue=oldInvoke.toString();
                                        if(!newValue.equals(oldValue)){
                                            if("language".equals(name)){
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "外语语种",describes,name,
                                                        DictUtils.getMainDictLabel(oldValue,"language",""),
                                                        DictUtils.getMainDictLabel(newValue,"language",""),
                                                        oldValue,newValue,newLanguages.getId(),"修改");
                                            }else if("proficiency".equals(name)){
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "外语语种",describes,name,
                                                        DictUtils.getDictLabel(oldValue,"proficiency",""),
                                                        DictUtils.getDictLabel(newValue,"proficiency",""),
                                                        oldValue,newValue,newLanguages.getId(),"修改");
                                            }else{
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "外语语种",describes,name,
                                                        oldInvoke.toString(),newInvoke.toString(),
                                                        oldInvoke.toString(),newInvoke.toString(),newLanguages.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,newLanguages.getId(),"修改");
                                        }
                                    }
                                } catch (NoSuchMethodException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }
                }else if((newLanguages.getId()==null||"".equals(newLanguages.getId()))&&"0".equals(newLanguages.getDelFlag())){//新增
                    if(newLanguages.getFile()!=null&&!newLanguages.getFile().isEmpty()&&newLanguages.getFile().getSize()>0){
                        MultipartFile file = newLanguages.getFile();
                        newLanguages.setFilePath(this.uploadFile(file,newLanguages.getFilePath()));
                    }
                    String newId=IdGen.uuid();
                    for (Field field : declaredFields) {
                        String name = field.getName();
                        if("language".equals(name)||"proficiency".equals(name)||"certificate".equals(name)||"certifDate".equals(name)||"filePath".equals(name)
                                || "fileName".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(newLanguages);//修改后
                                String describes=EDU_MAP.get(name);
                                if(newInvoke instanceof String){
                                    String newValue=newInvoke.toString();
                                    if("language".equals(name)){
                                        workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                "外语语种",describes,name,
                                                "",
                                                DictUtils.getMainDictLabel(newValue,"language",""),
                                                "",newValue,newId,"新增");
                                    }else if("proficiency".equals(name)){
                                        workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                "外语语种",describes,name,
                                                "",
                                                DictUtils.getDictLabel(newValue,"proficiency",""),
                                                "",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(newLanguages.getId()!=null&&"1".equals(newLanguages.getDelFlag())&&!"".equals(newLanguages.getId())){//删除
                    WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                    workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                    workStaffAchivesLog.setModule("外语语种");
                    workStaffAchivesLog.setSonId(newLanguages.getId());
                    workStaffAchivesLog.setType("删除");
                    workStaffAchivesLog.setState("1");
                    workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                            "外语语种","","",
                            "","",
                            "","",newLanguages.getId(),"删除");
                }
            }
        }
    }
}