<template>
  <div class="p-2">
    <el-card shadow="hover" class="tree-content">
      <el-input v-model="areaName" placeholder="请输入区域名称" prefix-icon="Search" clearable />
      <el-tree ref="areaTreeRef" class="mt-2" node-key="id" :data="areaOptions"
        :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode"
        highlight-current default-expand-all @node-click="handleNodeClick" />
    </el-card>
    <div class="map-tips">在地图中右键可以添加监控点</div>
    <div class="map" id="map"></div>
    <el-dialog v-model="showMarkerDialog" :title="markerInfo.pointName" width="400">
      <span v-if="taskInfo.list.length == 0">暂无已配置并检测的类型，请点击右下角的配置</span>
      <div v-else-if="taskInfo.videoType == 1">
        <span>正在检测：</span>
        <span v-for="el, index in taskInfo.list[0].taskAlgorithms" :key="el.algorithm_name">{{ index === 0 ? '' : ','
          }}{{ el.algorithm_name }}</span>
      </div>
      <div v-else-if="taskInfo.videoType == 2"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="" link @click="editMarker">修改</el-button>
          <el-button type="" link @click="configClick">配置</el-button>
          <el-button type="" link @click="deleteMarker">删除</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showConfigDialog" title="配置信息" width="800" :destroy-on-close="true">
      <el-tabs v-model="activTab.first" class="custom-tabs" @tab-click="tabClick">
        <el-tab-pane v-for="item in algorithmCategoryOptions" :key="item.value" :label="item.name" :name="item.value">
          <el-row :gutter="20">
            <el-col :lg="6" :xs="24">
              <div class="algorithm-type">
                <div :class="{ 'algorithm-type-selected': el.id === activTab.second }" v-for="el in item.children" @click="activTab.second=el.id">{{
                  el.algorithmName }}</div>
              </div>
            </el-col>
            <el-col :lg="18" :xs="24" v-if="activTab.first === item.value">
              <JessibucaPlayer class="player" :videoUrl="`https://live.nodemedia.cn:8443/live/sony_4k_264.flv`"
                :show-paint="true" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" link @click="showConfigDialog = false">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="450px" append-to-body>
      <el-form ref="monitorPointFormRef" :model="form" label-width="100px">
        <el-form-item label="行政区域" prop="areaId" :rules="[{ required: true, message: '行政区域不能为空' }]">
          <el-tree-select v-model="form.areaId" :data="areaOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择行政区域"
            default-expand-all accordion :check-strictly="false" />
        </el-form-item>
        <el-form-item label="监控点名称" prop="pointName" :rules="[{ required: true, message: '监控点名称不能为空' }]">
          <el-input v-model="form.pointName" placeholder="请输入监控点名称" />
        </el-form-item>
        <el-form-item label="场景类型" prop="sceneType" :rules="[{ required: true, message: '场景类型不能为空' }]">
          <el-radio-group v-model="form.sceneType">
            <el-radio value="1">高速公路</el-radio>
            <el-radio value="2">城市道路</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频类型" prop="videoType" :rules="[{ required: true, message: '视频类型不能为空' }]">
          <el-radio-group v-model="form.videoType">
            <el-radio value="1">实时视频</el-radio>
            <el-radio value="2">离线视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.videoType == '1'">
          <el-form-item label="设备编号" prop="deviceNo" :rules="[{ required: true, message: '设备编号不能为空' }]">
            <el-input v-model="form.deviceNo" placeholder="请输入设备编号" />
          </el-form-item>
          <el-form-item label="实时流地址" prop="streamUrl" :rules="[{ required: true, message: '实时流地址不能为空' }]">
            <el-input v-model="form.streamUrl" placeholder="请输入实时流地址" />
          </el-form-item>
        </template>
        <el-form-item label="经度" prop="longitude" :rules="[{ required: true, message: '经度不能为空' }]">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude" :rules="[{ required: true, message: '纬度不能为空' }]">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-input v-model="form.direction" placeholder="请输入方向" />
        </el-form-item>
        <el-form-item label="路口编号" prop="intersectionId">
          <el-input v-model="form.intersectionId" placeholder="请输入路口编号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="buttonLoading" @click="submitForm">确 定</el-button>
          <el-button @click="dialogClose()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getListByAreaTree, addMonitorPoint, updateMonitorPoint, delMonitorPoint } from '@/api/manage/monitorPoint/index'
import { getTaskInfoByPointId } from '@/api/manage/monitorTask'
import { listAlgorithmConfig } from '@/api/manage/algorithmConfig'
import api from '@/api/system/user';
import { getDicts } from '@/api/system/dict/data'
import monitorIcon from '@/assets/images/monitor.svg'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const areaTreeRef = ref<ElTreeInstance>();
const marks = ref([]);
const bdmap = ref(null);
const areaName = ref('');
const areaOptions = ref([])
const buttonLoading = ref(false);
const monitorPointFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const markerInfo = ref({
  pointId: '',
  pointName: ''
})
const taskInfo = ref<any>({
  list: [],
  videoType: ''
})
const showMarkerDialog = ref(false)
const showConfigDialog = ref(false)
const algorithmCategoryOptions = ref([])
const activTab = reactive({
  first: '',
  second: '',
})
const form = ref({
  pointId: '',
  areaId: '',
  pointName: '',
  sceneType: '1',
  videoType: '1',
  deviceNo: '',
  streamUrl: '',
  longitude: '',
  latitude: '',
  direction: '',
  intersectionId: ''
});
onMounted(() => {
  var map = new BMapGL.Map("map"); // 创建地图实例
  var point = new BMapGL.Point(118.879999, 32.016216); // 创建点坐标
  map.centerAndZoom(point, 14);
  map.enableScrollWheelZoom(true);
  bdmap.value = map;

  map.addEventListener("rightclick", function (e) {
    const { lng, lat } = e.latlng;
    monitorPointFormRef.value?.resetFields()
    form.value.longitude = lng
    form.value.latitude = lat
    dialog.visible = true
    dialog.title = '新增监控点位'
  });
  getTreeSelect()
  getAreaTree(100)
  getAlTabs()
});
const dialogClose = () => {
  dialog.visible = false
}
const getTreeSelect = async () => {
  const res = await api.areaTreeSelect();
  areaOptions.value = res.data;
};
const getAreaTree = (areaId) => {
  getListByAreaTree({ areaId }).then(({ code, data }) => {
    if (code === 200) {
      marks.value = data
      showMarks()
    }
  })
}
const getAlTabs = async () => {
  await getDicts('algorithm_category').then(({ data }) => {
    algorithmCategoryOptions.value = (data || []).map(item => ({
      name: item.dictLabel,
      value: Number(item.dictValue),
      children: []
    }))
  })
  const { code, rows } = await listAlgorithmConfig()
  if (code == 200) {
    (rows || []).forEach(item => {
      algorithmCategoryOptions.value.forEach(el => {
        if (item.algorithmCategory === el.value) {
          el.children.push(item)
        }
      })
    })
  }
  activTab.first = algorithmCategoryOptions.value[0].value
  activTab.second = algorithmCategoryOptions.value[0].children[0].id
}
const tabClick = () => { }
/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
const handleNodeClick = (data) => {
  getAreaTree(data.id)
}
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    areaTreeRef.value?.filter(areaName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);
/** 提交按钮 */
const submitForm = () => {
  monitorPointFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.pointId) {
        await updateMonitorPoint(form.value)
        proxy?.$modal.msgSuccess("修改成功");
      } else {
        await addMonitorPoint(form.value)
        proxy?.$modal.msgSuccess("新增成功");
      }
      buttonLoading.value = false;
      getAreaTree(100)
      dialog.visible = false;
    }
  });
}
const showMarks = () => {
  bdmap.value.clearOverlays();
  marks.value.forEach(item => {
    var pt = new BMapGL.Point(Number(item.longitude), Number(item.latitude));
    let icon = new BMapGL.Icon(monitorIcon, new BMapGL.Size(40, 40))
    var marker = new BMapGL.Marker(pt, { icon, myCustomProperty: '111' });
    bdmap.value.addOverlay(marker);
    marker.addEventListener("click", () => {
      markerInfo.value = item
      getTaskInfo(item.pointId)
      showMarkerDialog.value = true
    })
  })
};
const getTaskInfo = (pointId) => {
  getTaskInfoByPointId(pointId).then(({ code, data }) => {
    if (code === 200) {
      taskInfo.value = data
    }
  })
}
const editMarker = () => {
  showMarkerDialog.value = false
  dialog.visible = true;
  dialog.title = '修改监控点位';
  Object.assign(form.value, markerInfo.value)
}
const deleteMarker = async () => {
  await proxy?.$modal.confirm('您确定要删除该监控点位?');
  showMarkerDialog.value = false
  const { pointId } = markerInfo.value
  await delMonitorPoint(pointId)
  proxy?.$modal.msgSuccess("删除成功");
  getAreaTree(100)
}
const configClick = () => {
  showMarkerDialog.value = false
  showConfigDialog.value = true
}
</script>

<style lang="scss" scoped>
.p-2 {
  height: 100%;
  position: relative;

  :deep(.tree-content) {
    position: absolute;
    left: 20px;
    top: 20px;
    width: 350px;
    max-height: 300px;
    overflow-y: auto;
    z-index: 10
  }
}

.map {
  position: fixed;
  width: 100%;
  height: 100%;
}

.map-tips {
  position: absolute;
  top: 20px;
  font-size: 12px;
  color: red;
  left: 50%;
  transform: translateX(-50%);
  z-index: 99;
}

.player {
  height: 400px;
  width: 100%;
}

.algorithm-type {
  >div {
    margin-top: 10px;
    cursor: pointer;
  }

  .algorithm-type-selected {
    color: #409EFF;

  }
}
</style>
