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

import com.yeejoin.amos.fas.business.service.intfc.IPlanVisual3dService;
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;
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.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

@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;

    @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 (InputStream fis = new BufferedInputStream(new FileInputStream(fileUploadDir + path));) {
                    // path是指欲下载的文件的路径。
                    File file = new File(fileUploadDir + path);
                    if (file.exists()) {
                        // 取得文件名。
                        String filename = file.getName();
                        // 取得文件的后缀名。
                        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
                        // 以流的形式下载文件。
                        byte[] buffer = new byte[fis.available()];
                        fis.read(buffer);
                        // 清空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());
		}
    }

    
}
