<template>
  <div>
    <el-row :gutter="12">
      <el-col :offset="1" :span="5">
        <el-card shadow="hover" style="margin:24px 0 ">
          <h2>车辆信息</h2>
          <p>车队名称：<span>{{ cardInfo.name }}</span></p>
        </el-card>
        <h2>实时位置</h2>
        <div id="container" class="container1"></div>
        <!--        <div style="width: 25%;text-align: center;margin-top: 14px">-->
        <!--          <img height="70" src="@/assets/images/tyre.png" style="" width="70"/>-->
        <!--          <div style="width: 100%;font-size: 12px;white-space:nowrap">轮胎详情</div>-->
        <!--        </div>-->
      </el-col>
      <el-col :offset="1" :span="11">
        <div style="width: 100%;text-align: center;height: 100px">
          <div style="width: calc(50% - 50px);float:left;">
            <span style="font-weight: 600;font-size: 16px;color:#cba658;line-height: 40px">
            <span class="platebg">
              <span class="span1">{{ cardInfo.carLicense.slice(0, 2) }}</span>
              <span class="span2">{{ cardInfo.carLicense.slice(2, 7) }}</span>
            </span>
            </span>
          </div>
          <div style="width: 100px;float:left;">
            <span style="font-weight: 600;font-size: 20px;line-height: 40px">单车监控</span>
          </div>
          <div style="width: calc(50% - 50px);float:left;">
            <span style="font-weight: 600;font-size: 16px;color:#cba658;line-height: 100px">
              <span style="vertical-align:top;">
            里程：000.00km
              </span>
            </span>
          </div>
        </div>
        <div v-for="(item,index) in TireRow" key="index" style="margin-bottom: 18px">
          <div
              style="vertical-align:top;width: 12.5%;margin: 0 12px; height: 100px;display: inline-block;border: 1px solid #666;border-radius: 10%"
              @click="getTyreInfo(`${index+1}-1-1`)">
            <div v-if="tyreDataList.includes(`${index+1}-1-1`)"
                 style="border-radius: 10%;width:100%;height:100%;background-color:green;vertical-align:top">
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon1"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-1-1`))[0].temperature).toFixed(3) }}℃
              </div>
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon2"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-1-1`))[0].pressure).toFixed(3) }}Pa
              </div>
              <!--              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">-->
              <!--                花纹:{{ tyreList.filter(e => e.tyrePositionS === (`${index + 1}-1-1`))[0].pattern }}-->
              <!--              </div>-->
            </div>
          </div>
          <div
              :style="'vertical-align: top;width: 12.5%;margin: 0 12px; height: 100px;display: inline-block;border: 1px solid'+ (TireRow[index] === 2 ? '#666;' :'rgba(0,0,0,0);') + 'border-radius: 10%'"
              @click="getTyreInfo(`${index+1}-1-2`)">
            <div v-if="tyreDataList.includes(`${index+1}-1-2`)"
                 style="border-radius: 10%;width:100%;height:100%;background-color:green;vertical-align: top">
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon1"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-1-2`))[0].temperature).toFixed(3) }}℃
              </div>
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon2"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-1-2`))[0].pressure) }}Pa
              </div>
              <!--              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">-->
              <!--                花纹:{{ tyreList.filter(e => e.tyrePositionS === (`${index + 1}-1-2`))[0].pattern }}-->
              <!--              </div>-->
            </div>
          </div>
          <img sizes="100% 100%" src="@/assets/images/zhou.png"
               style="width: calc(50% - 108px);height: 100px;display: inline-block;vertical-align:top"/>
          <div
              :style="'vertical-align: top;width: 12.5%;margin: 0 12px; height: 100px;display: inline-block;border: 1px solid '+ (TireRow[index] === 2 ? '#666' :'rgba(0,0,0,0)')  +';border-radius: 10%'"
              @click="getTyreInfo(`${index+1}-2-2`)">
            <div v-if="tyreDataList.includes(`${index+1}-2-2`)"
                 style="border-radius: 10%;width:100%;height:100%;background-color:green;vertical-align:top">
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon1"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-2-2`))[0].temperature).toFixed(3) }}℃
              </div>
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon2"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-2-2`))[0].pressure) }}Pa
              </div>
              <!--              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">-->
              <!--                花纹:{{ tyreList.filter(e => e.tyrePositionS === (`${index + 1}-2-2`))[0].pattern }}-->
              <!--              </div>-->
            </div>
          </div>
          <div
              style="vertical-align: top;width: 12.5%;margin: 0 12px; height: 100px;display: inline-block;border: 1px solid #666;border-radius: 10%"
              @click="getTyreInfo(`${index+1}-2-1`)">
            <div v-if="tyreDataList.includes(`${index+1}-2-1`)"
                 style="border-radius: 10%;width:100%;height:100%;background-color:green;vertical-align:top">
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon1"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-2-1`))[0].temperature).toFixed(3) }}℃
              </div>
              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">
                <div class="icon2"/>
                {{ parseFloat(tyreList.filter(e => e.tyrePositionS === (`${index + 1}-2-1`))[0].pressure) }}Pa
              </div>
              <!--              <div style="white-space:nowrap;width: 100%;color:#fff;font-size: 0.7vw;line-height: 50px">-->
              <!--                花纹:{{ tyreList.filter(e => e.tyrePositionS === (`${index + 1}-2-1`))[0].pattern }}-->
              <!--              </div>-->
            </div>
          </div>
        </div>
      </el-col>
      <el-col :offset="1" :span="5">
        <el-tabs
            v-model="tabsName"
            style="margin:24px 0 0 0"
            type="card"
            @tab-click="resetQuery"
        >
          <el-tab-pane label="有车载设备车辆" name="有车载设备车辆">
            <el-form ref="queryRef" :inline="true" :model="queryParams"
                     label-width="60px" max-height="800">
              <el-form-item label="车牌号" prop="carLicense">
                <el-input
                    v-model="queryParams.carLicense"
                    clearable
                    style="width: 200px"
                    @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label=" ">
                <el-button icon="Search" type="primary" @click="handleQuery">{{ t('option.search') }}</el-button>
                <el-button icon="Refresh" @click="resetQuery">{{ t('option.reset') }}</el-button>
              </el-form-item>
            </el-form>

            <el-table
                ref="tableRef1"
                :data="tableData"
                :show-header="false"
                highlight-current-row
                style="width: 100%"
                @current-change="tableChange"
            >
              <el-table-column label="label" prop="label"/>
              <el-table-column v-if="false" label="id" prop="id"/>
            </el-table>

            <pagination
                v-show="total > 0"
                v-model:limit="queryParams.pageSize"
                v-model:page="queryParams.pageNum"
                :total="total"
                layout="sizes, prev, pager, next"
                style="margin-bottom: 40px"
                @pagination="getList"
            />
          </el-tab-pane>
        </el-tabs>

      </el-col>
    </el-row>

    <el-dialog v-model="open" :title="title" append-to-body width="800px">
      <el-descriptions :column="2" border class="margin-top" width="150px">
        <el-descriptions-item>
          <template #label>
            胎号
          </template>
          {{ tyreInfo.outerTireNumber }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            轮位描述
          </template>
          {{ tyreInfo.tyrePosition }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            传感器ID
          </template>
          {{ tyreInfo.sensorId }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            品牌
          </template>
          {{ tyreInfo.brand }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            总里程
          </template>
          {{ tyreInfo.internationalization2 }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            规格
          </template>
          {{ tyreInfo.size }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            花纹
          </template>
          {{ tyreInfo.pattern }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            当前花纹深度
          </template>
          {{ tyreInfo.currentTextureDepth }}mm
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            电池电压
          </template>
          {{ tyreInfo.internationalization2 }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            温度
          </template>
          {{ tyreInfo.temperature }}℃
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            压力
          </template>
          {{ tyreInfo.pressure }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            安装时间
          </template>
          {{ tyreInfo.internationalization2 }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ t('option.ok') }}</el-button>
          <el-button @click="cancel">{{ t('option.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {listBaseCar, getCarGpsList, getTyreList} from '@/api/realTimeMonitoring/carMonitoring'
import AMapLoader from '@amap/amap-jsapi-loader';
import {useI18n} from "vue-i18n";
import {ref} from 'vue'
import {useRouter} from 'vue-router';
import {parseTime} from "@/utils/ruoyi";
import {onBeforeUnmount} from "@vue/runtime-core";
import {addBaseDevice, updateBaseDevice} from "@/api/deviceManagement/info";

const title = '轮胎信息'
const {proxy} = getCurrentInstance();
const $router = useRouter();
const {t} = useI18n();
const TireRow = ref([])
const tyreList = ref([])
const tyreDataList = ref([])
const pageId = ref('')
const tableRef1 = ref()
const open = ref(false)
let map = null
const markers = ref(null)
const tyreInfo = ref({})
const childrenList = ref([])

const getTyreInfo = (e) => {
  console.log(e)
  console.log(tyreList.value)
  let id = tyreList.value.filter(val => val.tyrePositionS === e)?.[0]?.tyreId || ''
  console.log(id)
  if (!id) return
  open.value = true
  getTyreList(id).then(e => {
    tyreInfo.value = e.data
  })
}

AMapLoader.load({
  key: "ba8fb8d8bae1b280b93406d5959d492f",             // 申请好的Web端开发者Key，首次调用 load 时必填
  // version: "1.4.15",      //
  version: "2.0",      //
  plugins: [],

  AMapUI: {
    version: '1.1',
    plugins: []
  }
}).then((AMap) => {
  map = new AMap.Map("container", {  //设置地图容器id
    viewMode: "3D",    //是否为3D地图模式
    zoom: 16,           //初始化地图级别
    center: [116.397428, 39.90923], //初始化地图中心点位置
  });
}).catch(e => {
})
proxy.$nextTick(async () => {
  pageId.value = $router?.currentRoute?.value?.query?.id
  if (pageId.value) {
    // await tableChange({id: pageId.value})
    const {rows: list} = await listBaseCar(queryParams.value)
    tableData.value = list.map(e => {
      return {
        label: e.carLicense,
        ...e
      }
    })
    tableRef1.value.setCurrentRow(tableData.value.find(e => e.id === pageId.value))
  } else {
    getList()
  }
})
// 总条数
const total = ref(0);
const getList = async () => {
  const {rows: list} = await listBaseCar(queryParams.value)
  tableData.value = list.map(e => {
    return {
      label: e.carLicense,
      ...e
    }
  })
  total.value = tableData.value.length
  tableRef1.value.setCurrentRow(tableData.value[0])
  console.log(tableData.value)
}


const setChildrenList =async (e) => {
  const {rows: list} = await listBaseCar({
    pageNum: 1,
    pageSize: 10,
    carLicense: '',
  })
}
const tableChange = async (e) => {
  pageId.value = e.id
  const {data: info} = await getCarGpsList({id: pageId.value})
  cardInfo.value = {
    carLicense: info.carLicense,
    name: info.carQueue
  }
  let TireRow1 = info.cartype?.split('T')[1]?.split('|').filter(e => e !== '') || []
  let title = []
  TireRow1.forEach((res) => {
    title.push(parseInt(res.split('-')[1]))
  })
  TireRow.value = title
  let tyreListData = info.tyreList.map(e => {
    return {
      ...e,
      tyrePositionS: e.tyrePosition?.split('-')[0] + '-' + e.tyrePosition?.split('-')[1] + '-' + e.tyrePosition?.split('-')[2]
    }
  })
  tyreList.value = tyreListData
  tyreDataList.value = tyreListData.map(e => e.tyrePositionS)
  let timeOut = () => {
    setTimeout(() => {
      if (map) {
        setMarker(info)
        clearTimeout(timeOut)
      }
    }, 1000)
  }
  timeOut()
}

const cardInfo = ref({
  name: '名称',
  carLicense: ''
})

const tabsName = ref('有车载设备车辆')
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  carLicense: '',
})
const tableData = ref([])


/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  tyreInfo.value = {
    id: null,
    internetThingsNo: null,
    deviceType: null,
    state: null,
  };
  proxy.resetForm("postRef");
}

/** 提交按钮 */
function submitForm() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;

  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    carLicense: '',
  }
  handleQuery();
  tableRef1.value.setCurrentRow()
}
const setMarker = (res) => {
  let pathRow = [[res.longitude, res.latitude]]
  markers.value && map.remove(markers.value)
  AMap.convertFrom(pathRow, 'gps', function (status, result) {
    if (result.info === 'ok') {
      let lnglats = result.locations.map(e => [e.lng, e.lat]);
      markers.value = new AMap.Marker({
        content: '<div class="markerIcon" />',
        position: lnglats[0],
        anchor: 'bottom-center',
        offset: new AMap.Pixel(0, 0),
      });
      map.add(markers.value)
      map.setFitView()
      map.setZoom(8)
    }
  })
}
onBeforeUnmount(() => {
  map.destroy()
  map = null
})
</script>
<style lang="scss">
.container1 {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: calc(30vh - 84px);
  min-height: 200px;
}

.el-tabs__nav {
  width: 100%;
  border: 0 !important;
}

.el-tabs__item {
  width: 100%;
  text-align: center;
}

.el-tabs {
  border: 1px solid #ddd
}

.platebg {
  display: inline-block;
  width: 192px;
  height: 60px;
  background-image: url("../../../assets/images/platebg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  line-height: 40px;
  font-size: 30px;
  color: #fff;
  margin-top: 20px;

  .span1 {
    display: inline-block;
    float: left;
    line-height: 60px;
    width: 32%;
  }

  .span2 {
    display: inline-block;
    float: left;
    line-height: 60px;
    width: 68%;
    letter-spacing: 4px;
  }
}

.markerIcon {
  width: 65px;
  height: 50px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url("../../../assets/images/trucks.png");
}

.el-descriptions__label {
  width: 170px;
}

.icon1 {
  margin-left: 5px;
  display: inline-block;
  vertical-align: top;
  margin-top: 13px;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url('@/assets/images/temperature.png')
}

.icon2 {
  margin-left: 5px;
  display: inline-block;
  vertical-align: top;
  margin-top: 13px;
  width: 20px;
  height: 20px;
  margin-right: 3px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url('@/assets/images/pressure.png')
}
</style>
