package org.springblade.modules.earth.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Query;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.modules.earth.service.RasterService;
import org.springblade.modules.earth.entity.Raster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import org.springblade.core.tool.api.R;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;



/**
* 类名: RasterController
* @author hzy
*/
@Validated
@Api(tags = "RasterController")
@RestController
@RequestMapping("raster")
public class RasterController extends BladeController {
    private final static Logger logger = LoggerFactory.getLogger(RasterController.class);

    @Autowired
    private RasterService rasterService;


	@ApiOperation("发布tif图")
	@ResponseBody
	@RequestMapping(value = "publishRaster",method = RequestMethod.POST)
	public R publishRaster(@RequestBody Raster request) throws Exception {
		// TODO: 将请求参数构建为HTTP请求发送到API服务器，获取响应数据
		// 这里可以使用HttpURLConnection或者其他HTTP客户端库发送请求

		String gridName = request.getGridName();
		String gridType = request.getGridType();
		String gridUrl = request.getGridUrl();

		// 对请求参数做校验
		checkRequestParam(gridName, gridType, gridUrl);
		// 校验 链接的连通性
		boolean downloadable = isDownloadable(gridUrl);
		if(!downloadable){
			return R.fail(400,"文件链接不可访问");
		}
		if(CommonUtil.isNotNull(request.getAttachmentUrl())){
			boolean attachAble = isDownloadable(request.getAttachmentUrl());
			if(!attachAble){
				return R.fail(400,"附件链接不可访问");
			}
		}

		this.save(request);
		// 假设成功发布栅格后，API服务器会返回数据ID


		return R.data(request.getId());
	}

	public boolean isDownloadable(String url) {
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod("HEAD");
			connection.setConnectTimeout(1000);
			connection.setReadTimeout(1000);

			int responseCode = connection.getResponseCode();
			return (responseCode >= 200 && responseCode < 300) || responseCode == 304;
		} catch (IOException e) {
			return false;
		}
	}


	private static void checkRequestParam(String gridName, String gridType, String gridUrl) {
		if (gridName == null || gridType == null || gridUrl == null) {
			String message = "Missing required parameter(s): ";
			if (gridName == null) {
				message += "gridName, ";
			}
			if (gridType == null) {
				message += "gridType, ";
			}
			if (gridUrl == null) {
				message += "gridUrl, ";
			}
			message = message.substring(0, message.length() - 2);
			throw new IllegalArgumentException(message);
		}
	}

    @ApiOperation("根据ID获取记录信息")
    @RequestMapping(value = "selectById", method = RequestMethod.GET)
    @ResponseBody
    public R<Raster> selectById(@RequestParam(value = "id") Integer id){
        Raster model = rasterService.getById(id);
        if (CommonUtil.isNull(model)) {
            return R.fail(400,"未获取到数据, 请检查id");
        }
        return R.data(model);
    }

    @ApiOperation("保存")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public R<Raster> save(@RequestBody Raster entity) {
        boolean saveSuccess =rasterService.save(entity);
        if(saveSuccess == true){
            return R.data(entity);
        }
        return R.fail(400,"插入失败");
    }


    @ApiOperation("分页查询")
    @ApiImplicitParams( value = {
        @ApiImplicitParam(paramType = "query", name = "gridName", value = "发布的栅格的名称", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "gridType", value = "栅格文件类型，可选值为 'tiff' 或 'img'", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "gridUrl", value = "发布栅格的可下载链接", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "captureDate", value = "数据采集时间，格式为字符串", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "attachmentType", value = "附属文件类型,可选值为 'rpb'、'rpc' 或 'tfw'；对于 img 格式，可选值为 'ige'", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "attachmentUrl", value = "发布栅格的附属文件的可下载链接", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "tenantId", value = "tenantId", dataType = "int", required = false),
        @ApiImplicitParam(paramType = "query", name = "startCreateTime", value = "开始时间", dataType = "String", required = false),
        @ApiImplicitParam(paramType = "query", name = "endCreateTime", value = "结束时间", dataType = "String", required = false)
    })
    @RequestMapping(value = "selectPage", method = RequestMethod.GET)
    @ResponseBody
    public R<IPage<Raster>> selectPage(@ApiIgnore @RequestParam Map<String, Object> code, Query query) {
        IPage<Raster> pages = rasterService.page(Condition.getPage(query), Condition.getQueryWrapper(code, Raster.class));
        return R.data(pages);
    }


}
