package cn.wisenergy.service.app.impl;

import cn.wisenergy.common.utils.*;

import cn.wisenergy.mapper.UsersMapper;
import cn.wisenergy.model.app.zxUserDto;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import cn.wisenergy.service.app.UploadService;
import java.io.File;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import cn.wisenergy.mapper.ShopZxMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by m1991 on 2021/2/24 13:42
 */
@Slf4j
@Transactional
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private ShopZxMapper shopZxMapper;

    @Autowired
    private UsersMapper usersMapper;

   // @Value("${file.upload.path:#{null}}")
    private String path;

    /**
     * 视频文件上传
     */
    @Override
    public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request,String zxField,String zxAddress,String inviteCode) throws Exception {
        Map<String, Object> resultMap=new HashMap<String, Object>();
        /**
         * http://路径  request.getScheme() + "://" + request.getServerName()
         *                 + ":" + request.getServerPort()+/upload/";"
         */
        String basePath ="/upload/";
        Long time = new Date().getTime();

        String fileName = file.getOriginalFilename();//文件原始名称
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//从最后一个.开始截取。截取fileName的后缀名
        String newFileName = time+suffixName; //文件新名称
        //设置文件存储路径，可以存放在你想要指定的路径里面
        String rootPath="/opt/upload/video/"; //上传视频存放位置

        String filePath = rootPath+newFileName;
        File newFile = new File(filePath);
        //判断目标文件所在目录是否存在
        if(!newFile.getParentFile().exists()){
            //如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }

        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //视频上传保存url
        String videoUrl = basePath + newFileName;

        //视频封面图处理
        String newImgName = time+".jpg";
        String framefile = rootPath + newImgName;
        String imgUrlSave = basePath+newImgName;//图片最终位置路径
        //视频截取封面图
        String imgUrl=FrameGrabberKit.getVedioImg(videoUrl, framefile, imgUrlSave);

        resultMap.put("videoUrl", videoUrl);
        resultMap.put("imgUrl", imgUrl);
        resultMap.put("returnCode", 0);
        String zxUrl=videoUrl;
        //System.out.println("上传的文件名为："+fileName+",后缀名为："+newFileName);
        /**
         * 生成当前时间戳
         */
        Long zxDate= System.currentTimeMillis();
        shopZxMapper.zxadd(zxUrl,zxField,zxAddress,inviteCode, zxDate);
        return resultMap;
    }

        /**
         * 图片文件上传
         */
        @Override
        public Map<String, Object> uploadImage(MultipartFile file, HttpServletRequest request,String zxField, String zxAddress,String inviteCode) throws Exception {
            Map<String, Object> resultMap=new HashMap<String, Object>();

            /**
             * 生成当前时间戳
             */
            Long zxDate= Long.valueOf(System.currentTimeMillis());

//            request.getScheme() + "://" + request.getServerName()
//                    + ":" + request.getServerPort()+"/upload/";
            String basePath = "/upload/";


            Long time = System.currentTimeMillis();

            String zxName = file.getOriginalFilename();//文件原始名称
            String suffixName = zxName.substring(zxName.lastIndexOf("."));//从最后一个.开始截取。截取zxName的后缀名
            String newzxName = time+suffixName; //文件新名称
            //设置文件存储路径，可以存放在你想要指定的路径里面
            String rootPath="/opt/upload/video/"; //上传图片存放位置
            String filePath = rootPath+newzxName;
            File newFile = new File(filePath);
            //判断目标文件所在目录是否存在
            if(!newFile.getParentFile().exists()){
                //如果目标文件所在的目录不存在，则创建父目录
                newFile.getParentFile().mkdirs();
            }

            //将内存中的数据写入磁盘
            file.transferTo(newFile);
            //图片上传保存url
            String zxUrl = basePath + newzxName;

            resultMap.put("zxUrl", zxUrl);
            resultMap.put("returnCode", 0);
            shopZxMapper.zxadd(zxUrl,zxField,zxAddress,inviteCode, zxDate);
            return resultMap;
        }

    /**
     * 多图片
     * @param files
     * @param zxField
     * @param zxAddress
     * @param inviteCode
     * @return
     */
    @Override
    public List imageUpload(MultipartFile[] files, String zxField, String zxAddress,String inviteCode) {
        //获取上传图片数量，打印在控制台
        System.out.println("上传图片数量" + files.length);
        String zxUrl = new String();
        //创建集合
        List<Map<String, Object>> root = new ArrayList<Map<String, Object>>();
        String fileName1=null;
        // 要上传的目标文件存放的绝对路径
//        final String localPath = path;
        Long time = new Date().getTime();
        String localPath = "/upload/";
        Map<String, Object> result = new HashMap<String, Object>();//一个文件上传的结果
        String result_msg = "";//上传结果信息
        //遍历图片数据
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                System.out.println("上传图片为空，请重新上传");
            }

            //判断上传文件格式
            String fileType = file.getContentType();
            if (fileType.equals("image/jpeg") || fileType.equals("image/png")) {

                //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                //获取文件名
                fileName1 = file.getOriginalFilename();
                //获取文件后缀名
                String suffixName = fileName1.substring(fileName1.lastIndexOf("."));
                //重新生成文件名
                String fileName ="1"+UUID.randomUUID()+suffixName;//文件新名称
                //设置文件存储路径，可以存放在你想要指定的路径里面
                String Path="/opt/upload/video/"; //上传图片存放位置
                zxUrl+=localPath+fileName+",";

                if (FileUtils.upload(file,Path, fileName)) {
                    //文件存放的相对路径(一般存放在数据库用于img标签的src)
                    String relativePath ="用于判断是否图片上传成功，返回值有："+fileName;
                    result.put("relativePath", relativePath);//前端根据是否存在该字段来判断上传是否成功
                    result_msg = "图片上传成功";
                    result.put("zxUrl", zxUrl);

                } else {
                    result_msg = "图片上传失败";
                }
            } else {
                result_msg = "图片格式不正确";
            }

        }
        result.put("result_msg", result_msg);
        root.add(result);
        String root_json = JSON.toJSONString(root);
        System.out.println(root_json);
        result.put("returnCode", 0);
        /**
         * 生成当前时间戳
         */
        Long zxDate= Long.valueOf(System.currentTimeMillis());
        shopZxMapper.zxadd(zxUrl,zxField,zxAddress,inviteCode, zxDate);
        return root;
    }

    /**
     * 多文件上传 TODO
     */
    private Path fileStorageLocation; // 文件在本地存储的地址

    public UploadServiceImpl() {
        if (!StringUtil.isBlank(path)) {
            this.fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
            try {
                Files.createDirectories(this.fileStorageLocation);
            } catch (IOException e) {
                throw new FileException("Could not create the directory", e);
            }
        }
    }

    /**
     * 存储文件到系统
     * @param file 文件
     * @return 文件名
     */
    @Override
    public String storeFile(MultipartFile file) {
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            // Check if the file's name contains invalid characters
            if(fileName.contains("..")) {
                throw new FileException("Sorry! Filename contains invalid path sequence " + fileName);
            }

            // Copy file to the target location (Replacing existing file with the same name)
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return fileName;
        } catch (IOException ex) {
            throw new FileException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

    @Override
    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new FileException("File not found " + fileName);
            }
        } catch (MalformedURLException  ex) {
            throw new FileException("File not found " + fileName, ex);
        }
    }

    /**
     *  资讯文件展示
     */
    @Override
    public Map selectPage(Integer pageNum, Integer pageSize) {
        Map map = new HashMap();
        pageNum=pageNum-1;
        List<zxUserDto> shopZxList = shopZxMapper.selectPage(pageNum,pageSize);
        for (zxUserDto shopZx : shopZxList) {
            String zxUrl = shopZx.getZxUrl();
            ;
            shopZx.setUserId(shopZx.getUserId().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
            String[] split = StringUtils.split(zxUrl, ",");
            if (null != split){
                List<String> strings = Arrays.asList(split);
                shopZx.setAskImgList(strings);
            }
        }
        map.put("data",shopZxList);

        return map;
    }
}
