package com.uas.eis.controller;

import com.uas.eis.utils.FileUtil;
import com.uas.eis.sdk.entity.ApiResult;
import com.uas.eis.sdk.resp.ApiResponse;
import com.uas.eis.service.MESHelperService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaost
 * @date 2022/8/16 11:35
 **/
@RestController
@RequestMapping("/MES/helper")
public class MESHelperController {
    @Autowired
    private MESHelperService mesHelperService;

    @RequestMapping(value="/dllMain")
    public ApiResult<Map<Object,Object>> DLLMain(HttpServletRequest request, String data){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        String accessKey = request.getHeader("AccessKey");
        String requestId = request.getHeader("RequestId");
        Map<Object,Object> map = mesHelperService.DLLMain(accessKey,requestId,data);
        return ApiResponse.successRsp(requestId,map);
    }

    /**
     * 附件下载
    */
    @RequestMapping("/downloadbyId.action")
    public void downloadById(HttpServletResponse response, HttpServletRequest request) throws IOException, KeyManagementException, NoSuchAlgorithmException {
        String id = request.getParameter("id");
        String accessKey = request.getHeader("AccessKey");
        String requestId = request.getHeader("RequestId");
        JSONObject obj = mesHelperService.getFiles(accessKey,requestId,id).getJSONObject(0);
        String path = obj.getString("fp_path");
        String size = "0";
        InputStream in = null;
        File file = new File(path);
        in = new FileInputStream(file);
        size = String.valueOf(file.length());
        OutputStream os = response.getOutputStream();
        String fileName = obj.getString("fp_name");
        response.addHeader("Content-Disposition", "attachment;filename=\""
                + new String(fileName.getBytes("utf-8"), "iso-8859-1")+"\"");
        response.addHeader("Content-Length", size);
        response.setCharacterEncoding("utf-8");
        response.setContentType(FileUtil.getContentType(fileName));
        int data = 0;
        while ((data = in.read()) != -1) {
            os.write(data);
        }
        in.close();
        os.close();
    }
}
