<template>
  <div class="mm-merge">
    <el-alert class="merge-tip" type="info" :closable="false" show-icon>
      <template #title>
        与桌面端「合并」一致：以<strong>当前使用地图</strong>为底图，把选中的地图依次合并进来（自动分配独立图层、
        站点 / 路径 ID 自动避让，互不冲突），再另存为目标地图。可用于多楼层汇总、多区域拼接。
      </template>
    </el-alert>

    <el-alert
      v-if="!loadingMaps && !currentName"
      class="merge-tip"
      type="warning"
      :closable="false"
      show-icon
      title="当前未设置「使用中」地图。请先到「服务器地图」页对某张地图点「使用」，再来执行合并。"
    />

    <div class="merge-body">
      <el-form label-width="120px" label-position="right" class="merge-form" @submit.prevent>
        <el-form-item label="底图（当前地图）">
          <el-tag v-if="currentName" type="success" effect="plain">{{ currentName }}</el-tag>
          <span v-else class="merge-hint">未设置</span>
        </el-form-item>

        <el-form-item label="合并进来的地图" required>
          <el-select
            v-model="selected"
            multiple
            filterable
            :loading="loadingMaps"
            :disabled="!currentName"
            placeholder="选择 1 张及以上要合并进当前地图的地图"
            style="width: 100%"
          >
            <el-option v-for="m in sourceOptions" :key="m" :label="m" :value="m" />
          </el-select>
        </el-form-item>

        <el-form-item label="另存为" required>
          <el-input
            v-model="target"
            :disabled="!currentName"
            placeholder="目标地图名称（与当前地图同名则覆盖当前地图）"
            clearable
            maxlength="60"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="merging" :disabled="!canMerge" @click="onMerge">开始合并</el-button>
          <el-button text :disabled="!currentName" @click="reset">重置</el-button>
          <span class="merge-hint">已选 {{ selected.length }} 张</span>
        </el-form-item>
      </el-form>

      <div v-if="currentName" class="merge-order">
        <div class="order-title">叠加顺序</div>
        <ol class="order-list">
          <li class="order-item">
            <el-tag size="small" type="success" effect="plain">底图</el-tag>
            <span class="order-name">{{ currentName }}</span>
          </li>
          <li v-for="(m, i) in selected" :key="m" class="order-item">
            <el-tag size="small" type="info" effect="plain">叠加 {{ i + 1 }}</el-tag>
            <span class="order-name">{{ m }}</span>
          </li>
        </ol>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mapsApi } from '@/api/mapEdit'

const emit = defineEmits<{ (e: 'merged', name: string): void }>()

const loadingMaps = ref(false)
const merging = ref(false)
const allMaps = ref<string[]>([])
const currentName = ref('')
const selected = ref<string[]>([])
const target = ref('')

// 可合并的源地图 = 全部地图去掉「当前地图」自身。
const sourceOptions = computed(() => allMaps.value.filter((m) => m !== currentName.value))
const canMerge = computed(
  () => !!currentName.value && selected.value.length >= 1 && target.value.trim().length > 0
)

async function loadMaps() {
  loadingMaps.value = true
  try {
    const r = await mapsApi.list()
    allMaps.value = r.maps.map((m) => m.name)
    currentName.value = r.maps.find((m) => m.isCurrent)?.name ?? ''
    // 当前地图变化时，剔除已不可选的项。
    selected.value = selected.value.filter((m) => sourceOptions.value.includes(m))
  } catch (err) {
    ElMessage.error(`加载地图列表失败：${(err as Error).message}`)
  } finally {
    loadingMaps.value = false
  }
}

function reset() {
  selected.value = []
  target.value = ''
}

async function doMerge(overwrite: boolean) {
  const sources = [...selected.value]
  const name = target.value.trim()
  const res = await mapsApi.merge(sources, name, overwrite)
  if (res.ok) {
    const into = res.data.overwroteCurrent ? '（已覆盖当前地图）' : ''
    ElMessage.success(
      `已把 ${res.data.sourceCount} 张地图合并进「${res.data.baseMap}」并另存为「${res.data.name}」${into}` +
        `（站点 ${res.data.sites} · 路径 ${res.data.tracks}）`
    )
    reset()
    await loadMaps()
    emit('merged', name)
    return
  }
  if (res.conflict) {
    const tip =
      name === currentName.value
        ? `目标与当前地图「${name}」同名，将用合并结果覆盖当前地图，是否继续？`
        : `地图「${name}」已存在，是否替换原地图？`
    try {
      await ElMessageBox.confirm(tip, '目标地图已存在', {
        type: 'warning',
        confirmButtonText: '替换',
        cancelButtonText: '取消'
      })
    } catch {
      return
    }
    await doMerge(true)
    return
  }
  ElMessage.error(res.message)
}

async function onMerge() {
  if (!canMerge.value) return
  merging.value = true
  try {
    await doMerge(false)
  } finally {
    merging.value = false
  }
}

onMounted(loadMaps)

defineExpose({ refresh: loadMaps })
</script>

<style scoped>
.mm-merge {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 14px;
  min-height: 0;
  overflow: auto;
}
.merge-tip {
  flex-shrink: 0;
}
.merge-body {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  align-items: flex-start;
}
.merge-form {
  flex: 1 1 440px;
  max-width: 580px;
}
.merge-hint {
  margin-left: 12px;
  font-size: 12.5px;
  color: var(--mg-text-muted);
}
.merge-order {
  flex: 0 1 280px;
  min-width: 220px;
  padding: 12px 16px;
  border-radius: var(--mg-radius);
  background: rgba(var(--mg-accent-rgb), 0.08);
  border: 1px solid var(--mg-veil-border);
}
.order-title {
  font-size: 13px;
  font-weight: 600;
  color: var(--mg-text-light);
  margin-bottom: 10px;
}
.order-list {
  margin: 0;
  padding-left: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.order-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.order-name {
  color: var(--mg-text-light);
  font-size: 13px;
  word-break: break-all;
}
</style>
