package com.yeejoin.amos.fas.business.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yeejoin.amos.fas.business.service.intfc.IPlanVisual3dService;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.dao.entity.TextPlan;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/api/visual")
@Api(tags = "预案可视化API")
public class PlanVisual3dController extends AbstractBaseController {

    private final Logger log = LoggerFactory.getLogger(PlanVisual3dController.class);

    // 上传路径
    @Value("${file.uploadUrl}")
    private String fileUploadDir;

    @Autowired
    private IPlanVisual3dService planVisual3dService;

    @Autowired
    HttpServletResponse response;
    @Autowired
    HttpServletRequest request;

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "预案应用树", notes = "预案应用树")
    @GetMapping(value = "/plan/tree")
    public CommonResponse getPlanTree() {
        return CommonResponseUtil.success(planVisual3dService.getPlanTree());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据ID获取文字预案", notes = "根据ID获取文字预案")
    @GetMapping(value = "/plan/text/{id}")
    public CommonResponse getTextPlanById(@PathVariable(value = "id") Long id) {
        return CommonResponseUtil.success(planVisual3dService.getTextPlanInfoById(id));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @RequestMapping(value = "/plan/text/downloadFile/{id}", method = RequestMethod.GET)
    public HttpServletResponse download(@PathVariable("id") Long id) {
        TextPlan testPlan = planVisual3dService.getTextPlanInfoById(id);
        if (testPlan != null) {
            String path = testPlan.getFilePath();
            if (path != null && !"".equals(path)) {
                try {
                    // path是指欲下载的文件的路径。
                    File file = new File(fileUploadDir + path);
                    if (file.exists()) {
                        // 取得文件名。
                        String filename = file.getName();
                        // 取得文件的后缀名。
                        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

                        // 以流的形式下载文件。
                        InputStream fis = new BufferedInputStream(new FileInputStream(fileUploadDir + path));
                        byte[] buffer = new byte[fis.available()];
                        fis.read(buffer);
                        fis.close();
                        // 清空response
//    				response.reset();
                        // 设置response的Header
                        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
                        response.addHeader("Content-Length", "" + file.length());
                        response.setContentType("application/x-download");
                        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                        response.setContentType("application/octet-stream");
                        toClient.write(buffer);
                        toClient.flush();
                        toClient.close();
                    } else {
                        response.setStatus(404);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } else {
            response.setStatus(404);
        }
        return response;
    }

    /**
     * 资源设备信息查询
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "资源查询", notes = "资源查询")
    //@Authorization(ingore = true)
    @GetMapping(value = "/resource/{type}/list")
    public CommonResponse getResourceList(@ApiParam(value = "资源类型", required = true) @PathVariable String type) {
        return planVisual3dService.getResourceListByType(type);
    }

    /**
     * 资源设备数据项查询
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @GetMapping(value = "/{type}/detail/{id}")
    @ApiOperation(value = "数据项查询", notes = "按照分类及id查询数据项")
    public CommonResponse getResourceDetail(
            @ApiParam(value = "资源类型", required = true) @PathVariable String type,
            @ApiParam(value = "主键id", required = true) @PathVariable Long id) {
        List<Map<String, Object>> list = planVisual3dService.getResourceById(type, id);
        return CommonResponseUtil.success(list);
    }
    
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "预案应用树", notes = "预案应用树")
    @GetMapping(value = "/plan/textPlanTree/{appId}")
    public CommonResponse getPlanTree(@PathVariable("appId") String appId) {
        return CommonResponseUtil.success(planVisual3dService.getTextPlanBySubjectId(appId));
    }
    
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "删除预案文件", notes = "删除预案文件")
    @DeleteMapping(value = "/plan/textPlan/{id}")
    public CommonResponse deleteTextPlanFile(@PathVariable("id") Long id) {
    	try {			
    		planVisual3dService.deleteTextPlanFile(id);
    		return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
    }

    
}
