package cn.com.capcloud.api.action;

import cn.com.capcloud.api.action.service.*;
import cn.com.capcloud.api.action.service.util.FileUtil;
import cn.com.capcloud.api.action.service.util.ResponseUtil;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.ccui.core.common.utils.StringUtil;
import cn.com.capcloud.core.util.ReadProperty;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

@Component
public class ApiFileAction {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ApiFileAction.class);
    @Autowired
    private ReadProperty readProperty;
    @Autowired
    private ApiService apiService;
    @Autowired
    private FileService fileService;
    @Autowired
    private LogService logService;

    private String successResponse(Object data) {
        JackJSONObject retJson = JackJSONObject.fromObject(apiService.getReturnDataByCode("ok"));
        retJson.put("data", data);
        return JackJSON.toJSONString(retJson);
    }

    private String failResponse(JackJSONObject retJson) {
        return JackJSON.toJSONString(retJson);
    }

    public String upload(HttpServletRequest request){
        JackJSONObject retJson=new JackJSONObject();
        Map<String,Object> returnMap;
        String uploadFileToType=request.getParameter("upload_file_to_type");
        if(StringUtil.isEmpty(uploadFileToType)){
            uploadFileToType=readProperty.getDefaultUploadFileToType();

        }
        if(uploadFileToType.equals("minio")){
            returnMap=fileService.uploadToMinio(retJson,request);
        }else{
            returnMap=fileService.uploadToService(retJson,request);
        }
        if(returnMap.size()==0){
            return failResponse(retJson);
        }
        logService.fileLogSave(returnMap,request);
        return successResponse(returnMap);
    }

    public void downFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileDiskName = request.getParameter("fileDiskName");
        String realFileName = request.getParameter("realFileName");
        String suffix = request.getParameter("suffix");
        if (StringUtil.isNotEmpty(suffix)) {
            suffix = suffix.substring(1);
        }
        String fileDir = readProperty.getUploadFilePath();
        if (FileUtil.isInvalidPath(fileDiskName)) {
            throw new Exception("非法文件路径，禁止下载！");
        }
        File file = new File(fileDir + fileDiskName);
        if (!file.exists()) {
            throw new Exception("文件不存在：" + realFileName);
        }
        FileInputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        inputStream.read(data);
        inputStream.close();
        ResponseUtil.setContentType(response, suffix);
        String downloadFileName = request.getParameter("downFileName");
        if (downloadFileName == null || downloadFileName.length() == 0) {
            downloadFileName = realFileName;
        }
        response.addHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(downloadFileName, "utf-8"));
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
    }


}

