package com.upyuns.platform.rs.website.controller.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.upyuns.platform.rs.website.biz.LmyxmonitorimageBiz;
import com.upyuns.platform.rs.website.entity.Lmyxmonitorimage;
import com.upyuns.platform.rs.website.util.GeoServerUtil;
import com.upyuns.platform.rs.website.util.LoginDigestUtil;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;

@RestController
@RequestMapping("lmyxmonitorimage/web")
public class LmyxmonitorimageController extends BaseController<LmyxmonitorimageBiz,Lmyxmonitorimage> {

    @Value("${universal.baseUploadPath}")
    private String baseUploadPath ;

    @Value("${universal.url}")
    private String xx_url ;

    @RequestMapping(value = "/app/unauth/baseAdd",method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<Lmyxmonitorimage> appUnauthbaseAdd(@RequestBody Lmyxmonitorimage entity){
        baseBiz.insertSelective(entity);
        return new ObjectRestResponse<Lmyxmonitorimage>();
    }

    @ApiOperation("根据参数查询，等于")
    @RequestMapping(value = "/app/unauth/logicList",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<List<Lmyxmonitorimage>> logicList(Lmyxmonitorimage entity){
        //查询列表数据
        entity.setIsDel(SYS_FALSE);
        entity.setState(Lmyxmonitorimage.STATE_UP);
        return ObjectRestResponse.succ(baseBiz.selectList(entity));
    }

    /**
     * 类型：2212--温度反演；2213--植被覆盖度；2214--植被识别；2215--水体识别；2216--风险等级；2217--病虫害监测；2218--植被覆盖变化
     * @param dto
     * @return
     */
    @RequestMapping(value = "/app/unauth/publishMap",method={RequestMethod.POST})
    @ResponseBody
    public ObjectRestResponse<String> publishMap(@RequestBody PublishMapDTO dto){
        if(StrUtil.isBlank(dto.getWorkSpace())) {
            dto.setWorkSpace("test");
        }
//        ResultBean<String> resultBean = new ResultBean<String>();
        dto.setStyle("raster");
        GeoServerUtil.publishGeoTIFF(dto.getWorkSpace(), dto.getLayerName(), dto.getFilePath(), dto.getLayerName(), dto.getStyle());
//		HttpClientUtils httpClientApi = new HttpClientUtils("https://zzrsmgmt.upyuns.com/api/website/lmyxmonitorimage/web/app/unauth/baseAdd");
//		httpClientApi.execute()
        Lmyxmonitorimage lmyxmonitorimage = new Lmyxmonitorimage();
        lmyxmonitorimage.setState(1);
        lmyxmonitorimage.setType(dto.getType());
        if(dto.getType() == 2213) {
            lmyxmonitorimage.setLegendUrl("https://hstandfarm.upyuns.com/legend/植被覆盖度图例.png");
        }
        if(dto.getType() == 2214) {
            lmyxmonitorimage.setLegendUrl("https://hstandfarm.upyuns.com/legend/乡镇绿地图例.png");
        }
        if(dto.getType() == 2215) {
            lmyxmonitorimage.setLegendUrl("https://hstandfarm.upyuns.com/legend/水体识别图例.png");
        }
        if(dto.getType() == 2216) {
            lmyxmonitorimage.setLegendUrl("https://hstandfarm.upyuns.com/legend/火灾风险等级图例.png");
        }
        if(dto.getType() == 2217) {
            lmyxmonitorimage.setLegendUrl("https://hstandfarm.upyuns.com/legend/病虫害林地图例.png");
        }
        if(dto.getType() == 2218) {
            lmyxmonitorimage.setLegendUrl("https://hstandfarm.upyuns.com/legend/植被覆盖变化图例.png ");
        }
        lmyxmonitorimage.setUrl("https://hstandfarm.upyuns.com/geoserver/"+dto.getWorkSpace()+"/wms");
        lmyxmonitorimage.setTitle(dto.getTitle());
        lmyxmonitorimage.setResourcename(dto.getLayerName());
        String result = HttpUtil.post("http://zzrsmgmt.upyuns.com/api/website/lmyxmonitorimage/web/app/unauth/baseAdd", JSONUtil.toJsonStr(lmyxmonitorimage));
        return ObjectRestResponse.succ(result);
    }

    @RequestMapping(value = "/app/unauth/order",method={RequestMethod.POST})
    @ResponseBody
    public ObjectRestResponse<String> order() throws Exception {
        Long timelong = new Date().getTime();
        String uuid = timelong+ "";
        String time = (timelong + 1L) + "";
        String pvtKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALcPs3K2jRrdYSWFvsgMOogWgwa15kmEUC3AxlL4OwTOUFcxakZXKJdfBERK2Amz1ctf7RBGCq8WeAM07vcGSa9Ipp511w6YSezQIei748gN368o7lLfeXXE2ht8zLfCF05soLHtigjCYgM3pZPPfwRste+SV3G/Up8Ij/eW3hi1AgMBAAECgYANXw05fNITu0XkSr+jtxjzZcmOTO0UQ6DjpqgV2WHeOP+vTsG3f5hMbjlOj7T2CHe+UjRrsuIG5fpAKbamvoPVNQWT3C+PjA0xQqWU/LOnoIPfTI/JUYBkKtP3NAjib5bI61pqGJ0tLW4C6w1y3F0Qx0X8vyEnE9gLVuZ9c3+DwQJBAPGQc4kahnyKOQ0UO2+G0EjcuzLFkiZ6R83w5gBpe4i2EFGNzIrq8O3JxTI8n9nk+3CEXkvj6sEauRw/NyEsAtECQQDCAD95GBnADDZ4nshlhF0aA98+B37t2Uf/I7ZeRlT1jsdgeHsEAQXUUTRkQriAb1oX6GiEwjxx1OZ1+jSPvcilAkAhB5BUodTbuIaefDK4SCW4oL3T7mHScwvYY+T/D209vy8yB4J9SCyTRvB4swNkZsPemarPE6Xoq3++FgKyvXLRAkEAmCEZpRwBFVh+XpglDXZ+i6f9p+a44ktA6hJXMBZ3CRitwDi6PqmOqLAFJZoslIq9W4Ikc/bc72bEUj+ieBWbAQJAOGzhE6H3mR+XIM7S5mkZvjswtyGApjYuIq1Sm7b0aQm1L4IN9pXaHtQOhEnigPTMAexu/GX4LDyWlKZIcv8M+A==";
        String original = "appKey=guangdong&uid="+uuid+"&timestamp="+time;
        String sign = LoginDigestUtil.sign(original, pvtKey);

        System.out.println(uuid);
        System.out.println(time);
        System.out.println(sign);

        HttpRequest httpRequest = HttpRequest.post("https://smartplanting.cm-agri.com:442/plant-service/openApi/order");
        Map<String, String> headers = CollUtil.newHashMap();
        headers.put("appKey", "guangdong");
        headers.put("uid", uuid);
        headers.put("timestamp", time);
        headers.put("sign", sign);

        Map<String, Object> form = CollUtil.newHashMap();
        form.put("moduleCode", "landResource");
        form.put("regionCode", "440200");
        form.put("startTime", "2023-12-01");
        form.put("endTime", "2024-01-01");

        httpRequest.addHeaders(headers);
        httpRequest.form(form);
        String result = httpRequest.execute().body();
        return ObjectRestResponse.succ(result);
    }

    @RequestMapping(value = "/app/unauth/orderInfo",method={RequestMethod.GET})
    @ResponseBody
    public ObjectRestResponse<String> orderInfo(String id) throws Exception {
        Long timelong = new Date().getTime();
        String uuid = timelong+ "";
        String time = (timelong + 1L) + "";
        String pvtKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALcPs3K2jRrdYSWFvsgMOogWgwa15kmEUC3AxlL4OwTOUFcxakZXKJdfBERK2Amz1ctf7RBGCq8WeAM07vcGSa9Ipp511w6YSezQIei748gN368o7lLfeXXE2ht8zLfCF05soLHtigjCYgM3pZPPfwRste+SV3G/Up8Ij/eW3hi1AgMBAAECgYANXw05fNITu0XkSr+jtxjzZcmOTO0UQ6DjpqgV2WHeOP+vTsG3f5hMbjlOj7T2CHe+UjRrsuIG5fpAKbamvoPVNQWT3C+PjA0xQqWU/LOnoIPfTI/JUYBkKtP3NAjib5bI61pqGJ0tLW4C6w1y3F0Qx0X8vyEnE9gLVuZ9c3+DwQJBAPGQc4kahnyKOQ0UO2+G0EjcuzLFkiZ6R83w5gBpe4i2EFGNzIrq8O3JxTI8n9nk+3CEXkvj6sEauRw/NyEsAtECQQDCAD95GBnADDZ4nshlhF0aA98+B37t2Uf/I7ZeRlT1jsdgeHsEAQXUUTRkQriAb1oX6GiEwjxx1OZ1+jSPvcilAkAhB5BUodTbuIaefDK4SCW4oL3T7mHScwvYY+T/D209vy8yB4J9SCyTRvB4swNkZsPemarPE6Xoq3++FgKyvXLRAkEAmCEZpRwBFVh+XpglDXZ+i6f9p+a44ktA6hJXMBZ3CRitwDi6PqmOqLAFJZoslIq9W4Ikc/bc72bEUj+ieBWbAQJAOGzhE6H3mR+XIM7S5mkZvjswtyGApjYuIq1Sm7b0aQm1L4IN9pXaHtQOhEnigPTMAexu/GX4LDyWlKZIcv8M+A==";
        String original = "appKey=guangdong&uid="+uuid+"&timestamp="+time;
        String sign = LoginDigestUtil.sign(original, pvtKey);

        System.out.println(uuid);
        System.out.println(time);
        System.out.println(sign);

        HttpRequest httpRequest = HttpRequest.get("https://smartplanting.cm-agri.com:442/plant-service/openApi/orderInfo?id="+ id);
        Map<String, String> headers = CollUtil.newHashMap();
        headers.put("appKey", "guangdong");
        headers.put("uid", uuid);
        headers.put("timestamp", time);
        headers.put("sign", sign);

//        Map<String, Object> form = CollUtil.newHashMap();
//        form.put("moduleCode", "landResource");
//        form.put("regionCode", "440200");
//        form.put("startTime", "2023-12-01");
//        form.put("endTime", "2024-01-01");

        httpRequest.addHeaders(headers);
//        httpRequest.form(form);
        String result = httpRequest.execute().body();
        return ObjectRestResponse.succ(result);
    }

    @RequestMapping(value = "/app/unauth/download",method={RequestMethod.GET})
    @ResponseBody
    public ObjectRestResponse<String> download(String id) throws Exception {
        Long timelong = new Date().getTime();
        String uuid = timelong+ "";
        String time = (timelong + 1L) + "";
        String pvtKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALcPs3K2jRrdYSWFvsgMOogWgwa15kmEUC3AxlL4OwTOUFcxakZXKJdfBERK2Amz1ctf7RBGCq8WeAM07vcGSa9Ipp511w6YSezQIei748gN368o7lLfeXXE2ht8zLfCF05soLHtigjCYgM3pZPPfwRste+SV3G/Up8Ij/eW3hi1AgMBAAECgYANXw05fNITu0XkSr+jtxjzZcmOTO0UQ6DjpqgV2WHeOP+vTsG3f5hMbjlOj7T2CHe+UjRrsuIG5fpAKbamvoPVNQWT3C+PjA0xQqWU/LOnoIPfTI/JUYBkKtP3NAjib5bI61pqGJ0tLW4C6w1y3F0Qx0X8vyEnE9gLVuZ9c3+DwQJBAPGQc4kahnyKOQ0UO2+G0EjcuzLFkiZ6R83w5gBpe4i2EFGNzIrq8O3JxTI8n9nk+3CEXkvj6sEauRw/NyEsAtECQQDCAD95GBnADDZ4nshlhF0aA98+B37t2Uf/I7ZeRlT1jsdgeHsEAQXUUTRkQriAb1oX6GiEwjxx1OZ1+jSPvcilAkAhB5BUodTbuIaefDK4SCW4oL3T7mHScwvYY+T/D209vy8yB4J9SCyTRvB4swNkZsPemarPE6Xoq3++FgKyvXLRAkEAmCEZpRwBFVh+XpglDXZ+i6f9p+a44ktA6hJXMBZ3CRitwDi6PqmOqLAFJZoslIq9W4Ikc/bc72bEUj+ieBWbAQJAOGzhE6H3mR+XIM7S5mkZvjswtyGApjYuIq1Sm7b0aQm1L4IN9pXaHtQOhEnigPTMAexu/GX4LDyWlKZIcv8M+A==";
        String original = "appKey=guangdong&uid="+uuid+"&timestamp="+time;
        String sign = LoginDigestUtil.sign(original, pvtKey);

        System.out.println(uuid);
        System.out.println(time);
        System.out.println(sign);

        HttpRequest httpRequest = HttpRequest.get("https://smartplanting.cm-agri.com:442/plant-service/openApi/download?id="+ id);
        Map<String, String> headers = CollUtil.newHashMap();
        headers.put("appKey", "guangdong");
        headers.put("uid", uuid);
        headers.put("timestamp", time);
        headers.put("sign", sign);

        httpRequest.addHeaders(headers);
        // 直接在这里设置跟随重定向就可以了
        httpRequest.setFollowRedirects(true);
        httpRequest.setMaxRedirectCount(5);
//        String result = httpRequest.execute().body();
        HttpResponse response = httpRequest.execute();
//        if (response.isFollowRedirect() && response.getRedirectCount() > 0) {
//            String redirectUrl = request.getUrl();
//            System.out.println("重定向后的URL: " + redirectUrl);
//        }
        if (false == response.isOk()) {
            throw new HttpException("Server response error with status code: [{}]", response.getStatus());
        }
        response.writeBody(new File(baseUploadPath+ "/sanhua/"+id+".zip"), null);
        return ObjectRestResponse.succ(xx_url+ SystemConfig.XXMP_URL + "/sanhua/"+id+".zip");
    }

    @Data
    public static class PublishMapDTO {
        String workSpace;
        String title;
        String filePath;
        String layerName;
        String style;
        Integer type;
    }
}