/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.entity.App;
import com.tofly.base.entity.User;
import com.tofly.base.service.AppService;
import com.tofly.base.service.UserService;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tofly.base.mapper.AppMapper;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * ${comments}
 *
 * @author fcl
 * @date Wed Mar 10 00:00:00 CST 2021
 */
@Service("appService")
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements AppService {

    @Value("${user.avatar}")
    private String avatarPath;
    @Autowired
    private AppService appService;
    @Autowired
    private UserService userService;
    @Override
    public ResultRespone upLoadApp(MultipartFile appFile, MultipartFile txtFile,String type) throws Exception {

        if (!(appFile != null&& txtFile != null)) {
            return ResultRespone.failed("上传文件不能为空");
        }
        long size = appFile.getSize();
        File toFile =  multipartFileToFile(txtFile);

        String result = "";
        try{
            BufferedReader br = new BufferedReader(new FileReader(toFile));//构造一个BufferedReader类来读取文件
             String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result = result + "\n" +s;
            }
            br.close();
            }catch(Exception e){
                    e.printStackTrace();
            }
                String fileName = appFile.getOriginalFilename();

        String sb = fileName.substring(fileName.lastIndexOf("-")+1,fileName.lastIndexOf("."));
        // 判断当前上传App版本是否为数字
        boolean numeric = this.isNumeric(sb);
        if(numeric){
            // 判断当前上传版本号与最新对应类型上传的版本号是否大于,若小于等于不允许上传
            List<App> collect = new ArrayList<>(this.list(new QueryWrapper<App>().lambda().eq(App::getAppType, type).orderByDesc(App::getCreateTime)));
            boolean flag = true;
            if(collect.size()>0){
                App app1 = collect.get(0);
                double integer = Double.parseDouble(app1.getVersionsub());
                double integer1 = Double.parseDouble(sb);
                if(integer1<=integer){
                    flag = false;
                }
            }

            if(flag){
                String filePath =avatarPath + IdWorker.getIdStr() + appFile.getOriginalFilename().substring(appFile.getOriginalFilename().lastIndexOf("."));
                boolean b = FtpUtil.uploadFile2Ftp(appFile, filePath);
                App app = new App();
                if (b){ app.setAppSize(getStorageSpaceM(size));
                    app.setVersion(sb);
                    app.setCreateTime(new Date());
                    app.setFilename(fileName);
                    app.setVersionsub(sb);
                    app.setAppPath(filePath);
                    app.setCreateUser(SecurityUtils.getUserId());
                    app.setOthername(fileName);
                    app.setVersionstate(result);
                    app.setCreateUserName(SecurityUtils.getUserName());
                    app.setAppType(type);
                }
                appService.save(app);
            }else {
               return ResultRespone.failed("上传版本号小于已上传版本:"+sb);
            }



        }else {
           return ResultRespone.failed("上传APP版本,版本号不符合规范: "+sb);
        }
        return ResultRespone.success();


    }

    @Override
    public Page<Map> listAppPage(Page page, Map map) {
        return page.setRecords(baseMapper.listAppPage(page,map));
    }

    @Override
    public String selectOldApp(String type) {
        App app = baseMapper.selectOldApp(type);
        String appName = app.getFilename();
        String ordVersion = appName.substring(appName.indexOf("-")+1,appName.lastIndexOf("-"));
        return ordVersion;
    }

    @Override
    public Object appDownlod(String type) {
        App app = baseMapper.selectOldApp(type);
        String path = app.getAppPath();
        return path;
    }

    @Override
    public ResultRespone getNewVersionInformation(String type, String userId, String nowVersion) {
        User user = new User();
        if(StringUtils.isNotBlank(nowVersion)){
            user.setNowVersion(nowVersion);
        }
        if(StringUtils.isNotBlank(userId)){
            user.setId(Long.parseLong(userId.trim()));
            user.setLastAppUpdateTime(new Date());
            userService.updateById(user);
        }

        App app = baseMapper.selectOldApp(type);
        return ResultRespone.success(app);
    }

    public static String getStorageSpaceM(long size){
        String G = size/1024/1024/1024+"G";
        String M = size/1024/1024+"M";
        String KB = size/1024+"KB";
        if (size/1024/1024/1024>=1){
            return G;
        }else if (size/1024/1024>=1){
            return M;
        }else if (size/1024>=1){
            return KB;
        }else {
            return (size+"Byte");
        }
    }


    public File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private  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();
        }
    }

    /**
     * 判断当前字符串是否为数字
     * @param str
     * @return
     */
    public boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }

        return str.matches("[+-]?[0-9]+(\\.[0-9]{1,4})?");
    }
}
