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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaImageTotal;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaInfo;
import com.upyuns.platform.rs.datacenter.entity.RscpImageDataTotal;
import com.upyuns.platform.rs.datacenter.mapper.RscpAreaImageTotalMapper;
import com.upyuns.platform.rs.datacenter.mapper.RscpAreaInfoMapper;
import com.upyuns.platform.rs.datacenter.mapper.RscpImageDataTotalMapper;
import com.upyuns.platform.rs.datacenter.pojo.ImageTotalInputDTO;
import com.upyuns.platform.rs.datacenter.pojo.imagedata.QueryDTO;
import com.upyuns.platform.rs.datacenter.rest.RscpImageDataTotalController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

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

@Service
@Slf4j
public class RscpAreaImageTotalBiz extends BaseBiz<RscpAreaImageTotalMapper, RscpAreaImageTotal> {

    @Autowired
    RscpImageDataTotalMapper rscpImageDataTotalMapper;

    @Autowired
    RscpAreaInfoMapper rscpAreaInfoMapper;

    @Autowired
    RscpImageDataTotalBiz rscpImageDataTotalBiz;

    public List<RscpAreaImageTotal> queryDataList(QueryDTO dto) {
        return mapper.queryDataList(dto);
    }

    public void inStorageAreaDeal(ImageTotalInputDTO dto) {
        dto.initRange();

        // 第二步：判断是否已有区域影像信息，存在则删除
        //areaImageTotalManagement.deleteAreaImageTotalByDataId(imageDataId);
        delete(new RscpAreaImageTotal(){{
            setDataId(dto.getId());
        }});


        // 第三步：遍历地区表，查询该影像关联的地区
//        String geometryJson = areaInfoManagement.getGeometryJsonByWkt(imageData.getRange());

        // postgis查询区域交集
        List<RscpAreaInfo> imageAreaInfoList = rscpAreaInfoMapper.getIntersectAreaInfo(dto.getLeftTopLon(), dto.getLeftTopLat(), dto.getLeftBottomLon(), dto.getLeftBottomLat(), dto.getRightBottomLon(), dto.getRightBottomLat(), dto.getRightTopLon(), dto.getRightTopLat());

        if (CollUtil.isNotEmpty(imageAreaInfoList)) {
            // 第四步：拼接影像所属省、市
            Set<String> adminCodeSet = new HashSet<String>();
            Set<String> provinceNameSet = new HashSet<String>();
            Set<String> cityNameSet = new HashSet<String>();

            for (RscpAreaInfo areaInfo : imageAreaInfoList) {
                String adminCode = areaInfo.getAdmincode();
                String adminName = areaInfo.getName();
                adminCodeSet.add(adminCode);

                if (adminCode.substring(4, 6).equals("00") && !adminCode.substring(2, 6).equals("0000") && !adminName.equals("县")
                        && !adminName.equals("自治区直辖县级行政区划") && !adminName.equals("市辖区")) {

                    if (StringUtils.isNotBlank(areaInfo.getProname())) {
                        // 添加影像所属省
                        provinceNameSet.add(areaInfo.getProname());
                    }

                    if (StringUtils.isNotBlank(areaInfo.getName())) {
                        // 添加影像所属市
                        cityNameSet.add(areaInfo.getName());
                    }
                }
            }

            // 第五步：计算每座城市覆盖面积
            List<Map<String, Object>> intersectionAreaMapList = rscpAreaInfoMapper.queryIntersectionArea(dto.getRange(), "'"+ StrUtil.join("','", adminCodeSet)+ "'");
            for (Map<String, Object> intersectionAreaMap : intersectionAreaMapList) {
                log.info("===intersectionAreaMap:" + intersectionAreaMap);
                String proadcode = intersectionAreaMap.get("proadcode").toString();
//                String areaNoDetail = "{" + intersectionAreaMap.get("admin_code_ary").toString() + "}";
//                String isCover = "{" + intersectionAreaMap.get("is_cover_ary").toString() + "}";
                //String imageArea = "{" + intersectionAreaMap.get("image_area_ary").toString() + "}";
                Integer[] isCover = ArrayUtil.toArray(StrUtil.split(intersectionAreaMap.get("is_cover_ary").toString(),  ',').parallelStream().map(str -> Integer.valueOf(str)).collect(Collectors.toList()), Integer.class);
                String[] areaNoDetail = intersectionAreaMap.get("admin_code_ary").toString().split(",");
                        //StrSpliter.split(intersectionAreaMap.get("admin_code_ary").toString(),  ',', Boolean.TRUE, Boolean.TRUE);
                BigDecimal[] imageArea =
                        ArrayUtil.toArray(StrUtil.split(intersectionAreaMap.get("image_area_ary").toString(),  ',').parallelStream().map(str -> new BigDecimal(str)).collect(Collectors.toList()), BigDecimal.class);
//                StrSpliter.split(intersectionAreaMap.get("image_area_ary").toString(),  ',', Boolean.TRUE, Boolean.TRUE)
//                        .parallelStream().map(str -> new BigDecimal(str)).collect(Collectors.toList());

                // 第六步：入库rscp_area_image_total
                RscpAreaImageTotal areaImageTotal = new RscpAreaImageTotal();
                areaImageTotal.setId(UUID.randomUUID().toString());
                areaImageTotal.setAreaNo(proadcode);
                areaImageTotal.setAreaNoDetail(areaNoDetail);
                areaImageTotal.setImageRowCol(dto.getImageRowCol());
                areaImageTotal.setImageSatelliteType(dto.getImageSatelliteType());
                areaImageTotal.setImageResolution(dto.getImageResolution());
                areaImageTotal.setImageSpectrumType(dto.getImageSpectrumType());
                areaImageTotal.setImageSensorType(dto.getImageSensorType());
                areaImageTotal.setBeginTime(dto.getImageTakeTime());
//                areaImageTotal.setRange(dto.getRange());
                areaImageTotal.setNum(imageAreaInfoList.size());
                areaImageTotal.setIsCover(isCover);
                areaImageTotal.setImageArea(imageArea);
                areaImageTotal.setDataId(dto.getId());
                areaImageTotal.setImageCloudage(dto.getImageCloudage());
                areaImageTotal.setImageProductType(dto.getImageProductType());
                areaImageTotal.setName(dto.getName());
                areaImageTotal.setThumbnailPath(dto.getThumbnailPath());
                areaImageTotal.setImageIsSave(SYS_TRUE);
                areaImageTotal.setUpdateTime(DateUtil.date());
//                areaImageTotal.setImageProductId(dto.getImageProductId());

                // 保存区域影像信息至数据库
                insertSelective(areaImageTotal);

                dto.setAreaDataId(areaImageTotal.getId());
                updateGeom(dto);



            }

            // 第七步：更新rscm_image_data_total_v2
            log.info("===更新rscm_image_data_total_v2:" + StringUtils.join(provinceNameSet, ",") + "   " + StringUtils.join(cityNameSet, ","));

            try {
//                Map<String, Object> columnValueMap = new HashMap<String, Object>();
//                columnValueMap.put("image_province", "'" + StringUtils.join(provinceNameSet, ",") + "'");
//                columnValueMap.put("image_city", "'" + StringUtils.join(cityNameSet, ",") + "'");
//                columnValueMap.put("image_area", "st_area(range,true)/1000/1000");
//                imageDataManagement.updateImageDataTotalById(imageDataId, columnValueMap);
                rscpImageDataTotalBiz.updateSelectiveById(new RscpImageDataTotal(){{
                    setId(dto.getId());
                    setImageProvince(StrUtil.join(",", provinceNameSet));
                    setImageCity(StrUtil.join(",", cityNameSet));
//                    setImageArea(StrUtil.join(",", ));
                }});
                rscpImageDataTotalBiz.updateImageAreaByRange(dto.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Integer updateGeom(ImageTotalInputDTO dto){
        return mapper.updateGeom(dto.getLeftTopLon(), dto.getLeftTopLat(), dto.getLeftBottomLon(), dto.getLeftBottomLat(), dto.getRightBottomLon(), dto.getRightBottomLat(), dto.getRightTopLon(), dto.getRightTopLat(), dto.getAreaDataId());
    }

}
