<!-- eslint-disable indent -->
<script setup lang="ts">
import { ref, onMounted, withDefaults } from "vue"
import { getAssetPath } from "@/core/helpers/assets"
//import DynamicTreeSelect from "@/components/select/DynamicTreeSelect.vue"
import DySelectTree from "@/components/select/DySelectTree.vue"
import AMapLoader from "@amap/amap-jsapi-loader"
import { shallowRef } from "vue"
import Rs from "@/core/services/RequestService"
import { useRouter } from "vue-router"
const router = useRouter()

const props = withDefaults(defineProps<{ themeClass?: string }>(), {
  themeClass: "",
})
const map: any = shallowRef(null)
const org_id = ref<string | null>(null)
const name = ref("")
const showCompanyList = ref(false)
const companyList: any = ref([])
const companyTotal = ref(0)
const clist_loading = ref(false)
const companySearch: {
  pageIndex: number
  pageSize: number
  params?: any
} = {
  pageIndex: 1,
  pageSize: 100000,
  params: {
    org_id: "",
    name: "",
  },
}
const pagination = ref({
  curPage: 1,
  curPageSize: 10,
  curPageSizes: [10],
  curPagerCount: 10,
})
const mapMarkers: any = []
let isInit = true
let searchTimer: any = null

const companyAreaChange = (data: any) => {
  org_id.value = data.id
  console.log("change")
  refreshCompany(1)
}

const companyNameChange = () => {
  refreshCompany(1)
}
const refreshCompany = (pageIndex: number, pageSize?: number) => {
  clearTimeout(Number(searchTimer))
  if (pageIndex) {
    //console.log("pageIndexChange", pageSize)
    pagination.value.curPage = pageIndex
  }
  if (pageSize) {
    //console.log("pageSizeChange", pageSize)
    pagination.value.curPageSize = pageSize
  }
  clist_loading.value = true
  searchTimer = setTimeout(getCompany, 200)
}
const getCompany = () => {
  if (org_id.value) {
    companySearch.params.org_id = org_id.value
  } else {
    delete companySearch.params.org_id
  }

  if (name.value) {
    companySearch.params.name = name.value
  } else {
    delete companySearch.params.name
  }
  companySearch.pageSize = pagination.value.curPageSize || 10
  companySearch.pageIndex = pagination.value.curPage || 1

  // Rs.post("sys/companyGis/getData", { data: companySearch }).then((res: any) => {
  //   companyList.value = res.data
  //   companyTotal.value = Number(res.total)

  //   //console.log("companyList=====>", companyTotal.value, companyList.value)

  //   renderMap()
  // })
  Rs.post("sys/query/getCompany", { data: companySearch, successAlert: false }).then((res: any) => {
    companyList.value = res.data
    companyTotal.value = Number(res.total)
    renderMap()
    clist_loading.value = false
  })
  setTimeout(() => {
    clist_loading.value = false
  }, 300)
  //Rs.get("sys/dict/getOrgList?type=1")
}
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "b815cb3bb6aa8516fcfe8c506abe9da2",
  }
  AMapLoader.load({
    key: "0da67b4ef98b3975eed48e8f8d42f9cd", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale", "AMap.HawkEye", "AMap.ToolBar", "AMap.ControlBar"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap: any) => {
      const _map = new AMap.Map("map-container", {
        //设置地图容器id
        viewMode: "3D", //是否为3D地图模式
        rotation: 45,
        pitch: 65,
        zoom: 10, //初始化地图级别
      })
      const scale = new AMap.Scale(),
        toolBar = new AMap.ToolBar({
          position: {
            top: "110px",
            right: "40px",
          },
        }),
        controlBar = new AMap.ControlBar({
          position: {
            top: "10px",
            right: "10px",
          },
        }),
        overView = new AMap.HawkEye({
          opened: false,
        })
      _map.addControl(scale)
      _map.addControl(toolBar)
      _map.addControl(controlBar)
      _map.addControl(overView)
      overView.hide()
      if (props.themeClass == "dark") {
        _map.setMapStyle("amap://styles/1f1485e5beb2382bd068587d161155a2")
      }
      map.value = _map
      getCompany()
    })
    .catch((e) => {
      console.log(e)
    })
}
const renderMap = () => {
  if (companyList.value && companyList.value.length) {
    companyList.value.forEach((item: any) => {
      renderMark(item)
    })
    if (isInit) {
      const { latitude, longitude } = companyList.value[0]
      if (latitude || longitude) {
        map.value.setZoomAndCenter(13, [longitude, latitude])
      }
      //document.getElementById("map-container").style.height = "100%";

      isInit = false
    }
  }
  //this.map.setFitView();
}
const renderMark = (item: any) => {
  const { latitude, longitude } = item
  if (!latitude && !longitude) {
    return
  }
  const infoWindow = new window.AMap.InfoWindow({
    isCustom: true,
    //anchor: "top-center",
    offset: new window.AMap.Pixel(0, -25),
    //content: "2", //getInfoBoxHtml(item), //传入 dom 对象，或者 html 字符串
  })
  infoWindow.on("open", function () {
    console.log("====>1")
    document.querySelector(".close-btn_info-box_20220615")?.addEventListener("click", function () {
      console.log("====>2")
      infoWindow.close()
    })
  })
  const oldMark = mapMarkers.find((a: any) => a.companyId == item.company_id)
  if (oldMark) {
    if (item.run_state == oldMark.state) {
      oldMark.infoWindow = infoWindow
      return
    }
    //删除状态变更的marker
    map.value.remove(oldMark.marker)
    mapMarkers.splice(
      mapMarkers.findIndex((a: any) => a.companyId == item.company_id),
      1
    )
    // var allOverlay = this.map.getOverlays();
    // allOverlay.forEach((v) => {
    //   if (v.id == item.company_id) {
    //     this.map.removeOverlay(v);
    //   }
    // });
  }
  const mkIcon = new window.AMap.Icon({
    size: new window.AMap.Size(35, 35),
    image: getAssetPath(
      item.run_state == 0 ? "media/screen/map/blue-location.png" : "media/screen/map/red-location.png"
    ),
    imageOffset: new window.AMap.Pixel(0, 0),
    imageSize: new window.AMap.Size(35, 35),
  })

  const marker = new window.AMap.Marker({
    position: new window.AMap.LngLat(item.longitude, item.latitude),
    offset: new window.AMap.Pixel(0, 1),
    icon: mkIcon, // 添加 Icon 实例
    anchor: "bottom-center",
  })
  marker.id = item.company_id
  map.value.add(marker)
  let timer: any

  marker.on("click", () => {
    clearTimeout(Number(timer))
    companyMarkOpen(item, false)
  })
  marker.on("mouseover", () => {
    clearTimeout(Number(timer))
    timer = setTimeout(() => {
      companyMarkOpen(item, false)
    }, 800)
  })
  marker.on("mouseout", () => {
    clearTimeout(timer)
  })
  mapMarkers.push({
    companyId: item.company_id,
    marker,
    infoWindow,
    state: item.run_state,
  })
}
const companyMarkOpen = (item: any, moveCenter?: boolean) => {
  mapMarkers.forEach((v: any) => {
    if (item && v.companyId == item.company_id) {
      Rs.post(`sys/query/getPurAndFanMonitor/${item.company_id}`).then((res: any) => {
        const content = getInfoBoxHtml(item, res.data)
        v.infoWindow.setContent(content)
        v.infoWindow.open(map.value, [item.longitude, item.latitude])
        if (moveCenter || moveCenter == undefined) {
          map.value.setZoomAndCenter(13, [item.longitude, Number(item.latitude) + 0.01])
        }
      })
    } else {
      v.infoWindow.close()
    }
  })
}

const getInfoBoxHtml = (item: any, monitorVo: any) => {
  console.log("monitorVo", monitorVo)
  console.log("item", item)
  function monitor() {
    let str = ""
    if (monitorVo.monitor1 && monitorVo.monitor1.length) {
      let i = 0
      monitorVo.monitor1.forEach((v: any) => {
        const vv = monitorVo.monitor2.length > i ? monitorVo.monitor2[i] : { statue: "未运行", time: "0" }
        str += `<div class="monitor monitor_${i + 1}" style="display:${i == 0 ? "flex" : "none"};">
                <div class="name" >
                  <span style="width:100%;">${v.name}</span>
                </div>
                <div class="text" >
                  <span style="width:100%;">净化器状态：${v.status}</span>
                  <span style="width:100%;">运行时长：${v.time}</span>
                </div>
                <div class="splite" ></div>
                <div class="name" >
                  <span style="width:100%;">${vv.name}</span>
                </div>
                <div class="text" >
                  <span style="width:100%;">风机状态：${vv.status}</span>
                  <span style="width:100%;">运行时长：${vv.time}</span>
                </div>
              </div>`
        i++
      })
    }
    return str
  }
  return `<div class="map-company-box">
          <div class="close-btn close-btn_info-box_20220615"></div>
          <div class="title-box">
            <div class="name"  >
              <span>${item.name}</span>
            </div>
            <div class="address" >
              <span style="">详细地址：${item.address}</span>
              <span style="">企业负责人：${item.corporation_name}</span>
            </div>
          </div>
          <div class="monitor-box">
            ${monitor()}
          </div>
          <div class="page-box" data-page="1">
                <button class="left el-button el-button--default" type="button" disabled onclick="onCompanyMonitorScorl(this,0,${
                  monitorVo.monitor1?.length
                })"><</button>
                <div class="mid" style=""><span class="cur-page">1</span><span style="marging:0 3px;">/</span>${
                  monitorVo.monitor1.length
                }</div>
                <button class="right el-button el-button--default" type="button" style="" ${
                  monitorVo.monitor1.length == 1 ? "disabled" : ""
                } onclick="onCompanyMonitorScorl(this,1,${monitorVo.monitor1.length})">></button>
          </div>
 <div  class="btn-box" >
 <button type="button" class="el-button el-button--default" onclick="onCompanyDetail('${item.name}','${
    item.company_id
  }')">查看详情</button>
 </div>
          <div>
          </div>
        </div> `
}
const jumpCompanyDetail = (item: any) => {
  router.push({
    path: "/goLineData/oilFumeConcentration",
    query: {
      comName: item.name,
      company_id: item.company_id,
      back: 1,
    },
  })
}

onMounted(() => {
  initMap()
  window.onCompanyMonitorScorl = function (that: any, type: any, max: number) {
    const $this = that,
      $page = $this.closest(".page-box")
    const page = Number($page.dataset.page)
    const page2 = type ? page + 1 : page - 1
    if (page2 > max || page2 < 1) {
      return
    }
    $page.dataset.page = page2
    $page.querySelector(".cur-page").innerHTML = page2
    const $monitor = $page.previousElementSibling
    $monitor.querySelector(".monitor_" + page).style.display = "none"
    $monitor.querySelector(".monitor_" + page2).style.display = "flex"

    $page.querySelector(".left").disabled = page2 == 1
    $page.querySelector(".right").disabled = page2 == max
  }
  window.onCompanyDetail = function (name: string, company_id: string) {
    jumpCompanyDetail({
      name,
      company_id,
    })
  }
})
</script>
<template>
  <div style="width: 100%; height: 100%; position: relative">
    <!-- <link rel="stylesheet" type="text/css" href="https://api.map.baidu.com/res/webgl/10/bmap.css"></link> -->
    <div class="map-container" id="map-container"></div>
    <div class="menu-container" id="menu-container">
      <div class="menu-box">
        <div class="menu" :class="showCompanyList ? 'active' : ''" @click="showCompanyList = !showCompanyList">
          公司列表
        </div>
      </div>
      <div v-if="showCompanyList" class="company-list">
        <div class="close-btn" @click="showCompanyList = false"></div>
        <div class="input-group">
          <DySelectTree
            style="width: 48%"
            class="full-input"
            :url="'sys/dict/getOrgList?type=1'"
            v-model:value="org_id"
            :defaultExpandLevel="1"
            :option-map="{ id: 'value', label: 'label', children: 'children' }"
            placeholder="请选择区域..."
            @select="companyAreaChange"
          />
          <el-input
            @change="companyNameChange"
            style="width: 48%; height: 36px; border-radius: 5px"
            v-model="name"
            placeholder="输入企业名称"
          />
        </div>

        <div class="list-box" v-if="companyList.length > 0">
          <div class="clist_loading_box" v-if="clist_loading">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
          </div>
          <div class="company-item" v-for="(item, index) in companyList" :key="index">
            <img
              class="icon"
              :src="getAssetPath('media/screen/map/company.png')"
              alt=""
              @click="companyMarkOpen(item)"
            />
            <div class="text" @click="companyMarkOpen(item)">
              <span class="name">{{ item.name }}</span>
              <span class="address">{{ item.address }}</span>
            </div>
            <div class="btn">
              <el-button type="default" style="" class="lookDetal" @click="jumpCompanyDetail(item)">详情</el-button>
            </div>
          </div>
          <div v-if="companyTotal >= 0" style="float: right; margin: 10px 10px 5px 0">
            <el-pagination
              @size-change="(size:number) => refreshCompany(1, size)"
              background
              @current-change="refreshCompany"
              :current-page="pagination.curPage"
              :page-sizes="pagination.curPageSizes"
              :page-size="pagination.curPageSize"
              :pager-count="pagination.curPagerCount"
              layout="prev, pager, next"
              :total="companyTotal"
            ></el-pagination>
          </div>
        </div>
        <div class="list-box" v-if="companyList.length <= 0">
          <div style="color: #fff; font-size: 18px; width: 100%; text-align: center; padding: 10px">未查询到结果</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-pagination) {
  .el-pagination__sizes {
    display: none;
  }
  .el-pager > li.number,
  button {
    margin: 0 1px;
    width: 23px;
    min-width: 23px;
    height: 23px;
  }
  .el-pager > li.is-active {
    background-color: rgb(24, 28, 50);
  }
}

.clist_loading_box {
  width: 95%;
  height: 90%;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(159, 162, 184, 0.2);
}
</style>
