<template>
  <el-dialog
    :model-value="modelValue"
    title="选择执行区域"
    width="920px"
    align-center
    append-to-body
    destroy-on-close
    class="select-area-dialog"
    @update:model-value="emit('update:modelValue', $event)"
    @opened="handleOpened"
    @closed="handleClosed"
  >
    <div v-loading="loading" class="map-wrap">
      <div ref="mapRef" class="map-el"></div>
      <div v-if="!loading && regionCount === 0" class="map-empty">暂无区域数据</div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, nextTick, ref } from "vue";
import { ElMessage } from "element-plus";
import AreaSelectMap from "./areaSelectMap";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  farmId: {
    type: [String, Number],
    default: 101532,
  },
  /** 已选区域 id 列表，编辑回显 */
  selectedIds: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

const { proxy } = getCurrentInstance();
const mapRef = ref(null);
const loading = ref(false);
const regionCount = ref(0);
let areaMap = null;

const close = () => emit("update:modelValue", false);

const handleOpened = async () => {
  await nextTick();
  if (!mapRef.value) return;

  if (!areaMap) {
    areaMap = new AreaSelectMap();
  }
  await areaMap.init(
    mapRef.value,
    "POINT(113.61448114737868 23.585550924763083)"
  );
  await loadRegions();
  areaMap.updateSize();
};

const loadRegions = async () => {
  loading.value = true;
  regionCount.value = 0;
  try {
    const res = await proxy.VE_API.farm.blueRegionList({
      farmId: props.farmId,
      regionId: "",
    });
    const list = Array.isArray(res?.data) ? res.data : [];
    regionCount.value = list.length;
    areaMap?.setRegions(list, props.selectedIds);
    if (!list.length && res?.msg) {
      ElMessage.warning(res.msg);
    }
  } catch (e) {
    console.error(e);
    ElMessage.error("区域数据加载失败");
  } finally {
    loading.value = false;
    nextTick(() => areaMap?.updateSize());
  }
};

const handleConfirm = () => {
  const areas = areaMap?.getSelected() || [];
  if (!areas.length) {
    ElMessage.warning("请至少选择一个执行区域");
    return;
  }
  emit("confirm", {
    areas,
    ids: areas.map((a) => a.id),
    label: areas.map((a) => a.name).join("，"),
  });
  close();
};

const handleClosed = () => {
  areaMap?.destroy();
  areaMap = null;
  regionCount.value = 0;
};
</script>

<style lang="scss" scoped>
.map-wrap {
  position: relative;
  width: 100%;
  height: 520px;
  background: #d3d7d8;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.map-el {
  width: 100%;
  height: 100%;
}

.map-empty {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  pointer-events: none;
  z-index: 2;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-bottom: 4px;
}
</style>

<style lang="scss">
.select-area-dialog {
  .el-dialog__body {
    padding: 12px 20px 8px;
  }
}
</style>
