package com.jeeplus.human.signature.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.human.depart.handover.domain.Handover;
import com.jeeplus.human.depart.handover.service.HandoverService;
import com.jeeplus.human.enrollment.enrollmentRegistration.utils.SnowFlake;
import com.jeeplus.human.signature.entity.PresignCallBack;
import com.jeeplus.human.signature.utils.*;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

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


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

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

    @Autowired
    private HandoverService handoverService;


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

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


        //将文件下载并对原有文件地址进行替换
        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("/","")+"/human_dimission_file"+SpringUtil.getBean ( IWorkAttachmentApi.class ).datePath()+"/"+ System.currentTimeMillis();
                        //文件原名称
                        String newName = cMultiFile.getOriginalFilename();
                        if(StringUtils.isNotBlank(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();

                    //将签章完成的附件进行保存到附件表中
                    WorkAttachmentInfo workattachment = new WorkAttachmentInfo();
                    workattachment.setDelFlag(0);
                    workattachment.setUrl(filepath);
                    workattachment.setType(substring);
                    workattachment.setAttachmentName(newFileName);
                    workattachment.setAttachmentFlag("dimission_file_signature");
                    workattachment.setFileSize(String.valueOf(f.length()));
                    workattachment.setAttachmentId(handover.getId());
                    workattachment.setAttachmentType("");
                    String id = SnowFlake.getId();
                    workattachment.setId(id);
                    workattachment.setCreateTime(new Date());
                    workattachment.setUpdateTime(new Date());
                    //先查询数据库中是否已经对数据进行保存
                    //若未保存，则进行保存，否则直接跳过
                    List<WorkAttachmentInfo> byAttachmentIdAndUrl = SpringUtil.getBean ( IWorkAttachmentApi.class ).selectListByAttachmentId(workattachment.getAttachmentId());
                    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);
                    }else{
                        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(handover.getId());
                        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);
                    }
                }
            }

        }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;
    }
}
