package com.malk.ruisi.controller;


import com.malk.ruisi.service.RsQysService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.common.McR;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/qys")
public class QysHuiDaoController {
    @Autowired
    private RsQysService qysService;
    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDConf ddConf;

    /***
     * 第三步
     * 契约锁签署完成回调、保存文件
     * @return
     */
    @PostMapping("/callback")
    public McR callback(@RequestParam Map<String, String> param) throws Exception {
        log.info("callback:{}", param);
//
        //1.content解析为json字符   并获得contractId
        //2.根据contractId 获取附件到本地获得一个本地地址  接口：/contract/download zip保存到本地   并解压zip

        //3.根据contractId查询对应的数据实例ID，根据实例ID把本地地址对的文件传到对应的 附件签署后

        //("attachmentField_ltsbweit",文件)
        return qysService.callback(param);
    }


    private static final String FILE_DIRECTORY = "C:\\Users\\Administrator\\Desktop\\";

    @GetMapping("/download/{sn}/{fileName}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName,@PathVariable String sn) {
        Path filePath = Paths.get(FILE_DIRECTORY.concat(sn.concat("\\"))).resolve(fileName).normalize();
        try {
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentType(MediaType.parseMediaType("application/octet-stream"))
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.notFound().build();
        } catch (IOException e) {
            return ResponseEntity.notFound().build();
        }
    }
}



