<template>
  <div class="app-container home">
    <el-row :gutter="20" style="margin-bottom: 25px;">
      <el-col :span="6">
        <div style="display: flex;width: 100%;height:80px;align-items: center;border-radius: 12px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);">
         <div style="display: flex;width: 80px;height: 80px;background: #0152a5;align-items: center;justify-content: center;border-radius: 12px 0 0 12px;color: #0152a5;">
          <img src="../assets/images/xms.png" width="50" height="50" />
         </div>
         <div style="flex: 1;text-align: center;">
          <div style="font-size: 40px;color: #0152a5;">{{xmtotal}}</div>
          <div style="font-size: 16px;">项目数</div>
         </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div style="display: flex;width: 100%;height:80px;align-items: center;border-radius: 12px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);">
         <div style="display: flex;width: 80px;height: 80px;background: #28b3a1;align-items: center;justify-content: center;border-radius: 12px 0 0 12px;color: #0152a5;">
          <img src="../assets/images/sheb.png" width="50" height="50" />
         </div>
         <div style="flex: 1;text-align: center;">
          <div style="font-size: 40px;color: #28b3a1;">{{sbtotal}}</div> 
          <div style="font-size: 16px;">设备数</div>
         </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div style="display: flex;width: 100%;height:80px;align-items: center;border-radius: 12px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);">
         <div style="display: flex;width: 80px;height: 80px;background: #67c23a;align-items: center;justify-content: center;border-radius: 12px 0 0 12px;color: #0152a5;">
          <img src="../assets/images/zaix.png" width="50" height="50" />
         </div>
         <div style="flex: 1;text-align: center;">
          <div style="font-size: 40px;color: #67c23a;">{{onlinnum}}</div>
          <div style="font-size: 16px;">在线数</div>
         </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div style="display: flex;width: 100%;height:80px;align-items: center;border-radius: 12px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);">
         <div style="display: flex;width: 80px;height: 80px;background: #e6a23c;align-items: center;justify-content: center;border-radius: 12px 0 0 12px;color: #0152a5;">
          <img src="../assets/images/guz.png" width="50" height="50" />
         </div>
         <div style="flex: 1;text-align: center;">
          <div style="font-size: 40px;color: #e6a23c;">{{gznum}}</div>
          <div style="font-size: 16px;">故障数</div>
         </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-row :gutter="20">
          <el-col :span="12">
            <div ref="socChart"  style="height: 260px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
          </el-col>
          <el-col :span="12">
            <div ref="gzdjChart" style="height: 260px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
          </el-col>
        </el-row>
        
      </el-col>
      <el-col :span="12">
        <div ref="cfdChart" style="height: 260px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
      </el-col>
    </el-row>
    <div id="shebmap"  style="height: 600px;margin: 25px 0;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
    <el-row :gutter="20">
      <el-col :span="6">
        <div  style="padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;">
          <el-descriptions 
            size="large"
            title="" 
            border 
            :column="1" 
            label-width="200"
          
          >
            <el-descriptions-item align="center" label="累计运行时间(h)">{{runtimeSummary.totalRunHours}}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计充电时间(h)">{{runtimeSummary.totalChargeHours}}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计放电时间(h)">{{runtimeSummary.totalDischargeHours}}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计充电能量(kWh)">{{runtimeSummary.totalChargeEnergyKWh}}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计放电能量(KWh)">{{runtimeSummary.totalDischargeEnergyKWh}}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计放电容量(Ah)">{{runtimeSummary.totalDischargeCapacityAh}}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计充电容量(Ah)">{{runtimeSummary.totalChargeCapacityAh}}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-col>
      <el-col :span="18">
       <div ref="yxscChart" style="height: 355px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
      </el-col>
    </el-row>
  </div>
  <el-drawer 
    v-model="dcdrawer"
    size="50%" 
    title="" 
    :with-header="false">
    <el-divider content-position="left" style="margin-bottom: 30px;">
      <div style="font-size: 18px;color: #278ed9;">电池信息</div>
    </el-divider>
    <el-descriptions title="" border>
      <el-descriptions-item label="设备名称">{{sbinfor.deviceName}}</el-descriptions-item>
      <el-descriptions-item label="设备ID">{{sbinfor.deviceId}}</el-descriptions-item>
      <el-descriptions-item label="设备SN">{{sbinfor.deviceSn}}</el-descriptions-item>
      <el-descriptions-item label="设备类型">{{sbinfor.deviceType}}</el-descriptions-item>
      <el-descriptions-item label="固件版本">{{sbinfor.firmwareVersion}}</el-descriptions-item>
      <el-descriptions-item label="设备状态">{{sbinfor.status}}</el-descriptions-item>
    </el-descriptions>
    <el-divider content-position="left" style="margin-bottom: 30px;">
      <div style="font-size: 18px;color: #278ed9;">电池轨迹</div>
    </el-divider>
    <div v-if="dcdrawer" id="wzmap"  style="height: 600px;margin: 25px 0;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
  </el-drawer>
</template>

<script setup name="Index">

import * as echarts from 'echarts'

import {
  gettotal,
  getloca,
  equdata,
  equfenbu,
  equguiji
} from '@/api/home'

 let xmtotal = ref(0)
 let sbtotal = ref(0)
 let onlinnum = ref(0) 
 let gznum = ref(0)

 let runtimeSummary = ref({})

 let sbdata = []

let markerlist = []

let yxscx = []
let yxscy = []
nextTick(() => {
  equdata().then(rps => {

    xmtotal.value = rps.data.summary.projectCount
    sbtotal.value = rps.data.summary.deviceCount
    onlinnum.value = rps.data.summary.onlineCount
    gznum.value = rps.data.summary.faultCount

    runtimeSummary.value = rps.data.runtimeSummary

    sbdata = rps.data.socDistribution

    if(rps.data.trend && rps.data.trend.length > 0){
      daycfd.value = rps.data.trend.map(n => {
        return n.date
      }) 
      chond.value = rps.data.trend.map(n => {
        return n.chargeDuration
      })
      fangd.value = rps.data.trend.map(n => {
        return n.dischargeDuration
      })
    }
    
    if(rps.data.runtimeDuration && rps.data.runtimeDuration.length > 0){
      yxscx = rps.data.runtimeDuration.map(n => {
        return n.name
      })

      yxscy = rps.data.runtimeDuration.map(n => {
        return n.value
      })
    }
    


    sbinit()
    gzdjinit()
    ricfdinit()
    yxscinit()
  })
  
 
  //positionmap()
  equfenbu().then(rps => {
    
   

    if(rps.data && rps.data.length > 0){
      rps.data.forEach(n => {
        markerlist.push({
          id:n.device.deviceId,
          styleId: 'marker',
          position: new TMap.LatLng(n.location?n.location.latitude:'',n.location?n.location.longitude:'')   //(39.954104, 116.357503),
        }) 
        // {
        //   id: 1,
        //   styleId: 'marker',
        //   position: new TMap.LatLng(39.954104, 116.357503),
        //   // properties: {
        //   //   title: 'marker1'
        //   // },
        //   src:'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
        // }  
      })
      
    }
    

    addmarker()
  })
  
})


function getDaysAgoTimestamp(days) {
  return Date.now() - days * 24 * 60 * 60 * 1000;
}

gettotal()

//getloca('137PBP1M11001AFCF0000006',getDaysAgoTimestamp(7),Date.now())


//设备SOC
const socChart = ref()
  let sbChart
function sbinit() {
  
  if (socChart.value) {
    //初始化echarts实例
    sbChart = echarts.init(socChart.value);
    // 指定图表的配置项和数据
    const option = {
      title: {
        text: '设备SOC',
        left: 'center',
        textStyle: {
            color: '#2363a5',
            fontSize: 16
        }
      },
      // grid: {
      //   left: '3%',
      //   top:'20%',
      //   right: '4%',
      //   bottom: '3%',
      //   containLabel: true
      // },
      label: {
          show: true, // 显示标签
          formatter: '{b}({c})'//'{b}({d}%)' // 使用 formatter 来格式化标签，其中 {b} 是名称，{d} 是百分比，{@2019} 是对应年份的数据值（如果需要的话）
      },
      tooltip: {
        trigger: "item",
      },
      // legend: {
      //   type: "scroll",
      //   orient: "horizontal",
      //   left: "center",
      //   bottom: 0,
      // },
      series: [
        {
          name: "数量",
          type: "pie",
          top:'10%',
          radius: ['40%','70%'],
          data: sbdata,
          padAngle: 2,
          emphasis: {
            itemStyle: {
              paddingTop:'20px',
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            },
          },
          itemStyle:{
            borderRadius: 3
          }
        },
      ],
    };
    // 使用刚指定的配置项和数据显示图表。
    sbChart.setOption(option);
  }
}

//故障等级
const gzdjChart = ref()
let gzdjChar
let gzdjdata = [
  {
    name:'正常',
    value:80
  },
  {
    name:'一级故障',
    value:1
  },
  {
    name:'二级故障',
    value:10
  },
  {
    name:'三级故障',
    value:15
  }
]

function gzdjinit() {
  if (gzdjChart.value) {
    //初始化echarts实例
    gzdjChar = echarts.init(gzdjChart.value);
    // 指定图表的配置项和数据
    const option = {
      title: {
        text: '故障等级',
        left: 'center',
        textStyle: {
            color: '#cd7509',
            fontSize: 16
        }
      },
      // grid: {
      //   left: '3%',
      //   top:'20%',
      //   right: '4%',
      //   bottom: '3%',
      //   containLabel: true
      // },
      label: {
          show: true, // 显示标签
          formatter: '{b}({c})' // 使用 formatter 来格式化标签，其中 {b} 是名称，{d} 是百分比，{@2019} 是对应年份的数据值（如果需要的话）
      },
      tooltip: {
        trigger: "item",
      },
      // legend: {
      //   type: "scroll",
      //   orient: "horizontal",
      //   left: "center",
      //   bottom: 0,
      // },
      series: [
        {
          name: "数量",
          type: "pie",
          top:'10%',
          radius: ['40%','70%'],
          data: gzdjdata,
          padAngle: 2,
          emphasis: {
            itemStyle: {
              paddingTop:'20px',
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            },
          },
          itemStyle:{
            borderRadius: 3
          }
        },
      ],
    };
    // 使用刚指定的配置项和数据显示图表。
    gzdjChar.setOption(option);
  }
}
//const version = ref('3.9.0')

// function goTarget(url) {
//   window.open(url, '__blank')
// }


//日充放电
const cfdChart = ref();
let chongfChart

let daycfd = ref([])
let chond = ref([])
let fangd = ref([])
function ricfdinit() {
  if (cfdChart.value) {
    //初始化echarts实例
    chongfChart = echarts.init(cfdChart.value);
    // 指定图表的配置项和数据
    const option = {
      title: {
        text: "日充放时长",
        left: "center",
        textStyle: {
            color: '#2363a5',
            fontSize: 16
        }
      },
      grid: {
        left: '3%',
        top:'25%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          crossStyle: {
            color: "#999",
          },
        },
      },
      // toolbox: {
      //   feature: {
      //     dataView: { title: "数据视图", show: true, readOnly: false },
      //     magicType: {
      //       title: { line: "折线图", bar: "柱状图" },
      //       show: true,
      //       type: ["line", "bar"],
      //     },
      //     restore: { title: "刷新", show: true },
      //     saveAsImage: { title: "下载", show: true },
      //   },
      // },
      legend: {
        data: [ "充电", "放电"],
        top:25
      //bottom: 0,
      },
      xAxis: [
        {
          type: "category",
          data: daycfd.value, //["2025-01-12", "2025-01-13", "2025-01-14", "2025-01-15", "2025-01-16", "2025-01-17", "2025-01-18"],
          axisPointer: {
            type: "shadow",
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          name: "",
          // min: 0,
          // max: 50,
          // interval: 50,
          axisLabel: {
            formatter: "{value}s",
          },
        },
      ],
      series: [
        {
          name: "充电",
          type: "bar",
          tooltip: {
            valueFormatter: function (value) {
              return value;
            },
          },
          barWidth:'20px',
          data:chond.value,   //[80.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
          itemStyle: {
          //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              normal: {
                  //柱形图圆角，初始化效果
                  // 第一个值表示顶部的左上角，第二个值表示顶部右上角
                  // 第三个值表示底部左下角，第四个值表示底部右下角
                  barBorderRadius:[20,20,0,0]
              }
          }
        },
        {
          name: "放电",
          type: "bar",
          tooltip: {
            valueFormatter: function (value) {
              return value 
            },
          },
          data:fangd.value, //[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
          barWidth:'20px',
          itemStyle: {
          //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              normal: {
                  width:'10px',
                  //柱形图圆角，初始化效果
                  // 第一个值表示顶部的左上角，第二个值表示顶部右上角
                  // 第三个值表示底部左下角，第四个值表示底部右下角
                  barBorderRadius:[20,20,0,0]
              }
          }
        },

      ],
    };
    // 使用刚指定的配置项和数据显示图表。
    chongfChart.setOption(option);
  }
};


//电池信息弹框
let dcdrawer = ref(false)
let sbinfor =ref({})
//添加电池标记
function addmarker() {
        //初始化地图
        let map = new TMap.Map('shebmap', {
            //center: new TMap.LatLng(39.984104, 116.307503),//设置中心点坐标
            zoom:8
        })
        
        //初始化marker
        let marker = new TMap.MultiMarker({
            id: 'marker-layer',
            map: map,
            styles: {
                marker: new TMap.MarkerStyle({
                  width: 25,
                  height: 35,
                  anchor: { x: 16, y: 32 },
                  //src:'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
                })
            },
            geometries:markerlist
        })

        marker.on('click', (v) => {
          dcdrawer.value = true
          nextTick(() => {
            //getDaysAgoTimestamp(7),Date.now()
            equguiji(v.geometry.id,1768040591000,1769027619000).then(rps => {
              sbinfor.value = rps.data
              if(sbinfor.value.trackList && sbinfor.value.trackList.length > 0){
                 sbinfor.value.trackList.forEach(n => {
                  pathlist.value.push(new TMap.LatLng(n.latitude, n.longitude))
                })
              }

              positionmap()
            })
          })
          
          console.log(v)
        })

         //初始化
        let bounds = new TMap.LatLngBounds()
        
        //设置自适应显示marker
        //判断标注点是否在范围内
        markerlist.forEach(function(item){
            //若坐标点不在范围内，扩大bounds范围
            if(bounds.isEmpty() || !bounds.contains(item.position)){
                bounds.extend(item.position)
            }
        })
        //设置地图可视范围
        map.fitBounds(bounds, {
            padding: 100 // 自适应边距
        })
        

}


//位置信息
let pathlist = ref([])
function positionmap() {
    
  //let center = new TMap.LatLng(39.984104, 116.307503);
  // 初始化地图
  let map = new TMap.Map( document.getElementById('wzmap'), {
    zoom: 10,
    //center: center,
  });


  let polylineLayer = new TMap.MultiPolyline({
    map, // 绘制到目标地图
    // 折线样式定义
    styles: {
      style_blue: new TMap.PolylineStyle({
        color: '#3777FF', // 线填充色
        width: 4, // 折线宽度
        borderWidth: 2, // 边线宽度
        borderColor: '#FFF', // 边线颜色
        lineCap: 'round', // 线端头方式
        eraseColor: 'rgba(190,188,188,1)',
      }),
    },
    geometries: [
      {
        id: 'erasePath',
        styleId: 'style_blue',
        paths: pathlist.value,
      },
    ],
  });

  let marker = new TMap.MultiMarker({
    map,
    styles: {
      'car-down': new TMap.MarkerStyle({
        width: 40,
        height: 40,
        anchor: {
          x: 20,
          y: 20,
        },
        faceTo: 'map',
        rotate: 180,
        src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/car.png',
      }),
      start: new TMap.MarkerStyle({
        width: 25,
        height: 35,
        anchor: { x: 16, y: 32 },
        src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png',
      }),
      end: new TMap.MarkerStyle({
        width: 25,
        height: 35,
        anchor: { x: 16, y: 32 },
        src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png',
      }),
    },
    geometries: [
      {
        id: 'car',
        styleId: 'car-down',
        position: pathlist.value[0],
      },
      {
        id: 'start',
        styleId: 'start',
        position: pathlist.value[0],
      },
      {
        id: 'end',
        styleId: 'end',
        position: pathlist.value[pathlist.value.length -1],
      },
    ],
  })

  //初始化
  let bounds = new TMap.LatLngBounds()
  
  //设置自适应显示marker
  //判断标注点是否在范围内
  markerlist.forEach(function(item){
      //若坐标点不在范围内，扩大bounds范围
      if(bounds.isEmpty() || !bounds.contains(item.position)){
          bounds.extend(item.position)
      }
  })
  //设置地图可视范围
  map.fitBounds(bounds, {
      padding: 100 // 自适应边距
  })

  // 使用marker 移动接口， https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocMarker
  marker.moveAlong(
    {
      car: {
        path:pathlist.value,
        speed: 1000,
      },
    },
    {
      autoRotation: true,
    }
  )
  marker.on('moving', (e) => {
    var passedLatLngs = e.car && e.car.passedLatLngs;
    if (passedLatLngs) {
      // 使用路线擦除接口 eraseTo, https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocVector
      polylineLayer.eraseTo(
        'erasePath',
        passedLatLngs.length - 1,
        passedLatLngs[passedLatLngs.length - 1]
      )
    }
  })

}

//运行时长
const yxscChart = ref()
let yunxChart

function yxscinit() {
  if (yxscChart.value) {
    //初始化echarts实例
    yunxChart = echarts.init(yxscChart.value);
    // 指定图表的配置项和数据
    const option = {
      title: {
        text: "运行时长",
        left: "center",
        textStyle: {
            color: '#2363a5',
            fontSize: 16
        }
      },
      grid: {
        left: '3%',
        top:'15%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          crossStyle: {
            color: "#999",
          },
        },
      },
      // toolbox: {
      //   feature: {
      //     dataView: { title: "数据视图", show: true, readOnly: false },
      //     magicType: {
      //       title: { line: "折线图", bar: "柱状图" },
      //       show: true,
      //       type: ["line", "bar"],
      //     },
      //     restore: { title: "刷新", show: true },
      //     saveAsImage: { title: "下载", show: true },
      //   },
      // },
      // legend: {
      //   data: [ "充电", "放电"],
      //   top:25
      // //bottom: 0,
      // },
      xAxis: [
        {
          type: "category",
          data:yxscx,           //["10h", "50h", "100h", "150h", "200h", "250h", "300h"],
          axisPointer: {
            type: "shadow",
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          name: "",
          // min: 0,
          // max: 50,
          // interval: 50,
          axisLabel: {
            formatter: "{value}台",
          },
        },
      ],
      series: [
        {
          type: "bar",
          tooltip: {
            valueFormatter: function (value) {
              return value;
            },
          },
          barWidth:'20px',
          data:yxscy,                                 //[80.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
          itemStyle: {
          //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              normal: {
                  //柱形图圆角，初始化效果
                  // 第一个值表示顶部的左上角，第二个值表示顶部右上角
                  // 第三个值表示底部左下角，第四个值表示底部右下角
                  barBorderRadius:[20,20,0,0]
              }
          }
        }

      ],
    };
    // 使用刚指定的配置项和数据显示图表。
    yunxChart.setOption(option);
  }
}
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

