package cn.com.tenlion.freemarker.controller.app.apis.templaterecord;

import cn.com.tenlion.freemarker.pojo.dtos.templaterecord.TemplateRecordDTO;
import cn.com.tenlion.freemarker.service.templaterecord.ITemplateRecordService;
import ink.wgink.common.base.DefaultBaseController;
import ink.wgink.common.component.SecurityComponent;
import ink.wgink.exceptions.SearchException;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.pojo.result.ErrorResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/**
 * @ClassName: TemplateRecordController
 * @Description: 模板构建记录
 * @Author: WenG
 * @Date: 2020-05-07 16:50
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "模板构建记录接口")
@RestController
@RequestMapping(ISystemConstant.APP_PREFIX + "/templaterecord")
public class TemplateRecordAppController extends DefaultBaseController {

    @Autowired
    private ITemplateRecordService templateRecordService;
    @Autowired
    private SecurityComponent securityComponent;

    @ApiOperation(value = "模板构建文件获取", notes = "模板构建文件获取")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "templateFileType", value = "文件类型", paramType = "path"),
            @ApiImplicitParam(name = "templateRecordId", value = "记录ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping(value = "get/{templateFileType}/{templateRecordId}")
    public void getById(@PathVariable("templateFileType") String templateFileType, @PathVariable("templateRecordId") String templateRecordId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 返回文件
        TemplateRecordDTO dto = templateRecordService.getTemplateRecordById(templateRecordId);
        File file = new File(dto.getTemplateRecordPath());
        String fileName = file.getName();
        String userAgent = request.getHeader("User-Agent").toUpperCase();
        if (userAgent.indexOf("MSIE") > 0 || userAgent.indexOf("Trident") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        byte[] data = toByteArray(file);
        response.reset();
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
        response.addHeader("Content-Length", "" + data.length);
        if ("html".equals(templateFileType)) {
            response.setContentType("text/html;charset=UTF-8");
        }else{
            response.setContentType("application/octet-stream;charset=UTF-8");
        }
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    @ApiOperation(value = "模板构建Html页面", notes = "模板构建Html页面接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "templateRecordId", value = "记录ID", paramType = "path"),
        @ApiImplicitParam(name = "token", value = "token", paramType = "header")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping(value = "get/html/{templateRecordId}", produces = "text/html")
    public String getHtmlById(@RequestHeader("token") String token, @PathVariable("templateRecordId") String templateRecordId) throws Exception {
        TemplateRecordDTO dto = templateRecordService.getTemplateRecordById(templateRecordId);
        File file = new File(dto.getTemplateRecordPath());
        StringBuilder logContent = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = reader.readLine()) != null) {
                logContent.append(line).append("\r\n");
            }
        } catch (IOException x) {
            x.printStackTrace();
        }
        return logContent.toString().replaceAll("getAppToken\\(\\)","\"" + token + "\"");
    }

    /**
     * 读取到字节数组
     * @param f 文件对象
     * @return
     * @throws IOException
     */
    private byte[] toByteArray(File f) throws IOException {
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
            }
            return byteBuffer.array();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation(value = "模板构建记录详情(通过ID)", notes = "模板构建记录详情(通过ID)接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "templateRecordId", value = "模板构建记录ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("gettemplaterecordbyid/{templateRecordId}")
    public TemplateRecordDTO getTemplateRecordById(@PathVariable("templateRecordId") String templateRecordId) throws SearchException {
        return templateRecordService.getTemplateRecordById(templateRecordId);
    }

}