package cn.datax.service.data.metadata.controller;

import cn.datax.common.core.R;
import cn.datax.service.data.metadata.service.DataMetadataService;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

@Api(tags = {"元数据"})
@RestController
@RequestMapping("/databases")
public class DataMetadataController {

    @Autowired
    private DataMetadataService dataMetadataService;

    @ApiOperation(value = "同步", notes = "根据url的id来指定同步对象")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @PostMapping("/sync/{id}")
    public R syncMetadata(@PathVariable String id) {
        dataMetadataService.syncMetadata(id);
        return R.ok();
    }

    @ApiOperation(value = "数据库设计文档", notes = "根据url的id来指定生成数据库设计文档对象")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @PostMapping("/word/{id}")
    public void wordMetadata(@PathVariable String id, HttpServletResponse response) throws Exception {
        // 清空response
        response.reset();
        // 设置response的Header
        response.setContentType("application/octet-stream;charset=utf-8");
        // 设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.addHeader("Content-Disposition", "attachment;filename=" + new String("数据库设计文档.doc".getBytes()));
        Document doc = dataMetadataService.wordMetadata(id);
        OutputStream out = response.getOutputStream();
        doc.save(out, SaveOptions.createSaveOptions(SaveFormat.DOC));
        out.flush();
        out.close();
    }
}
