package com.upyuns.platform.rs.datacenter.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.AssertUtils;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.result.JsonResultUtil;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.github.wxiaoqi.security.common.vo.PageParam;
import com.upyuns.platform.rs.datacenter.biz.RscpAreaImageTotalBiz;
import com.upyuns.platform.rs.datacenter.biz.RscpImageDataTotalBiz;
import com.upyuns.platform.rs.datacenter.biz.RscpImageInputLogBiz;
import com.upyuns.platform.rs.datacenter.biz.RscpImagePriceBiz;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaImageTotal;
import com.upyuns.platform.rs.datacenter.entity.RscpImageDataTotal;
import com.upyuns.platform.rs.datacenter.entity.RscpImageInputLog;
import com.upyuns.platform.rs.datacenter.entity.RscpImagePrice;
import com.upyuns.platform.rs.datacenter.fegin.RscloudboxClientRest;
import com.upyuns.platform.rs.datacenter.mapper.RscpAreaInfoMapper;
import com.upyuns.platform.rs.datacenter.pojo.ImageDataVO;
import com.upyuns.platform.rs.datacenter.pojo.ImagePageFeginDTO;
import com.upyuns.platform.rs.datacenter.pojo.ImageTotalInputDTO;
import com.upyuns.platform.rs.datacenter.pojo.imagedata.QueryDTO;
import com.upyuns.platform.rs.datacenter.pojo.rscloudbox.ImageDataDto;
import com.upyuns.platform.rs.datacenter.pojo.rscloudbox.RscmAreaImageDto;
import com.upyuns.platform.rs.datacenter.utils.ShpToGeojson;
import com.upyuns.platform.rs.datacenter.vo.ImageInputVO;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.nio.cs.ext.Big5;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
import static com.github.wxiaoqi.security.common.util.process.ResultCode.PARAM_ILLEGAL_CODE;

@RestController
@RequestMapping("/web/imageData")
public class RscpImageDataTotalController extends BaseController<RscpImageDataTotalBiz, RscpImageDataTotal> {

    @Autowired
    RscpAreaImageTotalBiz rscpAreaImageTotalBiz;

    @Autowired
    RscpImagePriceBiz rscpImagePriceBiz;

    @Autowired
    GtDataRestClient gtDataRestClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    RscloudboxClientRest rscloudboxClientRest;

    @Autowired
    RscpImageInputLogBiz rscpImageInputLogBiz;

    @RequestMapping(value = "/app/unauth/query", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse unauthQuery(PageParam pageParam) {
        return ObjectRestResponse.succ(baseBiz.selectByQuery(new Query(pageParam)));
    }

    @RequestMapping(value = "/app/unauth/aaa", method = RequestMethod.GET)
    @IgnoreUserToken
    @IgnoreClientToken
    public ObjectRestResponse unauthAaaa(PageParam pageParam) {
//        ImageInputVO vo = JSONUtil.toBean("{\"rightTopLon\":87.33106598951404,\"leftBottomLon\":87.26891697286784,\"imageCloudage\":0.18,\"imageSensorType\":\"micro\",\"imageWidthInPixels\":5001,\"imageSpectrumTypeDisplay\":\"{全色,多光谱}\",\"imageSatelliteTypeDisplay\":\"newsat8\",\"supplier\":\"Satellogic\",\"imageSensorId\":\"micro\",\"imageProductTime\":\"2020-09-14 04:42:05\",\"leftTopLat\":44.022589860423246,\"imageResolution\":[1,1],\"rightBottomLon\":87.33106598951404,\"imageStartTime\":\"2020-09-14 04:42:05\",\"imageCenterTime\":\"2020-09-14 04:42:05\",\"imageProjection\":\"WGS-84\",\"imageFilePath\":\"/rscloudmart/data/sateLLogic/20201220/20200914_044205_SN8_L1_Changji-China/20200914_044205_SN8_L1_Changji-China.zip\",\"imageSpectrumType\":\"{QS,DGP}\",\"imageSatelliteType\":\"newsat8\",\"imageSceneId\":\"newsat8_micro_L1_radiance_dca17df4-754d-4f02-ac65-3de4bfc66254_0_11_0\",\"imageCenterPointLon\":87.29999148119094,\"imageTakeTime\":\"2020-09-14 04:42:05\",\"leftTopLon\":87.26891697286784,\"imageEndTime\":\"2020-09-14 04:42:05\",\"rightTopLat\":44.022589860423246,\"leftBottomLat\":43.9774001602467,\"name\":\"20200914_044205_SN8_L1_Changji-China\",\"thumbnailPath\":\"/users/rscloudmart/thumbnail/data/sateLLogic/20201220/20200914_044205_SN8_L1_Changji-China\",\"imageCenterPointLat\":43.99999501033497,\"files\":[\"/20200914_044205_SN8_L1_Metadata.xml\",\"/20200914_044205_SN8_L1_RGB_Changji-China_showcase_Quicklook_800_800.png\",\"/20200914_044205_SN8_L1_RGB_Changji-China_showcase_Quicklook_800_800.jpeg\",\"/20200914_044205_SN8_L1_RGB_Changji-China_showcase_Quicklook_205_205.jpeg\",\"/20200914_044205_SN8_L1_RGB_Changji-China_showcase_Quicklook_98_98.jpeg\"],\"imageProductFormat\":\"TIFF\",\"imageHeightInPixels\":\"5001\",\"rightBottomLat\":43.9774001602467}", ImageInputVO.class);
        ImageInputVO vo = JSONUtil.toBean("{\"rightTopLon\":113.16291993521179,\"leftBottomLon\":113.2061962551077,\"imageCloudage\":0,\"imageSensorType\":\"micro\",\"imageWidthInPixels\":4400,\"imageSpectrumTypeDisplay\":\"全色,多光谱\",\"imageSatelliteTypeDisplay\":\"newsat8\",\"supplier\":\"Satellogic\",\"imageSensorId\":\"micro\",\"imageProductTime\":\"2020-07-13 02:40:30\",\"leftTopLat\":26.54466924531823,\"imageResolution\":[1,1],\"rightBottomLon\":113.2061962551077,\"imageStartTime\":\"2020-07-13 02:40:30\",\"imageCenterTime\":\"2020-07-13 02:40:30\",\"imageProjection\":\"WGS-84\",\"imageFilePath\":\"/rscloudmart/data/sateLLogic/20200713/20200713_024030_SN8_L1_MS_Huawang-China_showcase//20200713_024030_SN8_L1_MS_Huawang-China_showcase.zip\",\"imageSpectrumType\":\"QS,DGP\",\"imageSatelliteType\":\"newsat8\",\"imageSceneId\":\"newsat8_micro_L1_radiance_a67ee813-f7b3-4c07-be5e-6e8a55d7e13a_0_8_1\",\"imageCenterPointLon\":26.521774593346027,\"imageTakeTime\":\"2020-07-13 02:40:30\",\"leftTopLon\":113.16291993521179,\"imageEndTime\":\"2020-07-13 02:40:30\",\"rightTopLat\":26.498879941373822,\"leftBottomLat\":26.54466924531823,\"name\":\"20200713_024030_SN8_L1_MS_Huawang-China_showcase\",\"thumbnailPath\":\"/rscloudmart/thumbnail/data/sateLLogic/20200713/20200713_024030_SN8_L1_MS_Huawang-China_showcase\",\"imageCenterPointLat\":113.18455809515974,\"files\":[\"/20200713_024030_SN8_L1_Metadata.xml\",\"/20200713_024030_SN8_L1_RGB_Huawang-China_showcase_Quicklook_800_800.png\",\"/20200713_024030_SN8_L1_RGB_Huawang-China_showcase_Quicklook_800_800.jpeg\",\"/20200713_024030_SN8_L1_RGB_Huawang-China_showcase_Quicklook_205_205.jpeg\",\"/20200713_024030_SN8_L1_RGB_Huawang-China_showcase_Quicklook_98_98.jpeg\"],\"imageProductFormat\":\"TIFF\",\"imageHeightInPixels\":\"5000\",\"rightBottomLat\":26.498879941373822}", ImageInputVO.class);
        vo.clearBracket();
        baseBiz.inStorage(vo);
        return ObjectRestResponse.succ();

    }

    @RequestMapping(value = "/app/unauth/inStorageByLog", method = RequestMethod.GET)
    @IgnoreUserToken
    @IgnoreClientToken
    public ObjectRestResponse inStorageByLog(Integer logId) {
        RscpImageInputLog log = rscpImageInputLogBiz.selectById(logId);
        ImageInputVO vo = JSONUtil.toBean(log.getContextJson(), ImageInputVO.class);
        vo.clearBracket();
        baseBiz.inStorage(vo);
        return ObjectRestResponse.succ();
    }

//    @RequestMapping(value = "/storageJson", method = RequestMethod.POST)
//    public ObjectRestResponse storageJson(@RequestBody StorageJsonDTO storageJsonDTO) {
//
//        vo.clearBracket();
//        baseBiz.inStorage(vo);
//        return ObjectRestResponse.succ();
//    }
//
//    @Data
//    public class StorageJsonDTO {
//        String json;
//    }

//   resolution
//	     分辨率
//	 spectrum
//	     光谱
//	 startDate
//	     2017/04/14
//     endDate
//	     2017/07/13
//     geom
//	     {"type":"Polygon","coordinates":[[[3,4],[3,2],[1,2],[1,4],[3,4]]]}
//	 areaNo
//	     行政区域
//	 areaName
//	     行政区域名称
//	 resolutionSa
//	     分辨率/卫星
//	 saSensor
//	     卫星/传感器 {'GF2':'[PMS]','GF4':'[IRS]','GF1':'[PMS]'}
//	 shp
//	     2
//     cloud
//	     云量 10
//     imageSatelliteType
//	     卫星
//	 request
//	 resId
//	     分辨率id

    @RequestMapping(value = "/app/unauth/queryDataList", method = RequestMethod.POST)
    @IgnoreUserToken
    public ObjectRestResponse queryDataList(@RequestBody QueryDTO dto) {
        if(QueryDTO.TYPE_AREA == dto.getType()) {
            return ObjectRestResponse.succ(rscpAreaImageTotalBiz.queryDataList(dto));
        }else if(QueryDTO.TYPE_SHP == dto.getType()){
            //shp 转 geom
//            String shpPath = redisTemplate.opsForValue().get(dto.getShpKey());
//            dto.setGeom(ShpToGeojson.shp2geojson(shpPath));
            String redisStr = redisTemplate.opsForValue().get(dto.getShpKey()).toString();
            ShpDTO shpDTO = JSONUtil.toBean(redisStr, ShpDTO.class);
            if(CollUtil.isNotEmpty(shpDTO.getFeatures())) {
                dto.setGeoms(shpDTO.getFeatures());
//                dto.setGeom(redisTemplate.opsForValue().get(dto.getShpKey()).toString());
            }
            return ObjectRestResponse.succ(baseBiz.queryDataAreaList(dto));
        } else {
            return ObjectRestResponse.succ(baseBiz.queryDataAreaList(dto));
        }
    }

    @RequestMapping(value = "/app/unauth/queryGeomsJsonFegin", method = RequestMethod.POST)
    @IgnoreUserToken
    public String queryGeomsJsonFegin(@RequestBody QueryDTO dto){
        String redisStr = redisTemplate.opsForValue().get(dto.getShpKey()).toString();
        ShpDTO shpDTO = JSONUtil.toBean(redisStr, ShpDTO.class);
        if(CollUtil.isNotEmpty(shpDTO.getFeatures())) {
            dto.setGeoms(shpDTO.getFeatures());
            return baseBiz.queryGeomsJson(dto);
        }
        return null;
    }

    @Data
    public static class ShpDTO {
        List<String> features;
    }

    @RequestMapping(value = "/app/unauth/detailById", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse<List<RscpImageDataTotal>> detailById(Long id){
        return ObjectRestResponse.succ(baseBiz.queryDataList(id));
    }

    @RequestMapping(value = "/app/unauth/Fegin/queryByIds", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse<List<ImageDataVO>> queryByIds(String ids){
        List<RscpImagePrice> list = rscpImagePriceBiz.selectByWeekend(w -> {
            w.andEqualTo(RscpImagePrice::getStatus, SYS_TRUE);
            return w;
        }, " daily_sort asc ");
        List<Long> longs = CollUtil.toList(ids.split(",")).parallelStream().map(e -> Long.valueOf(e)).collect(Collectors.toList());
        List<RscpImageDataTotal> list2 = baseBiz.selectByAttrs(RscpImageDataTotal::getId, longs);
        List<ImageDataVO> list3 = CollUtil.newArrayList();
        list2.forEach(t -> {
            ImageDataVO vo = BeanUtil.toBean(t, ImageDataVO.class);
            vo.setBeginTime(t.getImageTakeTime());
            list.forEach(p -> {
                if(t.getImageSatelliteType().equals(p.getImageSatelliteType())
                && t.getImageSensorType().equals(p.getImageSensorType())) {
                    vo.setPrice(p.getPrice());
                }
            });
            list3.add(vo);
        });
        return ObjectRestResponse.succ(list3);
    }

    @RequestMapping(value = "/app/unauth/Fegin/pageBykey", method = RequestMethod.POST)
    @IgnoreUserToken
    public ObjectRestResponse<PageDataVO<ImageDataVO>> pageBykey(@RequestBody ImagePageFeginDTO dto){
        return ObjectRestResponse.succ(
                PageDataVO.pageInfo(dto.initQuery(),()-> baseBiz.selectByWeekend(w -> {
                    if(StrUtil.isNotBlank(dto.getKeyword())) {
                        w.andLike(RscpImageDataTotal::getName, "%"+ dto.getKeyword()+ "%");
                    }
                    w.andEqualTo(RscpImageDataTotal::getIsDel, SYS_FALSE);
                    return w;
                }), ImageDataVO.class)
        );
    }


    @RequestMapping(value = "/app/unauth/inputbbox", method = RequestMethod.GET)
    @IgnoreUserToken
    @IgnoreClientToken
    public ObjectRestResponse inputbbox(Long dataid) {
        Map<String, Object> map = baseBiz.inputbox(dataid);
        return ObjectRestResponse.succ(map);
    }

    public static void main(String[] args) {
        String str = StrUtil.sub("UPDATE rscp_image_data_total SET name = '20200914_044205_SN8_L1_Changji-China',range = '0106000020E6100000010000000103000000010000000500000067DB7B39E40246409EF388EF35D1554067DB7B39E4024640F471672F30D5554083ABCD721BFD4540F471672F30D5554083ABCD721BFD45409EF388EF35D1554067DB7B39E40246409EF388EF35D15540',thumbnail_path = '/rscloudmart/thumbnail/data/sateLLogic/20200914/20200914_044205_SN8_L1_Changji-China',image_resolution = [1, 1],image_spectrum_type = [{QS, DGP}],image_spectrum_type_display = [{全色, 多光谱}],image_file_path = '/rscloudmart/data/sateLLogic/20200914/20200914_044205_SN8_L1_Changji-China//20200914_044205_SN8_L1_Changji-China.zip',image_projection = ?,image_satellite_type = ?,image_satellite_type_display = ?,image_take_time = ?,image_cloudage = ?,image_sensor_type = ?,files = ?,image_sensor_id = ?,image_scene_id = ?,image_product_format = ?,image_product_time = ?,image_start_time = ?,image_end_time = ?,image_center_time = ?,image_width_in_pixels = ?,image_height_in_pixels = ? WHERE id = ?", 569, 589);
        System.out.println(str);
    }
}