package com.huatek.busi.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huatek.busi.dto.SimulateResultDto;
import com.huatek.busi.entity.SimulateResult;
import com.huatek.busi.where.SimulateResultSelectVo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.constant.ApiConstant.Tags;
import com.huatek.busi.dto.DataOutputEntityDto;
import com.huatek.busi.entity.DataOutputEntity;
import com.huatek.busi.service.dataoutput.DataOutputEntityService;
import com.huatek.busi.vo.dataoutput.DataOutputEntityVo;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据输出记录 控制层
 *
 * @author anker_cheng
 * @date Oct 12, 2019 9:57:46 AM
 */
@Slf4j
@Api(tags = {Tags.DATA_OUTPUT})
@RestController
@RequestMapping("/api/DataOutputEntity")
public class DataOutputEntityController {

    @Reference(check = false)
    private DataOutputEntityService dataOutputEntityService;

    @ApiOperation(value = "分页查询", response = DataOutputEntityVo.class)
    @PostMapping(value = "/queryList")
    public Map<String, Object> queryList(@RequestBody DataOutputEntityDto dataOutputEntityDto) {
        PageInfo<DataOutputEntityVo> pageInfo = dataOutputEntityService.findDataOutputEntityPage(dataOutputEntityDto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "", pageInfo.getList());
    }

    @ApiOperation(value = "文件仿真下载")
    @ApiImplicitParam(name = "id", value = "记录ID")
    @GetMapping("/downloadReal")
    public void downloadReal(HttpServletResponse response, HttpServletRequest request,
                             @RequestParam(value = "id") String mainId ) {
        SimulateResultDto vo = dataOutputEntityService.getSimulateResultDto(mainId);
        if (vo == null) {
            throw new OwlException("记录不存在！");
        }
        String basePath = dataOutputEntityService.getBasePath();
        Path path = Paths.get(basePath, vo.getFilePath(), vo.getFileName());
        if (!Files.exists(path)) {
            throw new OwlException("文件不存在！");
        }
        ServletOutputStream outputStream = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        InputStream in = null;
        try {
            // 文件名转码
            String optFileName =  vo.getFileName().substring(vo.getFileName().indexOf("."));
            String filename = new String(optFileName.getBytes(), "iso-8859-1");
            // 设置response信息
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "application/msexcel");
            response.setHeader("Content-disposition", "attachment; filename=" + filename);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            // 输出
            in = new FileInputStream(path.toFile());
            outputStream = response.getOutputStream();
            bis = new BufferedInputStream(in);
            bos = new BufferedOutputStream(outputStream);
            byte[] buff = new byte[8192];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            outputStream.flush();

        } catch (Exception e) {
            log.error("下载文件出错", e);
            throw new OwlException("下载文件出错！");
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(in);
        }
    }


    @ApiOperation(value = "文件下载")
    @ApiImplicitParam(name = "id", value = "记录ID")
    @GetMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request,
                         @RequestParam(value = "id") String id) {
        DataOutputEntityVo vo = dataOutputEntityService.getDataOutputEntityVo(id);
        if (vo == null) {
            throw new OwlException("记录不存在！");
        }
        String basePath = dataOutputEntityService.getBasePath();
        Path path = Paths.get(basePath, vo.getFilePath(), vo.getFileName());
        if (!Files.exists(path)) {
            throw new OwlException("文件不存在！");
        }
        ServletOutputStream outputStream = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        InputStream in = null;
        try {
            // 文件名转码
            String optFileName = vo.getDataDesc() + vo.getFileName().substring(vo.getFileName().indexOf("."));
            String filename = new String(optFileName.getBytes(), "iso-8859-1");
            // 设置response信息
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "application/msexcel");
            response.setHeader("Content-disposition", "attachment; filename=" + filename);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            // 输出
            in = new FileInputStream(path.toFile());
            outputStream = response.getOutputStream();
            bis = new BufferedInputStream(in);
            bos = new BufferedOutputStream(outputStream);
            byte[] buff = new byte[8192];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            outputStream.flush();
            //更新下载次数
            DataOutputEntity entity = new DataOutputEntity();
            entity.setId(vo.getId());
            entity.setDownloadTimes((vo.getDownloadTimes() == null ? 0 : vo.getDownloadTimes()) + 1);
            dataOutputEntityService.saveOrUpdate(entity);
        } catch (Exception e) {
            log.error("下载文件出错", e);
            throw new OwlException("下载文件出错！");
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(in);
        }
    }
}
