package com.jeeplus.finance.projectReport.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.finance.invoice.util.SignaturePostUtil;
import com.jeeplus.finance.projectReport.domain.CwProjectReportData;
import com.jeeplus.finance.projectReport.domain.CwProjectReportFile;
import com.jeeplus.finance.projectReport.domain.CwProjectReportSignature;
import com.jeeplus.finance.projectReport.domain.PresignCallBack;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportSignatureMapper;
import com.jeeplus.finance.projectReport.mapper.ProjectReportWorkAttachmentMapper;
import com.jeeplus.finance.projectReport.service.CwProjectReportService;
import com.jeeplus.finance.utils.Global;
import com.jeeplus.flowable.feign.IFlowableApi;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OSSClientService;
//import com.jeeplus.pubmodules.oss.service.dto.AttachmentDTO;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IOfficeApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
//import com.jeeplus.sys.service.OfficeService;
//import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.PostDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.Global;
//import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.FlowNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.jedis.JedisUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;
//import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartFile;

/**
 * 项目签章回调接口Controller
 * @author 徐滕
 * @version 2021-11-04
 */
@Controller
@RequestMapping(value = "/cwProjectReport/signatureCallBack")
@Transactional(rollbackFor = Exception.class)
public class CwProjectReportSignatureCallBackController {


    private static final String DIRECTORY  = Global.getConfig("directory");

    private static final String ALIYUNURL = Global.getConfig("aliyunUrl");

    @Autowired
    private CwProjectReportService cwProjectReportService;
//    @Autowired
//    private OSSClientService ossClientService;
//    @Autowired
//    private OssServiceMapper ossServiceMapper;
    @Autowired
    private CwProjectReportSignatureMapper cwProjectReportSignatureMapper;
    @Autowired
    private ProjectReportWorkAttachmentMapper attachmentMapper;
    @Autowired
    private CwProjectReportMapper reportMapper;
//    @Autowired
//    private UserService userService;

//    private static final String HTTPTOP = Global.getConfig("signature_http_top");
//
//    private final static String apptoken = Global.getConfig("apptoken");
//    private final static String appsecret = Global.getConfig("appsecret");
//    private final static String signature = Global.getConfig("signature");

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IFlowableApi flowTaskService;
//    @Autowired
//    private OfficeService officeService;


    /**
     * 审定单签章回调操作(个人职业章盖章)
     * @param presignCallBack  回调参数
     * @return
     */
    @RequestMapping(value = "/getApprovalCallBackCoordinates", method= RequestMethod.POST)
    public String getApprovalCallBackCoordinates(PresignCallBack presignCallBack, HttpServletResponse response) throws Exception {
        //查询报告签章id
        String id = (String) redisUtils.get("cw_report_signature_" + presignCallBack.getContractId());

        CwProjectReportSignature reportSignature = new CwProjectReportSignature();
        reportSignature.setId(id);
        //查询流程id
        String processInstanceId = reportMapper.getProcessInstanceIdById(id);
        if(StringUtils.isNotBlank(processInstanceId)){
            //根据流程id查询流程当前节点信息
            String currentTask = flowTaskService.getCurrentTaskName(processInstanceId);
            if(StringUtils.isNotEmpty(currentTask)){
                switch (currentTask){
                    case "签字注师1审核":
                        reportSignature.setSignatureAnnotator1Status("1");
                        cwProjectReportService.updateSignatureType(reportSignature);
                        break;
                    case "签字注师2审核":
                        reportSignature.setSignatureAnnotator2Status("1");
                        cwProjectReportService.updateSignatureType(reportSignature);
                        break;
                    case "签章管理员审核":
                    case "三级复核及签章":
                        reportSignature.setSealAdminStatus("1");
                        cwProjectReportService.updateSignatureType(reportSignature);
                        break;
                }
            }
        }

        /*// 在redis中取回流程审核所需的参数
        CommitParamDTO<CwProjectReportData> commitParamDTO = (CommitParamDTO<CwProjectReportData>)redisUtils.get("cw_report_signature_" + presignCallBack.getContractId());
        // 将取回的数据转换为审核通过所需要的参数
        Map<String, Object> vars = Maps.newHashMap();
        Flow flow = new Flow();
        flow.setTaskId(commitParamDTO.getTaskId());
        flow.setTaskDefKey(commitParamDTO.getTaskDefKey());
        flow.setProcInsId(commitParamDTO.getProcInsId());
        flow.setProcDefId(commitParamDTO.getProcDefId());
        flow.setAssignee(commitParamDTO.getAssignee());
        flow.setComment(commitParamDTO.getComment());
        Map<String, String> stringObjectMap = JSON.parseObject(JSON.toJSONString(commitParamDTO.getVars()), new TypeReference<Map<String, String>>() {});
        for (Map.Entry<String, String> entry : stringObjectMap.entrySet()) {
            String value = entry.getValue();
            if("true".equals(value) || "false".equals(value)){
                vars.put(entry.getKey(), Boolean.valueOf(value).booleanValue());
            }else{
                vars.put(entry.getKey(), value);
            }
        }
        // 流程节点审核通过
        flowTaskService.auditSave(flow, vars);
        CwProjectReport cwProjectReport = cwProjectReportService.list(new QueryWrapper<CwProjectReport>().lambda().eq(CwProjectReport::getSignatureContractId, presignCallBack.getContractId())).get(0);
        // 指定下一步处理人
        Task task = taskService.createTaskQuery().processInstanceId(flow.getProcInsId()).active().singleResult();
        // task为null时，则当前节点为最后一个审核节点
        if(task != null){
            if(StringUtils.isNotBlank(flow.getAssignee ())){
                taskService.setAssignee(task.getId(), flow.getAssignee ());
            }
            if(ObjectUtil.isNotEmpty(cwProjectReport)) {
                CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                        .eq(CwProjectReportSignature::getReportId, cwProjectReport.getId())
                        .eq(CwProjectReportSignature::getType, cwProjectReport.getSignatureType())
                );
                if ("2".equals(cwProjectReportSignature.getStatus())){
                    cwProjectReportSignature.setStatus("6");
                    cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
                }else if ("6".equals(cwProjectReportSignature.getStatus())){
                    cwProjectReportSignature.setStatus("7");
                    cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
                }
            }
        } else {
            // 修改数据流程状态为->审核通过
            if(ObjectUtil.isNotEmpty(cwProjectReport)) {
                CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                        .eq(CwProjectReportSignature::getReportId, cwProjectReport.getId())
                        .eq(CwProjectReportSignature::getType, cwProjectReport.getSignatureType())
                );
                cwProjectReportSignature.setStatus("5");
                cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
            }
        }*/
        // 删除redis中的数据
        redisUtils.delete("cw_report_signature_" + presignCallBack.getContractId());








//        Jedis jedis = JedisUtils.getResource();
//        String contractIdRedis = jedis.get("qiyuesuo" + presignCallBack.getContractId());
//        String auditUsersStr = jedis.get("qiyuesuoAuditUserList" + presignCallBack.getContractId());
//        Gson gson = new Gson();
//        ProjectApprovalSignature projectApprovalSignature1 = gson.fromJson(contractIdRedis, ProjectApprovalSignature.class);
//
//        Type listType = new TypeToken<ArrayList<User>>(){}.getType();
//        List<User> auditUserList = new Gson().fromJson(auditUsersStr, listType);
//
//        //根据contractId查询对应的报告信息
//        CwProjectReportData projectReportData = cwProjectReportService.queryById(projectApprovalSignature1.getId());
//
//        if(null == projectReportData){
//            return null;
//        }
//        //根据项目id查询对应的审定单数据状态是否是已经被送审
//        ProjectApprovalSignature projectApprovalSignature = cwProjectReportService.getProjectApprovalSignature(projectReportData.getId());

        //对数据进以及流程行处理
        //approvalSaveAudit(projectApprovalSignature1,auditUserList);

        return null;
    }


    @RequestMapping(value = "/getApprovalCallBackAccomplish", method= RequestMethod.POST)
    public String getApprovalCallBackAccomplish(PresignCallBack presignCallBack, HttpServletResponse response) {
        //根据contractId查询对应的报告信息
        CwProjectReportData projectReportData = cwProjectReportService.queryByContractId(presignCallBack.getContractId());
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getById (projectReportData.getCreateById());
        //对文件回调路径进行处理并保存
        String signatureUrl = null;
        if(StringUtils.isNotBlank(presignCallBack.getStoragePath())){
            signatureUrl = presignCallBack.getStoragePath().replace("oss:/","");
            signatureUrl = signatureUrl.replace("/xg-qz","");
            projectReportData.setSignatureUrl(signatureUrl);
        }

        //将签章完成地址保存到数据库对应报告信息中
        cwProjectReportService.updateSignatureUrl(projectReportData);


        //将文件下载并对原有文件地址进行替换
        String deleteFile = null;
        String unzipFileStr = null;
        try{
            String path = null;
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                path = "D:/attachment-file/";
            }else{
                path = "/attachment-file/";
            }
            String aliyunUrl = "http://cdn.gangwaninfo.com";
            String aliDownloadUrl = "http://oss.gangwaninfo.com";


            String file = aliyunUrl + signatureUrl;
            file = file.replace("amp;","");
            String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
            String cons = "";
            if (file.contains(aliyunUrl)){
                cons = aliyunUrl;
            }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
                cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
            }else {
                cons = aliDownloadUrl;
            }
            String ossKey = file.split(cons+"/")[1];
            SpringUtil.getBean ( IWorkAttachmentApi.class ).downQzByStreamSaveLocal(ossKey,fileName,path+fileName);
//            ossClientService.downQzByStreamSaveLocal(ossKey,fileName,path+fileName);
            //将下载下来的文件转换为file文件
            File srcFile = new File(path+fileName);
            deleteFile = path+fileName;

            //截取文件名称
            String srcFileName = srcFile.getName().substring(0,srcFile.getName().lastIndexOf("."));

            //解压后文件地址
            unzipFileStr = path + srcFileName;

            //将下载后的文件进行解压
            SignaturePostUtil.unZipFile(srcFile,unzipFileStr);

            //遍历解压后文件夹中的所有文件信息
            File unZipFile = new File(unzipFileStr);

            File[] unZipFileList = unZipFile.listFiles();

            if(null != unZipFileList && unZipFileList.length>0){
                for (File f : unZipFileList) {
                    String filepath = "";
                    //取得上传文件
                    //将文件上传到oss云盘中
                    MultipartFile cMultiFile = new MockMultipartFile("file", f.getName(), null, new FileInputStream(f));
                    if (!cMultiFile.isEmpty()) {
                        // 文件保存路径
                        String realPath =DIRECTORY.replace("/","")+"/cw_project_report_file"+SpringUtil.getBean ( IWorkAttachmentApi.class ).datePath()+"/"+ System.currentTimeMillis();
                        //文件原名称
                        String newName = cMultiFile.getOriginalFilename();
                        if(StringUtils.isNotBlank(newName)){
                            newName = newName.substring(13, newName.length());
                            //SpringUtil.getBean ( IWorkAttachmentApi.class ).uploadFile2OSS(cMultiFile.getInputStream(),realPath,newName);
                            SpringUtil.getBean ( IWorkAttachmentApi.class ).uploadFileSignatureOSS(f.getPath(),realPath,newName);
                            filepath = "/" + realPath + newName;
                        }
                    }

                    System.out.println(f.getName());
                    //截取文件后缀名
                    String substring = f.getName().substring(f.getName().lastIndexOf(".")+1, f.getName().length());

                    String newFileName = f.getName().substring(13, f.getName().length());

                    //将签章完成的附件进行保存到附件表中
                    WorkAttachmentInfo workattachment = new WorkAttachmentInfo();
                    workattachment.setDelFlag(0);
                    workattachment.setUrl(filepath);
                    workattachment.setType(substring);
                    workattachment.setAttachmentName(newFileName);
                    workattachment.setAttachmentFlag("cw_project_report_file_signature");
                    workattachment.setFileSize(String.valueOf(f.length()));
                    workattachment.setAttachmentId(projectReportData.getId());
                    workattachment.setAttachmentType("");
                    String id = UUID.randomUUID().toString().replace("-", "");
                    workattachment.setId(id);
                    workattachment.setCreateTime(new Date());
                    workattachment.setUpdateTime(new Date());
                    //先查询数据库中是否已经对数据进行保存
                    //若未保存，则进行保存，否则直接跳过
                    List<WorkAttachmentInfo> byAttachmentIdAndUrl = SpringUtil.getBean ( IWorkAttachmentApi.class ).getByAttachmentIdAndUrlAndAttachmentFlag(workattachment);
                    if(byAttachmentIdAndUrl.size() == 0){
                        Map<String,String> map = new HashMap<>();
                        String workAttachment = JSON.toJSONString((workattachment));
                        String userDTOInfo = JSON.toJSONString((userDTO));
                        map.put("workAttachment",workAttachment);
                        map.put("userDTO",userDTOInfo);
                        SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//                        ossServiceMapper.insert(workattachment);

                        //将附件信息添加到签章附件信息表中
                        CwProjectReportFile cwProjectReportFile = new CwProjectReportFile();
                        cwProjectReportFile.setDelFlag(0);
                        cwProjectReportFile.setId(UUID.randomUUID().toString().replace("-", ""));
                        cwProjectReportFile.setCreateById(projectReportData.getCreateById());
                        cwProjectReportFile.setUpdateById(projectReportData.getCreateById());
                        cwProjectReportFile.setCreateTime(new Date());
                        cwProjectReportFile.setUpdateTime(new Date());
                        cwProjectReportFile.setReportFileId(id);
                        cwProjectReportFile.setFileAffiliation("1");
                        cwProjectReportService.insertProjectReportFile(cwProjectReportFile);
                    }

                    //遍历该contractId对应的报告信息，将报告信息中的附件地址进行替换

                    //查询报告文件信息（电子章）
                    /*List<WorkAttachment> fileList = attachmentMapper.selectWorkAttachmentByReportId(projectReportData.getId());
                    if(fileList.size()>0){
                        for (WorkAttachment workattachment : fileList) {
                            //根据url截取文件名成
                            String workattachmentName = workattachment.getUrl().substring(workattachment.getUrl().lastIndexOf("/")+1, workattachment.getUrl().length());

                            if(f.getName().contains(workattachmentName)){
                                workattachment.setUrl(filepath);
                                workattachment.setType(substring);
                                workattachment.setAttachmentName(f.getName());
                                attachmentMapper.updateByIdOnSignature(workattachment);
                            }
                        }
                    }*/
                }
            }

            //将报告数据中的盖章状态更改为已盖章
            //cwProjectReportService.updateReportSealType(projectReportData);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(StringUtils.isNotBlank(deleteFile)){
                //根据路径创建文件对象
                File file = new File(deleteFile);
                //路径是个文件且不为空时删除文件
                if(file.isFile()&&file.exists()){
                    file.delete();
                }
            }
            File file = new File(unzipFileStr);
            deleteFile(file);
        }

        return null;
    }


    @RequestMapping(value = "/download", method= RequestMethod.POST)
    public String download(String signatureUrl) {
//        //根据contractId查询对应的报告信息
        CwProjectReportData projectReportData = cwProjectReportService.queryByContractId("3032604994397941821");

        //将文件下载并对原有文件地址进行替换
        String deleteFile = null;
        String unzipFileStr = null;
        try{
            String path = null;
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                path = "D:/attachment-file/";
            }else{
                path = "/attachment-file/";
            }
            String aliyunUrl = "http://cdn.gangwaninfo.com";
            String aliDownloadUrl = "http://oss.gangwaninfo.com";


            String file = aliyunUrl + signatureUrl;
            file = file.replace("amp;","");
            String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
            String cons = "";
            if (file.contains(aliyunUrl)){
                cons = aliyunUrl;
            }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
                cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
            }else {
                cons = aliDownloadUrl;
            }
            String ossKey = file.split(cons+"/")[1];
            SpringUtil.getBean ( IWorkAttachmentApi.class ).downQzByStreamSaveLocal(ossKey,fileName,path+fileName);
//            ossClientService.downQzByStreamSaveLocal(ossKey,fileName,path+fileName);
            //将下载下来的文件转换为file文件
            File srcFile = new File(path+fileName);
            deleteFile = path+fileName;

            //截取文件名称
            String srcFileName = srcFile.getName().substring(0,srcFile.getName().lastIndexOf("."));

            //解压后文件地址
            unzipFileStr = path + srcFileName;

            //将下载后的文件进行解压
            SignaturePostUtil.unZipFile(srcFile,unzipFileStr);

            //遍历解压后文件夹中的所有文件信息
            File unZipFile = new File(unzipFileStr);

            File[] unZipFileList = unZipFile.listFiles();

            for (File f : unZipFileList) {
                String filepath = "";
                //取得上传文件
                //将文件上传到oss云盘中
//                MultipartFile cMultiFile = new MockMultipartFile("file", f.getName(), null, new FileInputStream(f));
//                if (cMultiFile != null && !cMultiFile.isEmpty()) {
//                    // 文件保存路径
//                    String realPath =DIRECTORY.replace("/","")+"/cw_project_report_file"+ossClientService.datePath()+"/"+ System.currentTimeMillis();
//                    //文件原名称
//                    String newName = cMultiFile.getOriginalFilename();
//                    newName = newName.substring(13, newName.length());
//                    ossClientService.uploadFile2OSS(cMultiFile.getInputStream(),realPath,newName);
//                    filepath = "/" + realPath + newName;
//                }

                System.out.println(f.getName());
                //截取文件后缀名
                String substring = f.getName().substring(f.getName().lastIndexOf(".")+1, f.getName().length());
                //遍历该contractId对应的报告信息，将报告信息中的附件地址进行替换

                //查询报告文件信息（电子章）
                List<WorkAttachmentInfo> fileList = attachmentMapper.selectWorkAttachmentByReportId(projectReportData.getId());
                if(fileList.size()>0){
                    for (WorkAttachmentInfo workattachment : fileList) {
                        //根据url截取文件名成
                        String workattachmentName = workattachment.getUrl().substring(workattachment.getUrl().lastIndexOf("/")+1, workattachment.getUrl().length());

                        if(f.getName().contains(workattachmentName)){
                            workattachment.setUrl(filepath);
                            workattachment.setType(substring);
                            workattachment.setAttachmentName(f.getName());
                            attachmentMapper.updateByIdOnSignature(workattachment);
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(StringUtils.isNotBlank(deleteFile)){
                //根据路径创建文件对象
                File file = new File(deleteFile);
                //路径是个文件且不为空时删除文件
                if(file.isFile()&&file.exists()){
                    file.delete();
                }
            }
            File file = new File(unzipFileStr);
            deleteFile(file);
        }

        return null;
    }

    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
                //打印文件名
                System.out.println("文件名：" + f.getName());
            }
        }
        //文件夹删除
        file.delete();
        System.out.println("目录名：" + file.getName());
        return true;
    }

    @RequestMapping(value = "/updateAllUser", method= RequestMethod.POST)
    @ResponseBody
    public void updateAllUser() {
        // 查询全部用户
//        Page<UserDTO> page = new Page<>();
//        page.setCurrent(1);
//        page.setSize(-1);
        IPage<UserDTO> pageList = SpringUtil.getBean ( IUserApi.class ).findPage();
        // 将全部用户数据执行保存操作
        pageList.getRecords().stream().forEach(uuu -> {
            try {
                UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getById ( uuu.getId() );
                if(StringUtils.isNotBlank(userDTO.getManageOfficeIds())){
                    //获取当前人管理的部门id
                    List<String> manageOfficeIdList=Arrays.asList(userDTO.getManageOfficeIds().split(","));
                    //查询这些部门信息
                    List<String> officeNameList = SpringUtil.getBean ( IOfficeApi.class ).getOfficeNameByIds(manageOfficeIdList);
                    userDTO.setManageOfficeNameList(officeNameList);
                }
                if(ObjectUtil.isNotEmpty(userDTO)) {
                    if(CollectionUtil.isNotEmpty(userDTO.getCertDTOList())){
                        userDTO.getCertDTOList().stream().forEach(item->{
                            if (StringUtils.isNotBlank(item.getFileUrl())){
                                String fileTemporaryLookUrl = this.getFileTemporaryLookUrl(item.getFileUrl());
                                item.setFileLsUrl(fileTemporaryLookUrl);
                            }
                        });
                    }
                }
                //根据office.id 查询部门的所有父节点信息
                if(null != userDTO.getOfficeDTO() && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId())){
                    OfficeDTO office = SpringUtil.getBean ( IOfficeApi.class ).getOfficeById(userDTO.getOfficeDTO().getId());
                    //将office的父节点信息进行分割并查询赋值
                    if(null != office){
                        List<String> officeIdList = Arrays.asList(office.getParentIds().split(","));
                        Integer sort = 0;
                        if(null != officeIdList && officeIdList.size()>0){
                            for (String officeId : officeIdList) {
                                if(StringUtils.isNotBlank(officeId) && !"0".equals(officeId)){
                                    sort ++ ;
                                    OfficeDTO officeChild = SpringUtil.getBean ( IOfficeApi.class ).getOfficeById(officeId);
                                    if(null != officeChild) {
                                        switch (sort){
                                            case 1:
                                                userDTO.setCompanyDTO(officeChild);
                                                break;
                                            case 2:
                                                userDTO.setCorporationDTO(officeChild);
                                                break;
                                            case 3:
                                                userDTO.setOfficeDTO(officeChild);
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
                SpringUtil.getBean ( IUserApi.class ).saveOrUpdate(userDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    @Value("${config.accessory.aliyun.aliyunUrl}")
    private String aliyunUrl;
    @Value("${config.accessory.aliyun.aliyunDownloadUrl}")
    private String aliyunDownloadUrl;
    @Value("${config.accessory.aliyun.endpoint}")
    private String endpoint;
    @Value("${config.accessory.aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${config.accessory.aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${config.accessory.aliyun.bucketName}")
    private String bucketName;
    /**
     * 阿里云获取临时文件查看url
     * @param url
     */
    public String getFileTemporaryLookUrl(String url){
        url = url.replace("amp;","");
        String cons = "";
        if (url.contains(aliyunUrl)){
            cons = aliyunUrl;
        }else if (url.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
            cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
        }else {
            cons = aliyunDownloadUrl;
        }
        String key = "";
        String[] split = url.split(cons + "/");
        if(split.length>1){
            key = split[1];
        }else{
            key = url;
        }
        // 指定过期时间为24小时。
        Date expiration = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 );
        //初始化OSSClient
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        return ossClient.generatePresignedUrl(bucketName, key, expiration).toString();
    }

}
