<template>
  <div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ title }}</span>
        <div>
          <el-button
            v-if="!infoActive"
            type="primary"
            size="small"
            :loading="btnLoading"
          >保存</el-button
          >
          <el-button size="small" @click="close">关闭</el-button>
        </div>
      </div>

      <div class="dialogWrapper">
        <div class="tabsWrapper">
          <template v-for="(item, index) in form?.bddList" :key="index">
            <div :class="['item', { 'active': current === index }]" @click="handleItem(index)">{{ item?.bddMc }}</div>
          </template>
        </div>
        <div id="viewer" ref="viewerRef" style="width: 100%; height: 100%;background-color: aliceblue;"></div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, getCurrentInstance, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
import { fetchSelectListByBddxlrwId } from "@/api/service/taskProgress";
import emitter from "@/utils/eventBus";
import { MapUtil } from "@/components/Map/GdMap/mapUtil";
const { proxy } = getCurrentInstance();
const btnLoading = ref(false); //按钮截流
const title = ref("修改");
const formRef = ref(null);
const infoActive = ref(true);
const current = ref(0)

//级联选择器配置
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:modelValue', 'ok', 'update']);

const formData = computed(() => form.value?.bddList[current.value])
const dialogFormVisible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emits("update:modelValue", val);
  }
})

//表单数据
const form = ref({
  bddList: []
});


let viewerMap = null
const viewerRef = ref(null); // 添加 ref
const mapUtil = ref(null)
const initMap = () => {
  nextTick(() => {
    viewerMap = new EliMap({
      id: viewerRef.value.id,
      crs: "EPSG:3857",
      style: {
        glyphs: "./fonts/{fontstack}/{range}.pbf",
        center: [104.41361653448905, 31.127827898122767],
        zoom: 10
      },
      transformRequest: (url) => {
        if (url.indexOf("TileMatrix=") != -1) {
          const arr = url.split("TileMatrix=");
          const arr1 = arr[1].split("&");
          const nurl = `${arr[0]}&TileMatrix=${Number(arr1[0])}&${arr1[1]}&${arr1[2]
            }`;

        }
      }
    });

    viewerMap.mapboxGLMap.on("load", () => {
      viewerMap.addGaudLayer({
        url: 'http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
      })
    });
    console.log(viewerMap)
    // mapUtil.value = new MapUtil(viewerMap);
  })
}



// 监听对话框显示状态
watch(dialogFormVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initMap();
    });
  }
});

const setMapCenter = (location, zoomLevel) => {
  viewerMap.mapboxGLMap.setCenter(location);
  viewerMap.mapboxGLMap.setZoom(zoomLevel);
};

  const echoPlane = (res) => {
    let { type , coords ,fontColor, text = '' ,radius = 0, isclear ,flag ,id = 1 , color , linecolor} = res;
    if(!coords) return;
    // if(isclear) _that.removeElement(flag)
    // if(!_that._self[flag]) _that._self[flag] = [];
    let color1 = color ? color : 'rgba(29,237,245,0.6)'
    let linecolor1 = linecolor ? linecolor : 'rgba(29,237,245,0.6)'
    let style = {
      color:color1,
      outLineColor:linecolor1,
      outLineWidth:2,
      highlightColor:'rgba(255,0,0,0.5)',
      labelOption:{
        pixelOffset:[0,0],
        allShow:true,
        fontColor:fontColor ? fontColor:'#ffffff',
        fontSize:'12px'
      }
    }
    let maker ;
    // 矩形
    if(type == 'rectangle') maker = map.createRectangle(coords,style);
    
  }

  const makerSki = (res) => {
    const { coords, icon } = res
    if (!coords) return;
    coords.forEach(item => {
      
      const el = document.createElement("img");
      el.src = icon;
      el.style.width = "25px";
      const marker = viewerMap.Marker(el,[item.jd,item.wd],{anchor:'bottom', offset:[0,0]})
    });
  };

const getData = async () => {
  const { id = "" } = formData.value
  const res = await fetchSelectListByBddxlrwId({ bddxlrwId: id })
  if (res && res?.length > 0) {
    const { zxX, zxY, x1, x2, y1, y2, id, fgMc } = form.value
    let centerPoint = [zxX, zxY]
    let position = [[Number(x1),Number(y1)],[Number(x2),Number(y2)]]
    let text = fgMc
    let obj = [{ position: position, text, id: id ,userData: form.value}]

    // 方格
    echoPlane({ fontColor:'#12fdb8',coords: obj, type:'rectangle', flag:'fgxlrw', color:'rgba(2,20,51,0.5)', linecolor:'#1C97FF'})
    setMapCenter(centerPoint, 14);

    const dkJs = res?.map(i => ({ jd: i?.dkJsJd + 0.04, wd: i?.dkJsWd + 0.08 }))
    const dkKs = res?.map((i, k) => ({ jd: i?.dkKsJd * k, wd: i?.dkKsWd * k }))

    // 标注
    makerSki({
      coords: [...dkKs, ...dkJs],
      icon: require("@/assets/lz/dw.png"),
    })
  }
}

const handleItem = (index) => {
  current.value = index;
  getData();
}

//新增
function open(row = {}, type) {
  nextTick(() => {
    infoActive.value = !type;
    form.value = { ...row, bddList: row?.bddList ? JSON.parse(row?.bddList) : [] };
    title.value = "任务详情";
    getData()
    dialogFormVisible.value = true;
  })
}

//关闭弹窗
function close() {
  formRef.value?.resetFields();
  dialogFormVisible.value = false;
}

// //提交
// const submit = async () => {
//   try {
//     await formRef.value.validate()

//     await updateData(form.value)
//     proxy.$message({
//       type: "success",
//       message: "修改成功"
//     });
//     dialogFormVisible.value = false;
//     emits("ok")

//   } catch (error) {
//     console.log(error);
//   }
// }

defineExpose({ open })
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.dialog {
  #viewer {
    height: 100vh;
    width: 100vw;
  }

  .dialogWrapper {
    height: calc(100vh - 256px);
    margin: 20px 20px 0 20px;

    .el-form--inline {
      padding: 0 0 0rem 0;
    }

    .tabsWrapper {
      display: flex;
      margin-bottom: 0.53vw;
      overflow-x: auto;
      .item {
        cursor: pointer;
        padding: 0.27vw 0.53vw;
        width: fit-content;
        flex-shrink: 0;
        border: 1px solid #EDEDED;
        border-radius: 5px;
        margin-right: 0.53vw;

        &:last-child {
          margin-right: 0;
        }
      }

      .active {
        color: #24b6dd;
        border: 1px solid #24b6dd !important;
      }
    }
  }
}

.label {
  margin-bottom: 1rem;
}
</style>
