/**
 * 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.WorkStaffCertificate;
import com.jeeplus.modules.workstaff.dao.WorkStaffCertificateDao;
import org.springframework.web.multipart.MultipartFile;

/**
 * 执业资格证书Service
 * @author ssrh
 * @version 2018-07-27
 */
@Service
@Transactional(readOnly = true)
public class WorkStaffCertificateService extends CrudService<WorkStaffCertificateDao, WorkStaffCertificate> {
    @Autowired
    private WorkStaffAchivesLogService workStaffAchivesLogService;
    @Autowired
    private UserDao userDao;
	public WorkStaffCertificate get(String id) {
		return super.get(id);
	}
	
	public List<WorkStaffCertificate> findList(WorkStaffCertificate workStaffCertificate) {
		return super.findList(workStaffCertificate);
	}
	
	public Page<WorkStaffCertificate> findPage(Page<WorkStaffCertificate> page, WorkStaffCertificate workStaffCertificate) {
		return super.findPage(page, workStaffCertificate);
	}
	
	@Transactional(readOnly = false)
	public void save(WorkStaffCertificate workStaffCertificate) {
		super.save(workStaffCertificate);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkStaffCertificate workStaffCertificate) {
		super.delete(workStaffCertificate);
	}


    public boolean save(WorkStaffBasicInfo workStaffBasicInfo,boolean first) {
        if(workStaffBasicInfo==null|| StringUtils.isBlank(workStaffBasicInfo.getId())){
            return false;
        }
        if(workStaffBasicInfo.getCertificateList()==null||workStaffBasicInfo.getCertificateList().size()<=0){
            return false;
        }
        boolean flag=false;
        for (WorkStaffCertificate entity : workStaffBasicInfo.getCertificateList()) {
            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 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;
        }
        WorkStaffCertificate entity = new WorkStaffCertificate();
        entity.setStaffId(workStaffBasicInfo.getId());
        workStaffBasicInfo.setCertificateList(this.findList(entity));
    }
    private static Map<String,String> EDU_MAP = Maps.newHashMap();//教育经历

    static{//教育经历
        EDU_MAP.put("name", "证书名称");
        EDU_MAP.put("num", "证书编号");
        EDU_MAP.put("issuingAuthority", "发证机关");
        EDU_MAP.put("issuingDate", "发证日期");
        EDU_MAP.put("registDate", "注册日期");
        EDU_MAP.put("registNum", "注册证书编号");
        EDU_MAP.put("major", "专业");
        EDU_MAP.put("grade", "等级");
        EDU_MAP.put("issType", "取得方式");
        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<WorkStaffCertificate> list = workStaffBasicInfo.getCertificateList();
        if(list==null||list.size()<=0){
            return false;
        }
        boolean flag = false;
        User u=userDao.get(workStaffBasicInfo.getUserId());
        for (WorkStaffCertificate entity : list) {
            entity.setStaffId(workStaffBasicInfo.getId());
            WorkStaffCertificate workStaffCertificate=dao.get(entity.getId());
            if(workStaffCertificate==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;
        }
        WorkStaffCertificate entity = new WorkStaffCertificate();
        entity.setStaffId(workStaffBasicInfo.getId());
        List<WorkStaffCertificate> list=this.findList(entity);
        List<WorkStaffCertificate> newList=Lists.newArrayList();
        if(list!=null&&list.size()>0){//修改
            for(WorkStaffCertificate workStaffCertificate:list){
                Class<? extends WorkStaffCertificate> newClass = workStaffCertificate.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    String name = field.getName();
                    if("name".equals(name)||"num".equals(name)||"issuingAuthority".equals(name)||"issuingDate".equals(name)||"registDate".equals(name)
                            || "registNum".equals(name)||"major".equals(name)||"grade".equals(name)
                            ||"issType".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(workStaffCertificate.getId());
                        workStaffAchivesLog.setFields(name);
                        workStaffAchivesLog.setType("修改");
                        workStaffAchivesLog.setState("1");
                        List<WorkStaffAchivesLog> logs=workStaffAchivesLogService.findList(workStaffAchivesLog);
                        try {
                            Object newInvoke = newClass.getMethod(getMethod).invoke(workStaffCertificate);//修改后
                            if(newInvoke instanceof String){
                                Method setReadOnly = workStaffCertificate.getClass().getMethod(setMethod, String.class);
                                if(logs!=null&&logs.size()>0){
                                    setReadOnly.invoke(workStaffCertificate,logs.get(0).getNewKey());
                                }
                            }
                            if(newInvoke instanceof Date){//日期
                                Method setReadOnly = workStaffCertificate.getClass().getMethod(setMethod, Date.class);
                                if(logs!=null&&logs.size()>0){
                                    Date myDate = dateFormat1.parse(logs.get(0).getNewKey());
                                    setReadOnly.invoke(workStaffCertificate,myDate);
                                }
                            }
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                newList.add(workStaffCertificate);
            }
        }
        //新增
        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());
                WorkStaffCertificate workStaffCertificate = new WorkStaffCertificate();
                workStaffCertificate.setId(w.getSonId());
                workStaffCertificate.setDelFlag("0");
                workStaffCertificate.setStaffId(workStaffBasicInfo.getId());
                Class<? extends WorkStaffCertificate> newClass = workStaffCertificate.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    String name = field.getName();
                    if("name".equals(name)||"num".equals(name)||"issuingAuthority".equals(name)||"issuingDate".equals(name)||"registDate".equals(name)
                            || "registNum".equals(name)||"major".equals(name)||"grade".equals(name)
                            ||"issType".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("registDate".equals(name)||"issuingDate".equals(name)){//日期
                                Method setReadOnly = workStaffCertificate.getClass().getMethod(setMethod, Date.class);
                                if(logs!=null&&logs.size()>0){
                                    Date myDate = dateFormat1.parse(logs.get(0).getNewKey());
                                    setReadOnly.invoke(workStaffCertificate,myDate);
                                }
                            }else{
                                Method setReadOnly = workStaffCertificate.getClass().getMethod(setMethod, String.class);
                                if(logs!=null&&logs.size()>0){
                                    setReadOnly.invoke(workStaffCertificate,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(workStaffCertificate);
            }
        }
        //删除
        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.setCertificateList(newList);
    }
    @Transactional(readOnly = false)
    public void saveEdu(WorkStaffBasicInfo workStaffBasicInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<WorkStaffCertificate> certificateList =workStaffBasicInfo.getCertificateList();
        if(certificateList!=null&&certificateList.size()>0){
            for(WorkStaffCertificate newCertificate:certificateList){
                Class<? extends WorkStaffCertificate> newClass = newCertificate.getClass();
                Field[] declaredFields = newClass.getDeclaredFields();
                if(newCertificate.getId()!=null&&!"1".equals(newCertificate.getDelFlag())&&!"".equals(newCertificate.getId())){
                    if(newCertificate.getFile()!=null&&!newCertificate.getFile().isEmpty()&&newCertificate.getFile().getSize()>0){
                        MultipartFile file = newCertificate.getFile();
                        newCertificate.setFilePath(this.uploadFile(file,newCertificate.getFilePath()));
                    }
                    WorkStaffCertificate oldCertificate=this.get(newCertificate.getId());
                    if(oldCertificate!=null){
                        Class<? extends WorkStaffCertificate> oldClass = oldCertificate.getClass();
                        for (Field field : declaredFields) {
                            String name = field.getName();
                            if("name".equals(name)||"num".equals(name)||"issuingAuthority".equals(name)||"issuingDate".equals(name)||"registDate".equals(name)
                                    || "registNum".equals(name)||"major".equals(name)||"grade".equals(name)
                                    ||"issType".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(newCertificate.getId());
                                workStaffAchivesLog.setFields(name);
                                workStaffAchivesLog.setState("1");
                                try {
                                    Object newInvoke = newClass.getMethod(methodName).invoke(newCertificate);//修改后
                                    Object oldInvoke = oldClass.getMethod(methodName).invoke(oldCertificate);//修改前
                                    String describes=EDU_MAP.get(name);
                                    if(newInvoke instanceof String){
                                        String newValue=newInvoke.toString();
                                        String oldValue=oldInvoke.toString();
                                        if(!newValue.equals(oldValue)){
                                            if("name".equals(name)){
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "执业资格证书",describes,name,
                                                        DictUtils.getMainDictLabel(oldValue,"certificate_type",""),
                                                        DictUtils.getMainDictLabel(newValue,"certificate_type",""),
                                                        oldValue,newValue,newCertificate.getId(),"修改");
                                            }else{
                                                workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                        "执业资格证书",describes,name,
                                                        oldInvoke.toString(),newInvoke.toString(),
                                                        oldInvoke.toString(),newInvoke.toString(),newCertificate.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,newCertificate.getId(),"修改");
                                        }
                                    }
                                } catch (NoSuchMethodException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }else if((newCertificate.getId()==null||"".equals(newCertificate.getId()))&&"0".equals(newCertificate.getDelFlag())){//新增
                    if(newCertificate.getFile()!=null&&!newCertificate.getFile().isEmpty()&&newCertificate.getFile().getSize()>0){
                        MultipartFile file = newCertificate.getFile();
                        newCertificate.setFilePath(this.uploadFile(file,newCertificate.getFilePath()));
                    }
                    String newId=IdGen.uuid();
                    for (Field field : declaredFields) {
                        String name = field.getName();
                        if("name".equals(name)||"num".equals(name)||"issuingAuthority".equals(name)||"issuingDate".equals(name)||"registDate".equals(name)
                                || "registNum".equals(name)||"major".equals(name)||"grade".equals(name)
                                ||"issType".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(newCertificate);//修改后
                                String describes=EDU_MAP.get(name);
                                if(newInvoke instanceof String){
                                    String newValue=newInvoke.toString();
                                    if("name".equals(name)){
                                        workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                                                "执业资格证书",describes,name,
                                                "",
                                                DictUtils.getMainDictLabel(newValue,"certificate_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(newCertificate.getId()!=null&&"1".equals(newCertificate.getDelFlag())&&!"".equals(newCertificate.getId())){//删除
                    WorkStaffAchivesLog workStaffAchivesLog=new WorkStaffAchivesLog();
                    workStaffAchivesLog.setStaffId(workStaffBasicInfo.getId());
                    workStaffAchivesLog.setModule("执业资格证书");
                    workStaffAchivesLog.setSonId(newCertificate.getId());
                    workStaffAchivesLog.setType("删除");
                    workStaffAchivesLog.setState("1");
                    workStaffAchivesLogService.saveStaffLog(workStaffAchivesLog,workStaffBasicInfo.getId(),
                            "执业资格证书","","",
                            "","",
                            "","",newCertificate.getId(),"删除");
                }
            }
        }
    }
}