package com.zjty.autotest.service.impl;

import com.zjty.autotest.pojo.sjq.FileBean;
import com.zjty.autotest.pojo.sjq.common.AppHttpCodeEnum;
import com.zjty.autotest.pojo.sjq.common.ResponseResult;
import com.zjty.autotest.service.UploadCodeService;
import com.zjty.autotest.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class UploadCodeServiceImpl implements UploadCodeService {
    @Value("${uploadUnFile}")
    private String uploadUnFile;
    @Autowired
    private IdWorker idWorker;

    @Override
    public ResponseResult uploadCodeFile(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.File_Empty);
            }
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            File dest = new File(uploadUnFile +"/"+idWorker.nextId()+"/"+fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            FileBean bean=new FileBean(dest.getAbsolutePath(),fileType);
            return ResponseResult.okResult(bean);
        } catch (IOException e) {
            e.printStackTrace();

        }

        return ResponseResult.errorResult(AppHttpCodeEnum.File_UPLOAD_ERROR);
    }
}
