package com.casic.missiles.modular.system.controller;

import com.casic.missiles.modular.system.dto.VersionDto;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.base.response.ResponseData;
import com.casic.missiles.core.common.factory.CommonPermissionFactory;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.config.DeviceServerProperties;
import com.casic.missiles.modular.system.constant.DeviceConst;
import com.casic.missiles.modular.system.service.IDeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * 控制器
 *
 * @author dev123
 * @Date 2018-11-19 13:15:14
 */
@RestController
public class TemplateController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(TemplateController.class);
    @Autowired
    private DeviceServerProperties gunsProperties;
    @Autowired
    private IDeviceService service;

    /**
     * 文件模板下载 （待优化）
     */
    @GetMapping("/template/download")
    public void doPost(@RequestParam("filename") String filename, HttpServletResponse response)
            throws ServletException, IOException {
        String path = gunsProperties.getConfigPath();
        logger.info(path);
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        File file = new File(path, filename);
        // 获取文件名
        String fileName = null;
        if (filename.contains("/")) {
            fileName = filename.substring(filename.lastIndexOf("/") + 1);
        } else {
            fileName = filename;
        }

        // 设置以流的形式下载文件，这样可以实现任意格式的文件下载
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", " attachment;filename=" + fileName);
        response.setContentLength((int) file.length());

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int readTmp = 0;
            while ((readTmp = fis.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, readTmp);
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
        } finally {
            response.getOutputStream().flush();
            response.getOutputStream().close();
            fis.close();
        }
    }

    @PostMapping("/app/checkVersion")
    public ResponseData checkVersion(String nowVersion) {
        String path = gunsProperties.getDownloadPath();
        File file = new File(path.concat(DeviceConst.APP_DOWNLOAD));
        if (file.isDirectory()) {
            String[] filelist = file.list();
            if (ToolUtil.isNotEmpty(filelist)) {
                Arrays.sort(filelist);
                String apkName = filelist[filelist.length - 1];
                String version = apkName.replaceAll(".apk", "");
                VersionDto versionDto = new VersionDto();
                versionDto.setVersion(version);
                versionDto.setDownloadUrl(DeviceConst.APP_DOWNLOAD.concat(apkName));
                return ResponseData.success(versionDto);
            }
        }
        return ResponseData.error("暂无APK版本");
    }

    @PostMapping("/app/registerGeTui")
    public ResponseData geTuiRegister(@RequestParam String clientid) {

        service.registerGeTui(CommonPermissionFactory.me().getCurrLoginUser().getId(), clientid);
        return ResponseData.success();
    }
}
