import Layer from 'ol/layer/Vector'
import Source from 'ol/source/Vector'
import Select from 'ol/interaction/Select.js';
import {singleClick} from 'ol/events/condition'
import * as olEvents from 'ol/events';
import config from "@/api/config.js"
import * as KMap from '@/utils/ol-map/KMap';
import Style from "ol/style/Style";
import Photo from "ol-ext/style/Photo";
import {base_img_url2} from "../../api/config";
import Stroke from "ol/style/Stroke";
import * as util from "@/common/ol_common.js"
import {newAreaFeature, newAreaPoint, newPolymerFeature, newPoint} from "../zhgl/map";
import Icon from "ol/style/Icon";
import Point from 'ol/geom/Point.js';
import * as olExtent from 'ol/extent';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import Draw from 'ol/interaction/Draw.js';
import {createBox} from 'ol/interaction/Draw';
import { reactive } from 'vue';
export const treeIdsData = reactive({
    value: []
  });

/**
 * @description 智能巡园地图层对象
 */
class OwnershipMap {

    constructor(){
        let that = this
        this.vectorStyle = new KMap.VectorStyle()
        this.subAreaLayer = new KMap.VectorLayer("subAreaLayer",1000,{style:(f)=> {
                return that.vectorStyle.getPolygonStyle(f.get("fillColor"), f.get("strokeColor"), 2)
        }})
        this.afterDayNum = 3
        this.treeCacheStyle = {}
        this.treeStyle= (f)=> {
            let key = f.get("imgSrc");
            if(that.treeCacheStyle[key]){
                return that.treeCacheStyle[key]
            }
            let style = new Style({
                image: new Icon({
                    src: f.get("imgSrc"),
                    scale:1,
                    anchor:[0.5,1],
                })
            });
            that.treeCacheStyle[key] = style
            return style
        }
        this.treeLayer = new KMap.VectorLayer("statusPointLayer",999,{style:that.treeStyle})
        this.treePointLayer = new KMap.VectorLayer("treePointLayer",999,{style:(f)=> {
            let color = f.get('selected') ? "#ffa500" : "#4e64c6"
            let strokeColor = f.get('selected') ? "#ffa500" : "#4e64c6"
            return that.vectorStyle.getPointSimpleStyle(5,color,strokeColor,"2")
            }
        })
        this.treeFeatures = []
    }

    initMap(location, target)  {
        let level = 18
        let coordinate = util.wktCastGeom(location).getFirstCoordinate()
        this.kmap = new KMap.Map(target,level,coordinate[0], coordinate[1],null,10,22);
        let xyz = config.base_img_url + 'map/lby/{z}/{x}/{y}.png';
        this.kmap.addXYZLayer(xyz,{minZoom:15,maxZoom:22});
        let xyz2 = config.base_img_url3 + 'map/lby/{z}/{x}/{y}.png';
        this.kmap.addXYZLayer(xyz2,{minZoom:12,maxZoom:22});
        this.kmap.addLayer(this.subAreaLayer.layer)
        this.kmap.addLayer(this.treeLayer.layer)
        this.kmap.addLayer(this.treePointLayer.layer)
    }

    async initArea(gardenId, callback){
        let that = this
        // 果树级
        this.treePointLayer.refresh()
        await VE_API.regionalInformation.aPictureTreeList({gardenId}).then(({data,code})=>{
            for(let item of data){
                let point = newPoint(item, "wkt","polymer");
                that.treePointLayer.addFeature(point)
            }
            callback && callback()
        })
        this.fit(this.treePointLayer.source.getExtent())
        // this.selectPoint()
        // const ids = [75468,75471,75513,75585, 75586]
        // this.setSelectedPoint(ids)
        // this.getSelectedPoint()
        // this.initDrawBox()
    }

    // 点选
    selectPoint() {
        let that = this
        this.kmap.on('click', function (ev) {
            that.kmap.map.forEachFeatureAtPixel(ev.pixel, function (feature) {
                let geometry = feature.getGeometry();
                if (geometry instanceof Point) {
                    // selected = feature;
                    feature.set('selected', !feature.get('selected'))
                    // that.treePointLayer.changed()
                    return true;
                }
            });
        });
    }

    // 默认选中的
    setSelectedPoint(idArr) {
        let that = this
        this.clearFeaturesSelected()
        if (idArr && idArr.length) {
            // 筛选selectedIds对应的Feature并计算范围
            const features = that.treePointLayer.source.getFeatures()
            const selectedFeatures = features.filter(feature => idArr.includes(feature.getId()));
            let extent = olExtent.createEmpty(); // 创建一个空的Extent
            selectedFeatures.forEach(feature => {
                feature.set('selected', feature)
                extent = olExtent.extend(extent, feature.getGeometry().getExtent());
            })
            that.fit(extent)
        }
    }

    // 获取框选中的ids
    getSelectedPoint() {
        const features = this.treePointLayer.source.getFeatures()
        const selectedFeatures = features.filter(feature => feature.get("selected"));
        let treeIds = []
        selectedFeatures.forEach(feature => {
            treeIds.push(feature.getId())
        })
        treeIdsData.value = treeIds
    }
    // -----------draw----------------
    initDrawBox() {
        this.clearFeaturesSelected()
        let that = this
        this.tempVector = new VectorLayer({
            title: '画线层',
            source: new VectorSource({}),
            style: that.vectorStyle.getPolygonStyle("#ffffff00", "#ffffff00", 2),
            zIndex: 999
        })
        this.kmap.addLayer(this.tempVector)
        that.drawBox = new Draw({
            source: that.tempVector.getSource(),
            type: "Circle",
            geometryFunction: createBox(),
            freehand: false,//自由绘制
            // stopClick: true,
            // style: that.style(that.styleType.dotted)
        })
        // that.drawBox.setActive(false)
        // that.drawBox.on("drawend", function(e){
        //     that.drawBox.setActive(false)
        //     // that.endRemovePoint(e)
        // })
        that.kmap.map.addInteraction(that.drawBox)

        // 监听 drawend 事件
        that.drawBox.on('drawend', function (event) {
            // 获取绘制的几何对象（矩形）
            const geometry = event.feature.getGeometry();
            const extent = geometry.getExtent();
            // 遍历矢量图层中的所有feature
            that.treePointLayer.source.getFeatures().forEach(function (feature) {
                // feature与矩形是否相交
                if (olExtent.intersects(extent, feature.getGeometry().getExtent())) {
                    // 相交部分设置样式为selected
                    feature.set('selected', !feature.get('selected'));
                }
            });
            that.tempVector.getSource().clear()
            that.getSelectedPoint()
        });
    }

    // 移除draw
    removeDraw() {
        this.kmap.map.removeInteraction(this.drawBox)
        this.clearFeaturesSelected()
    }

    // 清除selected属性
    clearFeaturesSelected() {
        const features = this.treePointLayer.source.getFeatures()
        features.forEach(feature => {
            feature.set('selected', false);
        });
        treeIdsData.value = []
    }

    addToggleTreeSelect(listener){
        let that = this
        this.treeLayer.addToggleSelect(function({deselected,selected, preventDefault}){
            if(selected.length > 0){
                listener && listener(selected[0],deselected[0])
            }
            preventDefault()
        },this.kmap.map, that.treeStyle)
    }

    addToggleSubAreaSelect(listener){
        let that = this
        this.subAreaLayer.addToggleSelect(function({deselected,selected,preventDefault}){
            if(selected.length > 0){
                that.treeLayer.source.forEachFeature((f)=>{
                    if(f.get("subAreaId") == selected[0].get("id")){
                        that.treeLayer.toggleSelect.getFeatures().remove(f)
                    }
                })
                that.treeLayer.source.forEachFeature((f)=>{
                    if(f.get("subAreaId") == selected[0].get("id")){
                        that.treeLayer.toggleSelect.getFeatures().push(f)
                    }
                })
            }
            if(deselected.length > 0){
                that.treeLayer.source.forEachFeature((f)=>{
                    if(f.get("subAreaId") == deselected[0].get("id")){
                        that.treeLayer.toggleSelect.getFeatures().remove(f)
                    }
                })
            }
            listener && listener(selected[0],deselected[0])
            preventDefault()
        },this.kmap.map)
    }

    refreshTree(organId,day,callback){
        this.afterDayNum = day
        this.initTree(organId, callback)

    }
    fit(geomOrExtent){
        this.kmap.fit(geomOrExtent)
    }
}

export default OwnershipMap
