package com.pqs9300.serviceimpl.uploadFiles;

import com.pqs9300.mapper.uploadFiles.UploadFilesMapper;
import com.pqs9300.pojo.transaction.OverRunLog;
import com.pqs9300.service.uploadFiles.UploadFilesService;
import com.pqs9300.util.SocketSender;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: xuyang
 * @Description:
 */
@Service
public class UploadFilesServiceImpl implements UploadFilesService {
    private static final Logger logger = LoggerFactory.getLogger(UploadFilesServiceImpl.class);
    @Autowired
    private UploadFilesMapper uploadFilesMapper;

    @Resource
    private SocketSender socketSender;

    @Override
    public Map<String, Object> fileInformation(MultipartFile file, HttpServletRequest request, HttpServletResponse response, String supIndex, String lineIndex, Integer stepCount, String updateTime) {
        Map<String,Object> map = new HashMap<String,Object>();
        // 设置返回信息
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //真实路径
        String realpath="";
        //文件名
        String fileName = file.getOriginalFilename();
        //文件大小
        Long fileSize  = file.getSize()/1024;
        String uploadFileName = fileName.substring(0, fileName.lastIndexOf("."));
        //文件后缀,判断上传文件格式
        String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        //判断文件大小、再判断文件名、再判断文件类型、最后写入
        if (fileSize <= 3072 ){
            if (judgeFileType(subffix)){
                if (judgeFileName(supIndex,uploadFileName,lineIndex,updateTime)){
                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                    if (isMultipart){
                        //存放文件的文件夹
                        String fileDir = "one_upload";
                        //获取项目路径到webapp
                        String filepath = request.getSession().getServletContext().getRealPath("/")+fileDir;
                        File newFile=new File(filepath);
                        //目录不存在就创建
                        if(!newFile.exists()){
                            newFile.mkdirs();
                        }
                        try {
                            //保存文件
                            file.transferTo(new File(newFile+"\\"+fileName));
                            String url = "/" + fileDir + "/" + fileName;
                            realpath=newFile+"\\"+fileName;
                            updateFileUrl(stepCount,url,supIndex,lineIndex,updateTime);
                            map.put("msg","文件上传成功！");
                            map.put("code",0);
                            //判断需不需要修改流程状态
                            if (overRunLogList(supIndex,stepCount)){
                                int type = supIndexType(supIndex);
                                updateFileProgress(supIndex, stepCount, type, socketSender);
                            }
                        } catch (IOException e) {
                            logger.error(e.getMessage());
                        }
                    } else {
                        map.put("msg","文件信息错误！");
                        map.put("code",-1);
                    }
                } else {
                    map.put("msg","上传文件名与规定文件名称不一致，是否继续上传？(继续上传将修改您上传的文件名)");
                    map.put("code",-2);
                }
            }else {
                map.put("msg","上传失败，上传文件类型不符合。请上传pdf/图片(jpg、jepg、png)/word类型的文件");
                map.put("code",-1);
            }
        }else {
            map.put("msg","上传失败，文件过大。(请上传小于3M的文件)");
            map.put("code",-5);
        }
        return map;
    }

    @Override
    public Map<String, Object> fileCommit(MultipartFile file, HttpServletRequest request, HttpServletResponse response, String supIndex, String lineIndex, Integer stepCount, String updateTime) {
        Map<String,Object> map = new HashMap<String,Object>();
        // 设置返回信息
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //真实路径
        String realpath="";
        //文件名
        String fileName = file.getOriginalFilename();
        //文件后缀,用于拼接规定文件名称
        String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        //系统规定文件名称
        String sysName = uploadFilesMapper.getOverRunLogName(supIndex,lineIndex,timeStampDate(updateTime));
        String systemName = sysName + "." + subffix;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart){
            //存放文件的文件夹
            String fileDir = "one_upload";
            //获取项目路径到webapp
            String filepath = request.getSession().getServletContext().getRealPath("/")+fileDir;
            File newFile=new File(filepath);
            //目录不存在就创建
            if(!newFile.exists()){
                newFile.mkdirs();
            }
            try {
                //保存文件
                file.transferTo(new File(newFile+"\\"+systemName));
                String url = "/" + fileDir + "/" + systemName;
                realpath=newFile+"\\"+systemName;
                updateFileUrl(stepCount,url,supIndex,lineIndex,updateTime);
                map.put("msg","文件上传成功！");
                map.put("code",0);
                if (overRunLogList(supIndex,stepCount)){
                    int type = supIndexType(supIndex);
                    updateFileProgress(supIndex, stepCount, type, socketSender);
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        } else {
            map.put("msg","文件信息错误！");
            map.put("code",-1);
        }
        return map;
    }

    @Override
    public Boolean judgeFileName(String supIndex, String fileName, String lineIndex, String updateTime) {
        boolean result = false;
        Date time = timeStampDate(updateTime);
        String name = uploadFilesMapper.getOverRunLogName(supIndex,lineIndex,time);
        result = name.equals(fileName);
        return result;
    }

    @Override
    public Boolean judgeFileType(String subffix) {
        boolean result = false;
        String arr[] = {"pdf","jepg","jpg","png","JPG","PNG","doc","docx"};
        for (int i=0;i<arr.length;i++){
            if (arr[i].equals(subffix)){
                result = true;
            }
        }
        return result;
    }

    @Override
    public void updateFileUrl(Integer stepCount, String filePath, String supIndex, String lineIndex, String updateTime) {
        Date time = timeStampDate(updateTime);
        if (stepCount == 2){
            uploadFilesMapper.updateFeedbackUrl(filePath,supIndex,lineIndex,time);
        } else if (stepCount == 3){
            uploadFilesMapper.updateTestReportUrl(filePath,supIndex,lineIndex,time);
        } else if (stepCount == 5){
            uploadFilesMapper.updateReviseFeedbackUrl(filePath,supIndex,lineIndex,time);
        }
    }


    @Override
    public Map<String, Object> uploadFiles(MultipartFile file, HttpServletRequest request,  HttpServletResponse response,String supIndex, Integer stepCount) {
        Map<String,Object> map = new HashMap<String,Object>();
        List<String> fileList = uploadFilesMapper.getAllFileName(supIndex, stepCount);
        // 设置返回信息
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //真实路径
        String realpath="";
        //文件名
        String fileName = file.getOriginalFilename();
        //文件大小
        Long fileSize  = file.getSize()/1024;
        String uploadFileName = fileName.substring(0, fileName.lastIndexOf("."));
        //文件后缀,判断上传文件格式
        String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        if (fileList.size() <= 0){
            map.put("msg","上传失败，事务报告已全部上传完或暂无报告需要上传！");
            map.put("code",-4);
        }else {
            if (fileSize <= 3072){
                //判断文件类型
                if (judgeFileType(subffix)){
                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                    if (isMultipart){
                        for (int i=0;i<fileList.size();i++){
                            if (uploadFileName.equals(fileList.get(i))){
                                //存放文件的文件夹
                                String fileDir = "";
                                if (stepCount == 2){
                                    fileDir = "more_feedback";
                                } else if (stepCount == 3){
                                    fileDir = "more_testReport";
                                } else if (stepCount == 5){
                                    fileDir = "more_reviseFeedback";
                                }
                                //获取项目路径到webapp
                                String filepath = request.getSession().getServletContext().getRealPath("/")+fileDir;
                                File newFile=new File(filepath);
                                //目录不存在就创建
                                if(!newFile.exists()){
                                    newFile.mkdirs();
                                }
                                try {
                                    file.transferTo(new File(newFile+"\\"+fileName));
                                    String url = "/" + fileDir + "/" + fileName;
                                    realpath = newFile+"\\"+fileName;
                                    updateFilesUrl(stepCount,url,uploadFileName,supIndex);
                                    overRunLogList(supIndex, stepCount);
                                    map.put("msg","文件上传成功！");
                                    map.put("code",0);
                                    if (overRunLogList(supIndex,stepCount)){
                                        int type = supIndexType(supIndex);
                                        updateFileProgress(supIndex, stepCount, type, socketSender);
                                    }
                                } catch (IOException e) {
                                    logger.error(e.getMessage());
                                }
                                break;
                            } else {
                                map.put("msg","上传文件名与规定文件名称不一致,文件上传失败！");
                                map.put("code",-1);
                            }
                        }
                    } else {
                        map.put("msg","上传错误！");
                        map.put("code",-3);
                    }
                } else {
                    map.put("msg","文件类型错误！");
                    map.put("code",-2);
                }
            }else {
                map.put("msg","文件过大，上传失败！");
                map.put("code",-5);
            }
        }
        return map;
    }

    @Override
    public void updateFilesUrl(Integer stepCount, String filePath, String fileName,  String supIndex) {
        if (stepCount == 2){
            uploadFilesMapper.updateFilesFeedbackUrl(filePath,fileName,supIndex);
        } else if (stepCount == 3){
            uploadFilesMapper.updateFilesTestReportUrl(filePath,fileName,supIndex);
        } else if (stepCount == 5){
            uploadFilesMapper.updateFilesReviseFeedbackUrl(filePath,fileName,supIndex);
        }
    }

    @Override
    public Integer supIndexType(String supIndex) {
        return uploadFilesMapper.getSuperviseType(supIndex);
    }

    /**
     * 时间戳转换工具
     */
    public Date timeStampDate(String time) {
        Long timeLong = Long.parseLong(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date date;
        try {
            return sdf.parse(sdf.format(timeLong));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }


    /**
     * 修改主表中流程状态
     * @param supIndex
     */
    @Override
    public void updateFileProgress(String supIndex, Integer stepCount, Integer type, SocketSender socketSender) {
        if (type == 0){
            if (stepCount == 2){
                socketSender.sendSocketMsg(supIndex+"预警单已全部上传，更新事务流程状态！");
                int progress = 6;
                uploadFilesMapper.updateProgress(supIndex,progress);
            }else {
                int progress = stepCount+1;
                uploadFilesMapper.updateProgress(supIndex,progress);
            }
        } else {
            if (stepCount == 2){
                socketSender.sendSocketMsg(supIndex+"告警单已全部上传，更新事务流程状态！");
                int progress = stepCount+1;
                uploadFilesMapper.updateProgress(supIndex,progress);
            } else if (stepCount == 3){
                socketSender.sendSocketMsg(supIndex+"现场测试单已全部上传，更新事务流程状态！");
                int progress = stepCount+1;
                uploadFilesMapper.updateProgress(supIndex,progress);
            }  else if (stepCount == 5){
                socketSender.sendSocketMsg(supIndex+"整改反馈单已全部上传，更新事务流程状态！");
                int progress = stepCount+1;
                uploadFilesMapper.updateProgress(supIndex,progress);
            } else {
                int progress = stepCount+1;
                uploadFilesMapper.updateProgress(supIndex,progress);
            }
        }
    }

    @Override
    public Boolean overRunLogList(String supIndex, Integer stepCount) {
        boolean result = true;
        List<OverRunLog> list = uploadFilesMapper.getOverRunLog(supIndex);
        if (stepCount == 2){
            for (int i=0; i<list.size(); i++){
                if (list.get(i).getFeedBack() == null){
                    result = false;
                    break;
                }
            }
        } else if (stepCount == 3){
            for (int i=0; i<list.size(); i++){
                if (list.get(i).getTestReport() == null){
                    result = false;
                    break;
                }
            }
        } else if (stepCount == 5){
            for (int i=0; i<list.size(); i++){
                if (list.get(i).getReviseFeedBack() == null){
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

}
