<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    title="测点信息"
    width="500"
  >
    <el-form label-width="auto">
      <el-form-item label="坐标" v-if="coordInfo">
        <el-input :value="coordInfo" readonly type="textarea" rows="3" disabled />
      </el-form-item>

      <el-form-item label="测点类型" required>
        <el-select v-model="ivalue.type" placeholder="测点类型">
          <el-option :label="type" :value="type" v-for="type in typeOptions" />
        </el-select>
      </el-form-item>
      <el-form-item label="测点说明" required>
        <el-input
          v-model.trim="ivalue.name"
          :maxlength="100"
          rows="4"
          show-word-limit
          placeholder="请输入"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model.trim="ivalue.remark"
          :maxlength="100"
          show-word-limit
          placeholder="请输入"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="submit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { ref, watchEffect, computed, watch } from "vue";
import { ScenePoint } from "@/store/scene";
import { PointTypeEnum } from "drawing-board";
import { toDegrees } from "@/util";

const props = defineProps<{
  visible: boolean;
  value: ScenePoint;
  updateValue: (value: ScenePoint) => void;
}>();

const typeOptions = [
  PointTypeEnum.border,
  PointTypeEnum.center,
  PointTypeEnum.marker,
  PointTypeEnum.other,
];

const coordInfo = computed(() => {
  const point = ivalue.value.pos;
  if (!(!point || point.length === 0 || point.some((i) => !i))) {
    return `经度：${toDegrees(ivalue.value.pos[0])}
纬度：${toDegrees(ivalue.value.pos[1])}
高程：${ivalue.value.pos[2]}`;
  }
});

const emit = defineEmits<{
  (e: "update:visible", visible: boolean): void;
}>();

const ivalue = ref<ScenePoint>();
watchEffect(() => {
  ivalue.value = { ...props.value, name: props.value.name || "" };
});

watch(
  () => props.value?.type,
  (type) => {
    ivalue.value.type = type || PointTypeEnum.other;
  },
  { immediate: true }
);

const submit = async () => {
  if (ivalue.value.name.trim().length === 0) {
    return ElMessage.error(`测点说明不能为空！`);
  }
  await props.updateValue(ivalue.value);
  emit("update:visible", false);
};
</script>
