<template>
    <div id="containerMap" class="containerMap">
      <div class="alarm_list">
        <span class="alarm_list_item" v-for="item in alarm_list"><img :src="alarm_type[item.code].icon"/><span>{{ alarm_type[item.code].name }}</span><span class="alarm_item_brager" :style="{'background-color':alarm_type[item.code].bg}">{{ item.count }}</span></span>
      </div>
      <div class="houselist">
        <span  class="item" @click="toHouse(item)" v-for="item in houselist" :style="{'background-color':alarm_type[item.alarmtype].bg}" >
          <el-tooltip :content="item.name" placement="top" class="custom-tooltip">
            <span class="item">{{ item.code }}</span>
          </el-tooltip>
        </span>
      </div>
      <div class="left">
        <div class="area">
          <div class="title"><span class="line"></span><span>事件分布统计占比</span><span class="stat_rate">(月)</span></div>
          <div class="echartsdiv" ref="echarts01"></div>
        </div>
        <div class="area">
          <div class="title"><span class="line"></span><span>事件趋势</span><span class="stat_rate">(月)</span></div>
          <div class="echartsdiv" ref="echarts02"></div>
        </div>
        <div class="area">
          <div class="title"><span class="line"></span><span>流程督办</span><span class="stat_rate">(月)</span></div>
          <div class="toolsbtn">
            <div class="toolsbtn_item active">总量</div>
            <div class="toolsbtn_item">闭单量</div>
            <div class="toolsbtn_item">未闭单量</div>
          </div>
          <div class="echartsdiv" ref="echarts03" style="height: calc(100% - 69px);"></div>
        </div>
      </div>
      <div ref="infoWindowContent" v-show="showInfoWindow" @click="inHouse">
        <div class="infoWindowContent">
          <div class="linkpoint lefttoppoint"></div>
          <div class="linkpoint righttoppoint"></div>
          <div class="linkpoint leftbottompoint"></div>
          <div class="linkpoint rightbottompoint"></div>
          <div class="camername">{{ currentHouse.camername }}</div>
        </div>
      </div>
      <house ref="houseComp" />
    </div>
</template>
<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import {shallowRef,onMounted} from "vue";
import * as echarts from "echarts";
import House from './components/housecamer.vue'
const map = shallowRef(null);
const AMap = ref();
const echarts01 = ref(null);
const echarts02 = ref(null);
const echarts03 = ref(null);
const echars01data = ref(null);
const echars02data = ref(null);
const echars03data = ref(null);
const infoWindowContent = ref(null);
const showInfoWindow = ref(false);
const currentHouseCode = ref('');
const currentHouse = ref({});
const houseComp = ref(null);
let infoWindow = null;
let geocoder = null;
const alarm_type=ref({
  "none":{
    name:'行为合规',
    bg:'#2488fe',
    icon:'/images/ico_alarm_none.png'
  },
  "smoke":{
    name:'吸烟告警',
    bg:'#ef911c',
    icon:'/images/ico_alarm_smoke.png'
  },
  "fire":{
    name:'异常烟火',
    icon:'/images/ico_alarm_fire.png',
    bg:'#de4a4a'
  },
  "temp":{
    name:'环境异常',
    bg:'#12c9b5',
    icon:'/images/ico_alarm_temp.png'
  },
  "person":{
    name:'人员入侵',
    icon:'/images/ico_alarm_person.png',
    bg:'#833dd9'
  }
})
const alarm_list = ref([{
  code:"none",
  count:0
},{
  code:"smoke",
  count:0
},{
  code:"fire",
  count:0
},{
  code:"temp",
  count:0
},{
  code:"person",
  count:0
}]);

const houselist=ref([{
  name:"自贡中心仓库",
  code:"zg",
  city:"510300",
  addr:"自贡市沿滩区金川路东段28号高新仓储物流园一期",
  lnglat:[0,0],
  alarmtype:"none",
},{
  name:"成都中心仓库",
  code:"cd",
  city:"510100",
  addr:"简阳市石桥镇羊羊小镇大华国际B1栋13楼1322号",
  lnglat:[0,0],
  alarmtype:"smoke",
  camername:"1-10002号摄像头",
}]);

const initHouseLoca=()=>{
  for (let index = 0; index < houselist.value.length; index++) {
    const element = houselist.value[index];
    let address = element.addr;
    getGeoLocation(index,address);
  }
}
const toHouse=(item)=>{
  if(item.lnglat[0]==0||item.lnglat[1]==0) return;
  map.value.setCenter(item.lnglat);
}

const inHouse=()=>{
  houseComp.value.load(currentHouse,alarm_type.value);
}

const getGeoLocation=(houseind,address)=> {
  geocoder.getLocation(address, function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      const lnglat = result.geocodes[0].location; // 经纬度对象
      houselist.value[houseind].lnglat=[lnglat.getLng(),lnglat.getLat()];
      //console.log('经度：', lnglat.getLng(), '纬度：', lnglat.getLat());
      addMarker(houselist.value[houseind],lnglat); // 添加标记到地图上
    } else {
      console.error('获取位置失败');
    }
  });
}

const addMarker=(houseinfo,lnglat) =>{
  // 创建自定义 Marker 的 HTML 内容
  const customMarkerContent = document.createElement('div');
  customMarkerContent.id = houseinfo.code;
  customMarkerContent.className = 'custom-marker'; // 可以添加一些 CSS 类来美化 Marker
  customMarkerContent.innerHTML = '<div class="icon1"></div><div class="icon2"></div><div class="icon '+houseinfo.alarmtype+'"><img src='+alarm_type.value[houseinfo.alarmtype].icon+'></div><div class="housename">'+houseinfo.name+'<img src="/images/aowllow_up.png"></div>'; // 设置内容为红色的方块，显示一个 "X"
  customMarkerContent.style.cursor = 'pointer'; // 设置鼠标样式为指针，表示可点击
  const marker = new AMap.value.Marker({
    position: lnglat, // 经纬度对象
    content:customMarkerContent,
    map: map.value, // 添加到哪个地图实例
    extData:houseinfo,
  });
  marker.on('click',function(e){    
    if(currentHouseCode.value!='' && currentHouseCode.value!=e.target.dom.firstChild.id){
      document.getElementById(currentHouseCode.value).className = "custom-marker";
    }
    let classnames=document.getElementById(e.target.dom.firstChild.id).className;
    if(classnames.indexOf("active")==-1){
      if(infoWindow!=null) infoWindow.close();
      showInfoWindow.value=true;
      currentHouseCode.value=e.target.dom.firstChild.id;
      document.getElementById(currentHouseCode.value).className = "custom-marker active";
      let extdata = e.target.getExtData();
      currentHouse.value = extdata;
      infoWindow.setContent(infoWindowContent.value)
      infoWindow.open(map.value,e.target.getPosition());      
    }else{
      document.getElementById(currentHouseCode.value).className = "custom-marker";
      infoWindow.close();
      showInfoWindow.value=false;
      currentHouseCode.value="";
    }
  });
  map.value.setCenter(lnglat);
}

const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "f3a3cf317c5749d8b2fce022f63def43",
  }
  AMapLoader.load({
    key: 'cf0ede1d8833ccb51fb6b084e23a7b5e', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 'AMap.ToolBar','AMap.Geocoder','AMap.LngLat'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    Loca:{
      version:'2.0.0'
    }
  })
    .then((res) => {
      AMap.value = res
      // 上来就显示的中心点  北京 116.397, 39.918
      var lnglat = new res.LngLat(116.397, 39.918);
      map.value = new res.Map('containerMap', {
        //设置地图容器id
        viewMode: '2D', //是否为3D地图模式
        zoom: 8, //初始化地图级别
        mapStyle:"amap://styles/dark",//深色模式
        center: lnglat, //初始化地图中心点位置
      })
      // 初始化地理编码服务
      geocoder = new AMap.value.Geocoder({
        radius: 1000, // 范围，默认：1000
        extensions: "all" // 返回地址描述对应的详细信息
      });
      infoWindow = new AMap.value.InfoWindow({
        isCustom:true,
        offset: new AMap.value.Pixel(220,-28),
        autoMove:true,
        closewhenClickMap:true,
      });
      map.value.clearMap() // 清除地图覆盖物
      // 地图是否可拖拽和缩放
      map.value.setStatus({
        dragEnable: true, // 是否可拖拽
        zoomEnable: true, // 是否可缩放
      })
      initHouseLoca();
    })
    .catch((e) => {
      console.log('error', e)
    })
}

const initData = ()=>{
  //模拟数据
  echars01data.value=[{
      code:"none",
      name:alarm_type.value["none"].name,
      value:5,
      rate:Math.round(5/12*100)
    },
    {
      code:"smoke",
      name:alarm_type.value["smoke"].name,
      value:1,
      rate:Math.round(1/12*100)
    },
    {
      code:"fire",
      name:alarm_type.value["fire"].name,
      value:2,
      rate:Math.round(2/12*100)
    },
    {
      code:"temp",
      name:alarm_type.value["temp"].name,
      value:Math.round(1/12*100),
      rate:0
    },
    {
      code:"person",
      name:alarm_type.value["person"].name,
      value:3,
      rate:Math.round(4/12*100)
    },
  ];
  echars02data.value=[
    {date:"01",value:"2"},{date:"02",value:"0"},{date:"03",value:"1"},{date:"04",value:"3"},{date:"05",value:"0"},{date:"06",value:"0"},
    ,{date:"07",value:"0"},{date:"08",value:"0"},{date:"09",value:"0"},{date:"10",value:"1"},{date:"11",value:"0"},{date:"12",value:"0"}
  ];
  echars03data.value=[
    {date:"01",value:"2"},{date:"02",value:"0"},{date:"03",value:"1"},{date:"04",value:"3"},{date:"05",value:"0"},{date:"06",value:"0"},
    ,{date:"07",value:"0"},{date:"08",value:"0"},{date:"09",value:"0"},{date:"10",value:"1"},{date:"11",value:"0"},{date:"12",value:"0"}
  ];
  loadEchars01();
  loadEchars02();
  loadEchars03();
}

const loadEchars01=()=>{
  let chartData = {
     roseChart: true,
     colorArr: ['#2186fd', '#dd4949', '#ee901b', '#11c8b4',"#823cd8"],
     data:echars01data.value
  };
  let arr = chartData.data.map(item => item.value);

  function sum(arr) {
     return eval(arr.join("+"));
  };
  let legendObj = {};
  for (let i = 0; i < chartData.data.length; i++) {
     legendObj['d' + i] = {
        width: 10,
        height: 10,
        lineHeight: (chartData.setFont || 16) * 2,
        borderRadius: 10,
        backgroundColor: `rgb(${chartData.colorArr[i]})`,
     };
     legendObj['p' + i] = {
        fontSize: chartData.setFont || 16,
        padding: [0, 0, 0, 20],
        color: `rgb(${chartData.colorArr[i]})`,
     };
  }
  let option = {
     backgroundColor: '#00000000',
     color: chartData.colorArr,
     grid: {
        left: 5,
        right: 5,
        bottom: 5,
        top: 5,
        containLabel: true
     },
     title: {
        show: true,
        text: '{a|总量}\n{b|' + sum(arr) + '}',
        x: '30%',
        y: '43%',
        textStyle: {
           rich: {
              a: {
                 align: 'center',
                 fontSize: 12,
                 color: '#fff',
                 padding: [0, 0, 10, 0],
              },
              b: {
                 align: 'center',
                 fontSize: 14,
                 color: '#fff'
              },
           },
        }
     },
     legend: {
        height: '100%',
        icon: 'circle',
        orient: 'vertical',
        right: 10,
        bottom: 'center',
        itemWidth: 0,
        itemHeight: 0,
        itemGap: 10,
        textStyle: {
           rich: {
              n: {
                 padding: [0, 0, 0, 10],
                 lineHeight: chartData.setFont || 12,
                 fontSize: chartData.setFont || 12,
                 color: "#fff",
              },
              ...legendObj
           }
        },
        formatter: function (name) {
           let index = 0;
           let d = chartData.data.filter((item, i) => {
              if (item.name == name) {
                 index = i;
                 return item;
              }
           });
           let p = d[0].value / sum(arr) * 100;
           return `{d${index}|}{n|${name}}`;
        },
     },
     tooltip: {
        trigger: 'item',
        formatter: '{b}：{c}（{d}%）'
     },
     series: [{
        type: 'pie',
        clockwise: false,
        startAngle: 90,
        radius: ['35%', '55%'],
        center: ['35%', '50%'],
        hoverAnimation: false,
        roseType: chartData.roseChart ? 'radius' : false,
        data: chartData.data,
        itemStyle: {
           color: (param) => {
              let i = param.dataIndex;
              return  chartData.colorArr[i] 
           },
           opacity: .9
        },
        label: {
           show: false
        },
        labelLine: {
           show: false
        }
     }]
  };
  echarts.init(echarts01.value).setOption(option);
}
const loadEchars02=()=>{
  const dataX = [];
  const y = [];
  echars02data.value.map(item=>{
    dataX.push(item.date);
    y.push(item.value);
  })
  let option = {
    backgroundColor: '#00000000',
    grid: {
        left: 5,
        right: 5,
        bottom: 5,
        top: 15,
        containLabel: true
    },
    tooltip: { // 提示框组件
        trigger: 'axis', // 触发类型
        textStyle: {
           fontSize: 12 // 文字像素
        },
    },
    xAxis: {
        data: dataX, // 数据
        min: 0, // 最小值
        type: 'category',
        boundaryGap: true, // 开始和结尾是否隔开
        axisLabel: {
           textStyle: {
              color: '#5d646b', // 文字颜色
              fontSize: 12 // 文字像素
           }
        },
        axisLine: {
           show: false // 是否显示坐标轴轴线
        },
        axisTick: {
           show: false // 去除刻度线
        }
     },
     yAxis: {
        type: 'value',
        name: "单位：次",
        min: 0, // 最小值
        axisLine: {
           show: false
        },
        axisLabel: {
           textStyle: {
              color: '#5d646b', // 文字颜色
              fontSize: 12 // 文字像素
           }
        },
        // y轴分割线的颜色
        splitLine: {
           lineStyle: {
              color: '#575f66', // 分割线的颜色
              type: 'dashed',
           }
        }
     },
     series: [
        {
           type: 'line',
           symbolSize: 8, // 设置拐点大小
           symbol:'circle',
           label: {
              show: true, // 线条折点处显示值
              position: 'top', // 标签的位置
              color: "#5d646b", // 文字颜色
              fontSize: 12, // 文字像素
           },
           // 填充颜色设置
           areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                 { offset: 1, color: 'rgba(72,115,255,0.2)' },  //开始的颜色
                 { offset: 0, color: 'rgba(234,233,255,0.2)' }  //结束的颜色
              ]),
           },
           // 设置拐点颜色以及边框
           itemStyle: {
              color: '#2084fa'
           },
           lineStyle: {
              width: 2, // 线的宽度              
           },
           tooltip: {
              valueFormatter: function (value) {
                 return value;
              }
           },
           data: y
        },
     ]
  };
  echarts.init(echarts02.value).setOption(option);
}
const loadEchars03=()=>{
  var gain = 0.9;
  var gap = 0;
  let maxvalue=0;
  //柱子数据
  var data = [];
  var dataX = [];
  echars03data.value.map(item=>{
    dataX.push(item.date);
    data.push(item.value);
    if (maxvalue.length>1){
      maxvalue = Math.max(maxvalue,item.value);
    }
  })
  maxvalue =maxvalue+2;
  var option = {
      backgroundColor: '',
      tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          }
        },
    grid: {
      left: '3%',
      top: '10%',
      right: '2%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(160,160,160,0.3)'
          }
        },
        axisLabel: {
          textStyle:{
              fontSize:12,
              color:'#5a6268'
          }
        },
        data: dataX
      },
      {
        type: 'category',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle:{
              fontSize:12,
              color:'#fff'
          }
        },
        splitArea: {
          show: false
        },
        splitLine: {
          show: false
        },
        data: []
      }
    ],
    yAxis: {
      type: 'value',      
      nameTextStyle: {
        color: '#ffffff',
        fontSize: 12
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      splitLine: {
           lineStyle: {
              color: '#575f66', // 分割线的颜色
              type: 'dashed',
           }
      },
      axisLabel: {
        textStyle: {
          color: '#5a6268',
          fontSize: 12
        }
      }
    },
    series: [
      {
        type: 'bar',
        xAxisIndex: 1,
        itemStyle: {
          normal: {
            show: true,
            color: "#2186fd00",
            barBorderRadius: 50,
            borderWidth: 0,
            borderColor: '#333'
          }
        },
        barWidth: '30%',
        data: [maxvalue, maxvalue, maxvalue, maxvalue,maxvalue, maxvalue, maxvalue, maxvalue,maxvalue, maxvalue, maxvalue, maxvalue]
      },
      {
        type: 'bar',
        itemStyle: {
          normal: {
            show: true,
            color: "#2186fd",
            barBorderRadius: 50,
            borderWidth: 0,
            borderColor: '#333'
          }
        },
        label: {
          normal: {
            show: true,
            position: 'top',
            textStyle: {
                  fontSize: 12
              }
          }
        },
        barWidth: '30%',
        data: data
      }
    ]
  };
  echarts.init(echarts03.value).setOption(option);
}
onMounted(() => {
  const userinfo = JSON.parse(sessionStorage.getItem("user")||'{}');
  if (userinfo.userName!=null) {
    let tmplst =[];
    for (let index = 0; index <  houselist.value.length; index++) {
      const element =  houselist.value[index];
      if(userinfo.userName=='admin'|| userinfo.userName=='sc'|| element.code==userinfo.userName){
        tmplst.push(element)
      }
    }
    houselist.value = tmplst;
  }
  initMap();
  initData();
})
</script>
<style>
.custom-tooltip .el-tooltip__popper {
  background-color: #484e58 !important; /* 修改为你的颜色 */
}
.custom-marker{
      display: grid;
      color: #fff;
      font-size: 12px;
      .icon1,.icon2{
        display: none;
      }
      .housename{
          width: 140px;
          margin-left: -55px;
          text-align: center;
          background: #484e58;
          margin-top: 42px;
          padding: 3px 5px;
          border-radius: 18px;
          position: relative;
          position: absolute;
          z-index: 1;
          img{
            position: absolute;
            left: 50%;
            width: 10px;
            height: 6px;
            margin-left: -4px;
            top: -6px;
          }
      }
      .icon{
        border : 1px solid #fff;
        width: 32px;
        height: 32px;
        border-radius: 50%;  
        display: flex;
        justify-content: center;
        justify-items: center;
        position: absolute;
        z-index: 1;
        img{
          width: 24px;
          height: 24px;
          margin-top: 4px;
        }         
      }
      .none{
        background-color: #2287fe;     
      }
      .fire{
        background-color: #dd4949;  
      }
      .smoke{
        background-color: #ef911c;
      }
      .temp{
        background-color: #12c9b5;
      }
      .person{
        background-color: #833dd9;
      }
}

.custom-marker.active{
      display: grid;
      color: #fff;
      font-size: 12px;
      .icon1,.icon2{
        display: block;
        position: absolute;
        z-index: 0;
      }
      .icon1{
        width: 90px;
        height: 90px;
        background: transparent;
        border: 2px solid #4b3c2a;
        border-radius: 50%;
        left: -29px;
        top: -29px;
      }
      .icon2{
        width: 60px;
        height: 60px;
        background: #9a6523;
        border-radius: 50%;
        top: -14px;
        left: -14px;
      }
      .housename{
          width: 140px;
          margin-left: -55px;
          text-align: center;
          background: #484e58;
          margin-top: 70px;
          padding: 3px 5px;
          border-radius: 18px;
          position: relative;
          position: absolute;
          z-index: 1;
          img{
            position: absolute;
            left: 50%;
            width: 10px;
            height: 6px;
            margin-left: -4px;
            top: -6px;
          }
      }
      .icon{
        border : 1px solid #fff;
        width: 32px;
        height: 32px;
        border-radius: 50%;  
        display: flex;
        justify-content: center;
        justify-items: center;
        position: absolute;
        z-index: 1;
        img{
          width: 24px;
          height: 24px;
          margin-top: 4px;
        }         
      }
      .none{
        background-color: #2287fe;     
      }
      .fire{
        background-color: #dd4949;  
      }
      .smoke{
        background-color: #ef911c;
      }
      .temp{
        background-color: #12c9b5;
      }
      .person{
        background-color: #833dd9;
      }
}
.infoWindowContent{
  border: 2px solid #fff;
  position: relative;
  width: 380px;
  height: 260px;
  border-radius: 5px;
  background: #0000003b;
  .camername{
        height: 26px;
        width: auto;
        line-height: 16px;
        position: absolute;
        left: 5px;
        top: 5px;
        font-size: 12px;
        background-color: #0000004f;
        color: #fff;
        padding: 5px 15px;
        border-radius: 20px;
  }
  .linkpoint{
    width: 10px;
    height: 10px;
    position: absolute;
    border: 3px solid #fff;    
    z-index: 1;
    border-radius: 50%;
  }
  .lefttoppoint{
    top: -8px;
    left: -8px;
  }
  .righttoppoint{
    top: -8px;
    right: -8px;
  }
  .leftbottompoint{
    bottom: -8px;
    left: -8px;
  }
  .rightbottompoint{
    bottom: -8px;
    right: -8px;
  }
}
</style>
<style lang='scss' scoped>
.containerMap{
    width: 100%;
    height: calc(100vh - 60px);
    position: relative;
    .alarm_list{
      position: absolute;
      z-index: 10;
      display: flex;
      left: 75px;
      top: 40px;
      .alarm_list_item{
        position: relative;
        margin: 0 5px;
        padding: 6px 20px;
        border-radius: 30px;
        color: #fff;
        background-color: #455b6d;
        img{
          width: 24px;
          height: 24px;
          vertical-align: middle;
        }
        .alarm_item_brager{
          position: absolute;
          font-weight: bold;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          text-align: center;
          line-height: 24px;
          top: -13px;
          right: 0;
          font-size: 12px;
        }
      }
    }
    .houselist{
      position: absolute;
      bottom: 20px;
      left: 75px;
      display: flex;
      z-index: 10;
      color: #fff;
      .item{
        cursor: pointer;
        border-radius: 3px;
        margin: 3px;
        padding:5px 5px;
        text-align: center;
        font-weight: bold;
        .item:hover{
          padding:20px 5px;
        }
      }
    }
    .left{
      position: fixed;
      right: 0;
      top: 60px;
      z-index: 10;
      width: 300px;
      background-color:#03030366;
      height: calc(100% - 60px);
      .area{
        height: 33.3%;
        width: 100%;
        .title{
          background-color: #192733;
          font-size: 14px;
          font-weight: bold;
          color: #fff;
          height: 35px;
          line-height: 15px;
          padding: 10px;
          display: flex;
          .line{
            width: 5px;
            height: 15px;
            background-color: #fff;
            border-radius: 5px;
            margin-right: 10px;
          }
          .stat_rate{
            color: #47576a;
            font-size: 12px;
            margin-left: 5px;
          }
        }
        .toolsbtn{
          height: 24px;
          width: 100%;
          display: flex;
          margin-top: 10px;
          margin-left: 10px;
          line-height: 15px;
          margin-right: 2px;
          cursor: pointer;
          .toolsbtn_item{
            display: inline-block;
            padding: 5px 10px;
            background-color: #262f38;
            color: #686f75;
            font-size: 12px;
          }
          .toolsbtn_item.active,.toolsbtn_item:hover{
            background-color: #2184fa;
            color: #fff;
          }
        }
        .echartsdiv{
          height: calc(100% - 35px);
          width: 100%;
        }
      }
    }
}
</style>
