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

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.IdGen;
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.mapper.MaterialLibraryMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
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.*;

/**
 * 物料库Service
 * @author: 黄俊杰
 * @create: 2022-02-28 16:00
 */
@Service
@Transactional(readOnly = true)
public class MaterialLibraryService extends CrudService<MaterialLibraryMapper, MaterialLibrary> {

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

    @Autowired
    private MaterialLibraryMapper materialLibraryMapper;

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

    /**
     * 数据验证
     * @param file
     * @return
     * @throws Exception
     */
    public LinkedHashMap dataVerification(MultipartFile file) throws Exception{
        LinkedHashMap returnMap = new LinkedHashMap();
        //查询数据库的物料库表中是否含有数据
        Integer materialCount= materialLibraryMapper.getMaterialCodeByMaterialCount();
        if(materialCount>0){
            File multipartFile = transformMultipartFile(file);
            try {
                //将文件存到服务器
                String filePath = saveFile(multipartFile);
                returnMap.keySet().removeIf(key -> key == "repeat");
                returnMap.put("repeat", "3");
                returnMap.put("success", true);
                returnMap.put("filePath", filePath);
                returnMap.keySet().removeIf(key -> key == "msg");
                returnMap.put("msg", "已存在物料数据，是否覆盖？");
            }catch (Exception e){
                e.getMessage();
            }finally {
                multipartFile.delete();
            }
        }else{
            returnMap.put("success",false);
        }
        return returnMap;
    }



    /**
     * 物流库信息导入处理
     * @param list
     * @return
     */
    @Transactional(readOnly = false)
    public LinkedHashMap disposeImportMaterialLibrary(List<MaterialLibrary> list,MultipartFile file,String repeat) throws Exception{
        LinkedHashMap returnMap = new LinkedHashMap();
        Integer index= 2;
        Iterator<MaterialLibrary> its = list.iterator();
        while(its.hasNext()){  //验证主键不为空
            index ++;
            MaterialLibrary info = its.next();
            if(StringUtils.isBlank(info.getMaterialCode())){
                returnMap.put("success",false);
                returnMap.put("msg","第" + index + "行，存在物料编码为空的数据，请确认后重新提交！");
                return returnMap;
            }
        }

        if(repeat.equals("1")){  //覆盖 则删除数据库中的重复数据
            //删除数据库中数据
            if(list.size()>0){
                //提前保存读取的list的长度
                int size = list.size();
                materialLibraryMapper.deleteAll();
                modifyHandmadeVindicateList(list);

                returnMap.keySet().removeIf(key -> key == "msg");
                returnMap.put("success",true);
                returnMap.put("msg","已成功导入 "+size+" 条物料库记录");
            }else{
                returnMap.keySet().removeIf(key -> key == "msg");
                returnMap.put("success",false);
                returnMap.put("msg","导入表数据量为0条，不进行替换");
            }

        }
        return returnMap;
    }



    /**
     * 批量修改手工上传数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyHandmadeVindicateList(List<MaterialLibrary> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 5000;//限制条数
            Integer size = projectBasicsList.size();
            //判断是否有必要分批
            if(pointsDataLimit<size){
                int part = size/pointsDataLimit;//分批数
                //
                for (int i = 0; i < part; i++) {
                    //100条
                    List<MaterialLibrary> listPage = projectBasicsList.subList(0, pointsDataLimit);
                    for(MaterialLibrary info:listPage){
                        info.preInsert();
                    }
                    materialLibraryMapper.insertList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    for(MaterialLibrary info:projectBasicsList){
                        info.preInsert();
                    }
                    materialLibraryMapper.insertList(projectBasicsList);
                }
            }else{
                for(MaterialLibrary info:projectBasicsList){
                    if(StringUtils.isNotBlank(info.getMaterialCode())) {
                        info.preInsert();
                        System.out.println("111");
                    }
                }
                materialLibraryMapper.insertList(projectBasicsList);
            }
        }
        return null;
    }

    /**
     * 批量修改手工上传数据信息
     * @param projectBasicsList
     * @return
     */
    @Transactional(readOnly = false)
    public String modifyHandmadeVindicateListTwo(List<String> projectBasicsList){
        //分批处理
        if(null!=projectBasicsList && projectBasicsList.size()>0){
            int pointsDataLimit = 5000;//限制条数
            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);
                    materialLibraryMapper.deleteList(listPage);
                    //剔除
                    projectBasicsList.subList(0, pointsDataLimit).clear();
                }
                if(!projectBasicsList.isEmpty()){
                    materialLibraryMapper.deleteList(projectBasicsList);
                }
            }else{
                materialLibraryMapper.deleteList(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;
    }
}
