import * as Cesium from 'cesium'
import DialogPropertyGrid from '../DialogPropertyGrid';
import { setPropertyData } from '../DialogPropertyGrid/property';
import FeatureGroundPrimitive from '@/components/CesiumMap/FeatureGroundPrimitive';
import { getDistance, getArea, getBoundingCenterCoordinate, getBoundingCenter } from '@/components/CesiumMap/mixins/useMeasureTool';
import { parseTime } from '@/utils/ruoyi';

import fireWarningIcon from '@/assets/icons/fire_warning.png';
import fireRangerIcon from '@/assets/icons/fire_ranger.png';
import firePtzIcon from '@/assets/icons/fire_ptz.png';
import fireBayonetIcon from '@/assets/icons/fire_bayonet.png';
import fireAirportIcon from '@/assets/icons/fire_airport.png';
import fireHotIcon from '@/assets/icons/fire_hot.png';
import fireWarehouseIcon from '@/assets/icons/fire_warehouse.png';

// 绘制火情点
const drawWarning = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    // 获取当前时间
    const time = new Date()
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: fireWarningIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(255, 0, 0).withAlpha(0.4),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'warning',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
        discoveryTime: parseTime(time),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制巡护路线
const drawTrack = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPolyline().then((positions) => {
    // 计算中心点坐标
    const position = getBoundingCenter(positions, 100);
    
    const entity = toolbarLayer?.entities.add({
      position,
      polyline: {
        positions,
        width: 8,
        material: Cesium.Color.fromCssColorString('#DCE057'),
        clampToGround: true,
      },
      label: {
        text: '',
        font: '14px Sans-Serif',
        fillColor: Cesium.Color.fromCssColorString('#DCE057'),
        outlineColor: Cesium.Color.fromCssColorString('#FFFFFF'),
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        pixelOffset: new Cesium.Cartesian2(0, -5),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
      },
      properties: {
        __type: 'track',
        length: getDistance(positions).toFixed(2),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制护林员（点）
const drawRanger = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: fireRangerIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(155, 206, 255).withAlpha(0.15),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'ranger',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制云台（点）
const drawPtz = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: firePtzIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(35, 206, 235).withAlpha(0.45),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'ptz',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制卡口（点）
const drawBayonet = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: fireBayonetIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(233, 189, 128).withAlpha(0.45),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'bayonet',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制热点
const drawHot = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: fireHotIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(255, 0, 0).withAlpha(0.4),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'hot',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制无人机机场（点）
const drawAirport = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: fireAirportIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(164, 255, 147).withAlpha(0.4),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'airport',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制水源地（面）
const drawWatersource = (options) => {
  const { drawTool, measureTool, viewer, primitiveList } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPolygon().then((positions) => {
    // 计算中心点坐标
    const center = getBoundingCenterCoordinate(positions);

    // // 添加水源地实体
    // const entity = toolbarLayer?.entities.add({
    //   // polyline: {
    //   //   positions:[...positions, positions[0]], // 闭合多边形
    //   //   width: 2,
    //   //   material: Cesium.Color.BLUE,
    //   // },
    //   polygon: {
    //     hierarchy: positions,
    //     material: riverMaterial,
    //     // material: Cesium.Color.BLUE.withAlpha(0.5),
    //   },
    //   properties: {
    //     __type: 'watersource',
    //     name: '',
    //     area: getArea(positions).toFixed(2), // 面积
    //     longitude: center[0].toFixed(6),
    //     latitude: center[1].toFixed(6),
    //     volume: 0 // 储水量，默认0
    //   }
    // });

    const waterMaterial = new Cesium.Material({
      fabric: {
        type: 'Water',
        uniforms: {
          normalMap: Cesium.buildModuleUrl('Assets/Textures/waterNormals.jpg'),
          baseWaterColor: new Cesium.Color(
            64 / 255.0,
            157 / 255.0,
            253 / 255.0,
            0.6
          ),
          // blendColor: new Cesium.Color(0.0, 0.5, 1.0, 1.0),
          // frequency: 10.0,
          // animationSpeed: 0.05,
          // amplitude: 10,
          // specularIntensity: 0.5,
          // alpha: 0.1
          frequency: 1000.0,
          animationSpeed: 0.1,
          amplitude: 10,
          specularIntensity: 1.5,
        }
      }
    });

    const waterPrimitive = new FeatureGroundPrimitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: new Cesium.PolygonHierarchy(positions),
            vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
        })
      }),
      appearance: new Cesium.EllipsoidSurfaceAppearance({
        material: waterMaterial,
      })
    }, {
      __type: 'watersource',
      name: '',
      area: getArea(positions).toFixed(2), // 面积
      longitude: center[0].toFixed(6),
      latitude: center[1].toFixed(6),
      volume: 0 // 储水量，默认0
    });

    // 将 Primitive 添加到场景中
    viewer.scene.primitives.add(waterPrimitive);
    primitiveList.push(waterPrimitive);

    // 编辑属性
    DialogPropertyGrid.show(waterPrimitive, (data) => {
      // 更新实体属性
      setPropertyData(data, waterPrimitive);
      // 调用接口
    });
  });
};

// 绘制仓库（点）
const drawWarehouse = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPoint().then((position) => {
    // 计算中心点坐标
    const center = Cesium.Cartographic.fromCartesian(position);
    
    const entity = toolbarLayer?.entities.add({
      position,
      billboard: {
        image: fireWarehouseIcon,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, 18), // 可选偏移
      },
      label: {
        text: '',
        font: '14px sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, 18 - 96 - 6),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        showBackground: true,
        backgroundColor : Cesium.Color.fromBytes(155, 206, 255).withAlpha(0.4),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
      },
      properties: {
        __type: 'warehouse',
        name: '',
        longitude: Cesium.Math.toDegrees(center.longitude).toFixed(6),
        latitude: Cesium.Math.toDegrees(center.latitude).toFixed(6),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制林区道路
const drawRoad = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPolyline().then((positions) => {
    // 计算中心点坐标
    const position = getBoundingCenter(positions, 100);
    
    const entity = toolbarLayer?.entities.add({
      position,
      polyline: {
        positions,
        width: 5,
        material: new Cesium.PolylineOutlineMaterialProperty({
          color: Cesium.Color.fromCssColorString('#fecd78'),
          outlineColor: Cesium.Color.fromCssColorString('#d29661'),
          outlineWidth: 2,
        }),
        clampToGround: true,
      },
      label: {
        text: '',
        font: '14px Sans-Serif',
        fillColor: Cesium.Color.fromCssColorString('#fecd78'),
        outlineColor: Cesium.Color.fromCssColorString('#FFFFFF'),
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        pixelOffset: new Cesium.Cartesian2(0, -5),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
      },
      properties: {
        __type: 'road',
        length: getDistance(positions).toFixed(2),
      }
    });
    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

// 绘制重点区域（面）
const drawKeyarea = (options) => {
  const { drawTool, measureTool, toolbarLayer } = options;
  if(!drawTool) {
    console.error('绘制工具未初始化');
    return;
  }

  drawTool.abort();
  measureTool.abort();
  drawTool.drawPolygon().then((positions) => {
    // 计算中心点坐标
    const center = getBoundingCenterCoordinate(positions);

    // 添加实体
    const entity = toolbarLayer?.entities.add({
      position: Cesium.Cartesian3.fromDegrees(center[0], center[1], 100),
      label: {
        text: '',
        font: '14px Sans-Serif',
        fillColor: Cesium.Color.RED,
        outlineColor: Cesium.Color.fromCssColorString('#FFFFFF'),
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        pixelOffset: new Cesium.Cartesian2(0, -5),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
      },
      polyline: {
        positions:[...positions, positions[0]], // 闭合多边形
        width: 2,
        material: Cesium.Color.RED,
        clampToGround: true,
      },
      polygon: {
        hierarchy: positions,
        material: Cesium.Color.RED.withAlpha(0.3),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      },
      properties: {
        __type: 'keyarea',
        area: getArea(positions).toFixed(2), // 面积
        longitude: center[0].toFixed(6),
        latitude: center[1].toFixed(6),
      }
    });

    // 编辑属性
    DialogPropertyGrid.show(entity, (data) => {
      // 更新实体属性
      setPropertyData(data, entity);
      // 调用接口
    });
  });
};

export {
  drawWarning,
  drawTrack,
  drawRanger,
  drawPtz,
  drawBayonet,
  drawAirport,
  drawHot,
  drawWarehouse,
  drawWatersource,
  drawRoad,
  drawKeyarea,
}
