package com.jeeplus.modules.supply.projectInformation.service;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.supply.materialLibrary.entity.MaterialLibrary;
import com.jeeplus.modules.supply.materialLibrary.service.MaterialLibraryService;
import com.jeeplus.modules.supply.projectInformation.entity.ProjectInformation;
import com.jeeplus.modules.supply.projectInformation.entity.RealProjectInformation;
import com.jeeplus.modules.supply.projectInformation.mapper.ProjectInformationMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
public class ProjectInformationService extends CrudService<ProjectInformationMapper, ProjectInformation> {

    /** 主机 */
    private final static String host = Global.getConfig("remoteServer.host");
    private static Logger logger = LoggerFactory.getLogger(MaterialLibraryService.class);

    @Autowired
    private ProjectInformationMapper projectInformationMapper;


    //页面显示
    @Override
    public Page<ProjectInformation> findPage(Page<ProjectInformation> page, ProjectInformation projectInformation){
        return super.findPage(page,projectInformation);
    }

    /**
     * 物流库信息导入处理
     * @param list
     * @return
     */
    @Transactional(readOnly = false)
    public LinkedHashMap disposeImportProjectInformation(List<ProjectInformation> list, MultipartFile file, String repeat) throws Exception{
        LinkedHashMap returnMap = new LinkedHashMap();
        Set<String> submissionFormIdSet = new HashSet<>();
        for (ProjectInformation importInfo : list){
            //将审定单id放入set中
            submissionFormIdSet.add(importInfo.getSubmissionFormId());
        }
        //将去重后的set转换为list  方便比较
        List<String> submissionFormIdList = new ArrayList<>(submissionFormIdSet);

        //判断物流编码list长度和导入数据的list长度是否一样，不一样则说明导入数据中项目名存在重复数据
        if(submissionFormIdList.size() != list.size()){
            returnMap.keySet().removeIf(key -> key == "msg");
            returnMap.put("msg","数据中存在重复审定单id");
        }


        //将项目信息的内容去重  遍历
        List<ProjectInformation> projectInformationList = new ArrayList();
        Set<String> projectDefinitionNumberSet = new HashSet<>();//去重后的项目定义号
        for(int i=0;i<list.size();i++){ //遍历取出项目定义号   这里需要优化吗？
            projectDefinitionNumberSet.add(list.get(i).getProjectDefinitionNumber());
        }
        Iterator<String> projectDefinitionNumberIt = projectDefinitionNumberSet.iterator();//将项目定义号加入迭代器
        while(projectDefinitionNumberIt.hasNext()){//遍历迭代器，遍历list数据，当存在两个项目定义号相等时，存入新的list结合，为项目信息表的导入做准备
            String projectDefinitionNumber = projectDefinitionNumberIt.next();
            for(ProjectInformation info:list){
                if(info.getProjectDefinitionNumber().equals(projectDefinitionNumber)){
                    projectInformationList.add(info);
                    break;
                }
            }
        }



        //方便快捷删除  找到对应重复数据，以便最后批量操作使用  审定单id
        List<String> codeList = projectInformationMapper.getSubmissionFormIdListBysubmissionFormIdList(submissionFormIdList);  //即为重复数据的审定单id集合
        Iterator<ProjectInformation> it = list.iterator();
        if(codeList.size()!=0 && repeat.equals("0") && codeList != null) {  //有重复值并且为第一次交互  就保存文件
            File copyFile = transformMultipartFile(file);
            //将文件存到服务器
            String filePath = saveFile(copyFile);
            returnMap.put("filePath",filePath);
            returnMap.keySet().removeIf(key -> key == "msg");
            returnMap.put("msg","已存在物料数据，是否覆盖？");
            return returnMap;
        }

        if(repeat.equals("2")) {  //不覆盖 则删除list中的重复数据
            while (it.hasNext()) {
                ProjectInformation projectInformation = it.next();
                if (codeList.contains(projectInformation.getSubmissionFormId())) {
                    it.remove();
                }
            }
            Iterator<ProjectInformation> projectIt = projectInformationList.iterator();
            while(projectIt.hasNext()){
                ProjectInformation projectInformation = projectIt.next();
                if(codeList.contains(projectInformation.getSubmissionFormId())){
                    projectIt.remove();
                }
            }
        }else if(repeat.equals("1")){  //覆盖 则删除数据库中的重复数据
            //批量删除重复数据  覆盖操作
            modifyHandmadeVindicateListTwo(codeList);
        }


        //批量新增  分批次新增
        if(list.size()!=0) {
            modifyHandmadeVindicateList(list);
            modifyHandmadeVindicateList2(projectInformationList);
        }

        returnMap.keySet().removeIf(key -> key == "msg");
        returnMap.put("msg","已成功导入 "+list.size()+" 条项目表单记录");
        return returnMap;
    }

    /**
     * 批量修改手工上传数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyHandmadeVindicateList(List<ProjectInformation> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 1000;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<ProjectInformation> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    projectInformationMapper.insertSubmissionFormList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    projectInformationMapper.insertSubmissionFormList(projectBasicsList);
                }
            }else{
                projectInformationMapper.insertSubmissionFormList(projectBasicsList);
            }
        }
        return null;
    }

    /**
     * 批量修改手工上传数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyHandmadeVindicateList2(List<ProjectInformation> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 1000;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<ProjectInformation> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    projectInformationMapper.insertProjectInformationList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    projectInformationMapper.insertProjectInformationList(projectBasicsList);
                }
            }else{
                projectInformationMapper.insertProjectInformationList(projectBasicsList);
            }
        }
        return null;
    }

    /**
     * 批量修改手工上传数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyHandmadeVindicateListTwo(List<String> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 1000;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<String> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    projectInformationMapper.deleteAll(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    projectInformationMapper.deleteAll(projectBasicsList);
                }
            }else{
                projectInformationMapper.deleteAll(projectBasicsList);
            }
        }
        return null;
    }

    //文件的操作
    public String saveFile(File file){
        String filePath = "";
        try {
            if(StringUtils.isNotBlank(host) && ("127.0.0.1".equals(host) || "localhost".equals(host))){
                String path = null;
                if(System.getProperty("os.name").toLowerCase().contains("win")){
                    path = Global.getConfig("remoteServer.winDirectory");
                }else{
                    path = Global.getConfig("remoteServer.directory");
                }
                Calendar date = Calendar.getInstance();
                date.add(Calendar.DAY_OF_MONTH,0);
                String nowTime = new SimpleDateFormat("yyyy_MM_dd").format(date.getTime());
                String uploadPath = "/"+nowTime+System.currentTimeMillis();
                //检查该路径对应的目录是否存在. 如果不存在则创建目录
                File dir=new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                filePath = path  + uploadPath + file.getName();  //存到服务武器的路径名
                //File转MultipartFile文件
                MultipartFile multipartFile = transformFile(file);
                //保存文件
                File dest = new File(filePath);
                if (!(dest.exists())) {
                    multipartFile.transferTo(dest);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("Exception e:"+e);
        }
        return filePath;
    }

    //文件的删除操作
    public void deleteFileContent(File file) throws IOException {
        String filePath = file.getAbsolutePath();
        File deleteFile = new File(filePath);
        if(deleteFile.exists()){
            deleteFile.delete();
        }
    }

    /**
     * MultipartFile转File
     * @param file
     * @return
     * @throws IOException
     */
    public File transformMultipartFile( MultipartFile file) throws IOException {
        File srcFile = null;
        //MultipartFile转File
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            srcFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, srcFile);
            ins.close();
        }
        return srcFile;
    }

    /**
     * 获取流文件
     * @param ins
     * @param file
     */
    public void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * File转MultipartFile
     * @param file
     * @return
     */
    public MultipartFile transformFile(File file){
        InputStream inputStream = null;
        MultipartFile multipartFile = null;
        try {
            inputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(), inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return multipartFile;
    }

    //定时任务删除前两天数据
    @Scheduled(cron = "0 */2 * * * ?")
    public void deleteFileByCron(){
        try{
            if(StringUtils.isNotBlank(host) && ("127.0.0.1".equals(host) || "localhost".equals(host))){
                String path = null;
                if(System.getProperty("os.name").toLowerCase().contains("win")){
                    path = Global.getConfig("remoteServer.winDirectory");
                }else{
                    path = Global.getConfig("remoteServer.directory");
                }
                //删除  路径名
                File file = new File(path);
                File[] files = file.listFiles();
                //获取要删除的时间
                Calendar date = Calendar.getInstance();
                date.add(Calendar.DAY_OF_MONTH,-1);
                String oldOneTime = new SimpleDateFormat("yyyy_MM_dd").format(date.getTime());
                date.add(Calendar.DAY_OF_MONTH,-1);
                String oldTwoTime = new SimpleDateFormat("yyyy_MM_dd").format(date.getTime());
                //遍历获取全部文件名
                for(File fi:files){
                    if(fi.isFile()){  //如果是文件  取到名称集合
                        String fileName = fi.getName();
                        if(fileName.contains(oldOneTime) || fileName.contains(oldTwoTime)){  //删除前两天的文件
                            fi.delete();
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void delete(String id){
        projectInformationMapper.deletex(id);
    }

}
