package com.yccrc.kede.controller.other;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mchange.io.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
//import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yccrc.common.annotation.Log;
import com.yccrc.common.config.YccrcConfig;
import com.yccrc.common.core.controller.BaseController;
import com.yccrc.common.vo.*;
import io.swagger.annotations.*;
import com.yccrc.common.enums.BusinessType;
import com.yccrc.common.exception.ServiceException;
import com.yccrc.common.utils.PageUtils;
import com.yccrc.kede.domain.Attach;
import com.yccrc.kede.domain.Project;
import com.yccrc.kede.enums.AttachTypeEnum;
import com.yccrc.kede.service.IAttachService;
import com.yccrc.kede.service.IProjectService;
import com.yccrc.kede.vo.ProjectDetailVO;
import com.yccrc.kede.vo.ProjectListVO;
import com.yccrc.kede.vo.ProjectQueryVO;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import java.io.*;

/**
 * 项目信息Controller
 * 
 * @author yccrc
 * @date 2022-04-25
 */
@Api(tags = "项目申报")
@RestController
@RequestMapping("/project")
public class ProjectApplyController extends BaseController
{
    @Autowired
    private IProjectService projectService;

    @Autowired
    private IAttachService attachService;
    
//    @ApiOperation(value = "查询项目信息列表")
//    @GetMapping("/list")
//    public Result<Page<ProjectListVO>> list(ProjectQueryVO project)
//    {
//       return new Result<Page<ProjectListVO>>().ok(projectService.selectProject(project));
//     
//    }
    
    @ApiOperation(value = "查询项目信息列表")
    @GetMapping("/list")
    public Result<Page<Project>> list(ProjectQueryVO project)
    {
       return new Result<Page<Project>>().ok(projectService.selectReportProject(project));
     
    }
    

    @ApiOperation(value = "获取项目信息详细信息")
    @GetMapping(value = "/{id}")
    public Result<ProjectDetailVO> getInfo(@PathVariable("id") Integer id)
    {
        return new Result<ProjectDetailVO>().ok(projectService.getProject(id));
    }

    
    @ApiOperation(value = "下载指定项目附件")
	@GetMapping("download/{projectIds}")
    public void download(HttpServletResponse response, @PathVariable Integer[] projectIds) throws IOException{
    	String downloadFileName = "";
    	if(projectIds==null||projectIds.length==0) throw new ServiceException("项目ID不能为空");
    	
    	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        
    	for(Integer projectId:projectIds) {
    		ProjectDetailVO pro = projectService.getProject(projectId);
    		if(pro!=null) {
    			downloadFileName+=pro.getEntProject().getProjectName()+"_";
    			
    			//企业
    			List<Attach> attachEntList = attachService.lambdaQuery().eq(Attach::getAttachType, AttachTypeEnum.PROJECT).eq(Attach::getDataId, pro.getEntProject().getId()).list();
    			
    			//技术
    			List<Attach> attachTechList = attachService.lambdaQuery().eq(Attach::getAttachType, AttachTypeEnum.PROJECT).eq(Attach::getDataId, pro.getTechProject().getId()).list();
    			
    			//财务
    			List<Attach> attachFinList = attachService.lambdaQuery().eq(Attach::getAttachType, AttachTypeEnum.PROJECT).eq(Attach::getDataId, pro.getFinProject().getId()).list();
    			
    			//其他财务资料附件
    			List<Attach> attachFinacList = attachService.lambdaQuery().eq(Attach::getAttachType, AttachTypeEnum.FINACIAL).eq(Attach::getDataId, pro.getFinProject().getId()).list();
    			
    			
    			if(!CollectionUtil.isEmpty(attachEntList)) {
    				logger.info("打包企业资料");
    				ArrayList<String> fileList = new ArrayList<>();
    				for(Attach attach:attachEntList) {
    					File file = new File(YccrcConfig.getUploadPath()+attach.getFileKey());
        	            if(file.exists()) {
        	            	logger.info(file.getName());
        	            	try {
        	            		String fileName = attach.getFileName();
        	            		if(fileList.contains(fileName)){
        	            			fileName = FileUtil.getPrefix(fileName) +"_"+RandomUtil.randomString(3)+"." + FileUtil.getSuffix(fileName);
        	            		}
        	            		fileList.add(fileName);
        	            		
        	            		 ZipEntry e = new ZipEntry(pro.getEntProject().getProjectName()+"/企业/"+fileName);
         	            		logger.info(e.getName());
         	            		 zip.putNextEntry(e);
         	            		 
        	                    IOUtils.write(FileUtils.getBytes(file), zip);
        	                    zip.flush();
        	                    zip.closeEntry();
        	            	} catch (IOException e)
        	                {
        	            		logger.error("文件写入压缩包失败：" + attach.getFileName(), e);
        	                }
        	            	 
        	            }
        	        }
    			}
    			
    			if(!CollectionUtil.isEmpty(attachTechList)) {
    				logger.info("打包技术资料");
    				ArrayList<String> fileList = new ArrayList<>();
    				for(Attach attach:attachTechList) {
    					File file = new File(YccrcConfig.getUploadPath()+attach.getFileKey());
        	            if(file.exists()) {
        	            	logger.info(file.getName());
        	            	try {
        	            		String fileName = attach.getFileName();
        	            		if(fileList.contains(fileName)){
        	            			fileName = FileUtil.getPrefix(fileName) +"_"+RandomUtil.randomString(3)+"." + FileUtil.getSuffix(fileName);
        	            		}
        	            		fileList.add(fileName);
        	            		
        	            		 ZipEntry e = new ZipEntry(pro.getEntProject().getProjectName()+"/技术/"+fileName);
         	            		logger.info(e.getName());
         	            		 zip.putNextEntry(e);
         	            		 
        	                    IOUtils.write(FileUtils.getBytes(file), zip);
        	                    zip.flush();
        	                    zip.closeEntry();
        	            	} catch (IOException e)
        	                {
        	            		logger.error("文件写入压缩包失败：" + attach.getFileName(), e);
        	                }
        	            	 
        	            }
        	        }
    			}
    			
    			if(!CollectionUtil.isEmpty(attachFinList)) {
    				logger.info("打包财务资料");
    				ArrayList<String> fileList = new ArrayList<>();
    				for(Attach attach:attachFinList) {
    					File file = new File(YccrcConfig.getUploadPath()+attach.getFileKey());
        	           
        	            if(file.exists()) {
        	            	logger.info(file.getName());
        	            	try {
        	            		String fileName = attach.getFileName();
        	            		if(fileList.contains(fileName)){
        	            			fileName = FileUtil.getPrefix(fileName) +"_"+RandomUtil.randomString(3)+"." + FileUtil.getSuffix(fileName);
        	            		}
        	            		fileList.add(fileName);
        	            		
        	            		 ZipEntry e = new ZipEntry(pro.getEntProject().getProjectName()+"/财务/"+fileName);
         	            		logger.info(e.getName());
         	            		 zip.putNextEntry(e);
         	            		 
        	                    IOUtils.write(FileUtils.getBytes(file), zip);
        	                    zip.flush();
        	                    zip.closeEntry();
        	            	} catch (IOException e)
        	                {
        	            		logger.error("文件写入压缩包失败：" + attach.getFileName(), e);
        	                }
        	            	 
        	            }
        	        }
    			}
    			
    			if(!CollectionUtil.isEmpty(attachFinacList)) {
    				logger.info("打包财务其他资料");
    				ArrayList<String> fileList = new ArrayList<>();
    				for(Attach attach:attachFinacList) {
    					File file = new File(YccrcConfig.getUploadPath()+attach.getFileKey());
        	           
        	            if(file.exists()) {
        	            	logger.info(file.getName());
        	            	try {
        	            		String fileName = attach.getFileName();
        	            		if(fileList.contains(fileName)){
        	            			fileName = FileUtil.getPrefix(fileName) +"_"+RandomUtil.randomString(3)+"." + FileUtil.getSuffix(fileName);
        	            		}
        	            		fileList.add(fileName);
        	            		// 添加到zip
        	                   // zip.putNextEntry(new ZipEntry(attach.getFileName()));
        	            		ZipEntry e = new ZipEntry(pro.getEntProject().getProjectName()+"/财务其他/"+fileName);
        	            		logger.info(e.getName());
        	            		 zip.putNextEntry(e);
        	            		
        	                    IOUtils.write(FileUtils.getBytes(file), zip);
        	                    zip.flush();
        	                    zip.closeEntry();
        	            	} catch (IOException e)
        	                {
        	            		logger.error("文件写入压缩包失败：" + attach.getFileName(), e);
        	                }
        	            	 
        	            }
        	        }
    			}
    		}
    	}
    	downloadFileName+=DateUtil.format(new Date(), "HHmmss")+".zip";
    	
        IOUtils.closeQuietly(zip);
        byte[] data = outputStream.toByteArray();
        logger.info("data.lenght:{}",data.length);
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\""+java.net.URLEncoder.encode(downloadFileName,"utf-8").replaceAll("\\+", "%20")+"\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
    
}
