package com.nmgs.controller;

import com.nmgs.config.ResultData;
import com.nmgs.service.impl.IntegralAppServiceImpl;
import com.nmgs.util.LogUtil;
import com.nmgs.util.PubTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 小程序版本说明
 *
 */
@Controller
@Api(tags="APP获取")
public class IntegralAppController {
    public IntegralAppServiceImpl integralAppServiceImpl;
    @Autowired
    public void setIntegralAppServiceImpl(IntegralAppServiceImpl integralAppServiceImplT) {
        this.integralAppServiceImpl = integralAppServiceImplT;
    }

    /**
     * 查询APP更新信息
     * @return
     */
    @RequestMapping(value = "getIntegralAppList",
            method = {RequestMethod.POST}
    )
    @ApiOperation(value="查询APP更新信息",httpMethod = "POST")
    @ResponseBody
    public ResultData<List> getIntegralAppList(){
        List userVehicleByUserId = this.integralAppServiceImpl.getIntegraAppList();
        if(userVehicleByUserId != null){
            return ResultData.success("查询成功",userVehicleByUserId,userVehicleByUserId.size());
        }else{
            return ResultData.fail("接口查询出错");
        }
    }
    //实现Spring Boot 的文件下载功能，映射网址为/download
    @ApiOperation(value = "APP下载",httpMethod = "GET",ignoreJsonView = false )
    @ApiImplicitParams(
            @ApiImplicitParam(value = "fileName",defaultValue = "gasstation")
    )
    @RequestMapping(value = "/download", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = request.getParameter("fileName");
        if(PubTools.isNull(fileName)){
            fileName="gasstation";
        }
        fileName =fileName+".apk";
        String fileP=com.nmgs.util.PathUtil.webappsPath+"//"+ fileName;
        LogUtil.WriteLog_Info("APP下载地址====="+fileP,"FileDownload");
        File file = new File(fileP);
        //System.out.println(com.trkf.downloadupdata.util.PathUtil.webappsPath+"//"+PropertiesUtil.getValue("Downfilepth"));

        // 如果文件名存在，则进行下载
        if (file.exists()) {

            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.addHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            // 实现文件下载
            byte[] buffer = new byte[1024*1024*100];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

                System.out.println("Download the song successfully!");
                return "下载成功!";
            }
            catch (Exception e) {
                System.out.println("Download the song failed!");
                return "下载失败!";
            }
            finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //return "Download the song successfully!";
            }
        }else{
            return file.getPath()+"文件不存在！";
        }
    }
}
