<template>
  <div class="map-card" :class="{ selected: selected, selectable: selectable }">
    <!-- 选择框 -->
    <div v-if="selectable" class="card-checkbox">
      <el-checkbox 
        :value="selected" 
        @change="handleSelectChange"
        :aria-label="`选择地图${item.name}`"
      />
    </div>



    <!-- 缩略图 -->
    <div class="card-thumb" @click="handleEdit">
      <img 
        v-if="thumbUrl" 
        :src="thumbUrl" 
        :alt="item.name"
        @error="handleImageError"
        class="thumb-image"
      />
      <div v-else class="thumb-placeholder">
        <i class="el-icon-map-location"></i>
        <span>暂无预览</span>
      </div>
    </div>

    <!-- 状态徽标 -->
    <div class="card-status">
      <el-tag 
        :type="statusConfig.type" 
        size="mini" 
        effect="plain"
        class="status-tag"
      >
        <i :class="statusConfig.icon"></i>
        {{ statusConfig.text }}
      </el-tag>
    </div>

    <!-- 内容区 -->
    <div class="card-content">
      <h3 class="card-title" @click="handleEdit" :title="item.name">
        {{ item.name }}
      </h3>
      
      <p v-if="item.remark" class="card-remark" :title="item.remark">
        {{ item.remark }}
      </p>
      
      <div class="card-meta">
        <span class="update-time">
          <i class="el-icon-time"></i>
          {{ formatDateTimeCompat(pickUpdatedAt(item)) }}
        </span>
      </div>
    </div>

    <!-- 操作按钮区 -->
    <div class="card-actions" :class="{ 'show-on-mobile': true }">
      <router-link :to="buildNavTo(this, item)" class="card-op-link">
        <el-button 
          type="primary" 
          size="mini" 
          icon="el-icon-position"
          :aria-label="`导航到${item.name}`"
        >
          导航
        </el-button>
      </router-link>
      
      <router-link :to="buildEditTo(this, item)" class="card-op-link">
        <el-button 
          type="default" 
          size="mini" 
          icon="el-icon-edit-outline"
          :aria-label="`编辑${item.name}`"
        >
          编辑
        </el-button>
      </router-link>
      
      <el-dropdown 
        @command="handleMoreAction"
        trigger="click"
        placement="bottom-end"
      >
        <el-button 
          type="default" 
          size="mini" 
          icon="el-icon-more"
          :aria-label="`更多操作${item.name}`"
        />
        <el-dropdown-menu slot="dropdown" class="xt-more">
          <el-dropdown-item command="rename"><i class="el-icon-edit"></i> 重命名</el-dropdown-item>
          <el-dropdown-item command="download"><i class="el-icon-download"></i> 下载地图</el-dropdown-item>
          <el-dropdown-item command="build"><i class="el-icon-cpu"></i> 构建地图</el-dropdown-item>
          <el-dropdown-item divided command="delete" class="is-danger"><i class="el-icon-delete"></i> 删除地图</el-dropdown-item>
          <el-dropdown-item divided command="calibrate"><i class="el-icon-position"></i> 坐标系标定</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import { formatDateTimeCompat, pickUpdatedAt } from '@/utils/datefmt'
import { buildNavTo, buildEditTo, buildCalibrateTo, buildConstructTo, pickId } from '@/utils/route-helpers'

export default {
  name: 'XtMapCard',
  
  props: {
    item: {
      type: Object,
      required: true,
      default: () => ({
        id: '',
        name: '',
        status: 'ok',
        thumbUrl: '',
        remark: '',
        updatedAt: ''
      })
    },
    selectable: {
      type: Boolean,
      default: false
    },
    selected: {
      type: Boolean,
      default: false
    },
    mapFileBase: {
      type: String,
      default: ''
    }
  },

  computed: {
    // 状态配置
    statusConfig() {
      const configs = {
        ok: { type: 'success', icon: 'el-icon-check', text: '正常' },
        down: { type: 'danger', icon: 'el-icon-close', text: '不可用' },
        scanning: { type: 'warning', icon: 'el-icon-loading', text: '扫描中' }
      }
      return configs[this.item.status] || configs.ok
    },

    // 缩略图 URL
    thumbUrl() {
      if (this.item.thumbUrl) {
        return this.item.thumbUrl
      }
      
      // 尝试从地图文件服务拼接
      if (this.mapFileBase && this.item.id) {
        return `${this.mapFileBase}/thumbs/${this.item.id}.jpg`
      }
      
      return null
    },


  },

  methods: {
    // 格式化时间
    formatDateTimeCompat,
    pickUpdatedAt,

    // 路由辅助函数
    buildNavTo,
    buildEditTo,
    buildCalibrateTo,
    buildConstructTo,
    pickId,
    
    // 处理选择变化
    handleSelectChange(checked) {
      this.$emit('selectChange', this.item.id, checked)
    },



    // 导航
    handleNavigation() {
      this.$emit('clickNav', this.item.id)
    },

    // 编辑
    handleEdit() {
      this.$emit('clickEdit', this.item.id)
    },

    // 更多操作
    async handleMoreAction(cmd) {
      const row = this.item;
      const id = pickId(row);
      
      switch(cmd) {
        case 'rename':
          // 优先：已有重命名弹框/方法
          if (typeof this.openRenameDialog === 'function') return this.openRenameDialog(row);
          if (this.renameDialog) { this.renameDialog.visible = true; this.renameDialog.row = row; return; }
          // 兜底：Element prompt
          this.$prompt('请输入新的地图名称', '重命名', {
            inputValue: row.mapName || row.name || '',
            inputPattern: /\S+/,
            inputErrorMessage: '名称不能为空'
          }).then(({ value }) => {
            // 若有旧方法：this.renameMap(id, value)
            if (typeof this.renameMap === 'function') return this.renameMap(id, value);
            row.mapName = value; 
            row.name = value;
            this.$message.success('已重命名'); // mock 刷新
          }).catch(()=>{});
          break;

        case 'download':
          // 触发父组件的下载对话框
          this.$emit('clickMore', this.item.id, 'download');
          break;

        case 'build':
          // 优先：旧路由/方法
          if (typeof this.openBuildDialog === 'function') return this.openBuildDialog(row);
          if (typeof this.constructOpen === 'boolean') {
            this.$parent.constructOpen = true;
            this.$parent.title = `构建地图 - ${row.name || row.mapName || ''}`;
            this.$parent.currentRow = row;
            return;
          }
          if (typeof this.toBuildPage === 'function') return this.toBuildPage(row);
          return this.$router.push(buildConstructTo(row));

        case 'delete':
          // 优先：旧删除方法
          if (typeof this.handleDelete === 'function') {
            return this.$confirm('确认删除该地图？此操作不可恢复', '删除地图', {type: 'warning'})
              .then(() => this.handleDelete([id]))
              .catch(() => {});
          }
          if (typeof this.deleteMap === 'function') {
            return this.$confirm('确认删除该地图？此操作不可恢复', '删除地图', {type: 'warning'})
              .then(() => this.deleteMap(id))
              .catch(() => {});
          }
          this.$confirm('确认删除该地图？此操作不可恢复', '删除地图', {type: 'warning'})
            .then(() => { 
              this.$emit && this.$emit('remove', row); 
              this.$message.success('已删除（mock）'); 
            })
            .catch(() => {});
          break;

        case 'calibrate':
          // 优先：旧路由/方法
          if (typeof this.openCalibration === 'function') return this.openCalibration(row);
          return this.$router.push(buildCalibrateTo(row));
          
        default:
          // 兼容原有的操作
          this.$emit('clickMore', this.item.id, cmd);
      }
    },

    // 图片加载失败
    handleImageError(event) {
      event.target.style.display = 'none'
    }
  }
}
</script>

<style lang="scss" scoped>
.map-card {
  position: relative;
  background: var(--color-bg-card);
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(2, 6, 23, 0.05);
  overflow: hidden;
  transition: all var(--duration-200) var(--ease-out);
  cursor: pointer;

  &:hover {
    box-shadow: 0 8px 24px rgba(2, 6, 23, 0.08);
    transform: translateY(-2px);

    .card-actions {
      opacity: 1;
      visibility: visible;
    }
  }

  &.selected {
    border: 2px solid var(--color-primary);
    box-shadow: 0 8px 24px rgba(64, 158, 255, 0.15);
  }

  &.selectable {
    .card-checkbox {
      opacity: 1;
      visibility: visible;
    }
  }

  .card-checkbox {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 3;
    opacity: 0;
    visibility: hidden;
    transition: all var(--duration-200) var(--ease-out);
    background: rgba(255, 255, 255, 0.9);
    border-radius: var(--radius-base);
    padding: 4px;
    backdrop-filter: blur(4px);
  }





  .card-thumb {
    position: relative;
    width: 100%;
    height: 160px;
    overflow: hidden;
    background: var(--color-bg-secondary);

    .thumb-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform var(--duration-300) var(--ease-out);
    }

    .thumb-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: var(--color-text-quaternary);
      background: linear-gradient(135deg, var(--color-bg-secondary) 0%, var(--color-bg-tertiary) 100%);

      i {
        font-size: var(--font-size-3xl);
        margin-bottom: var(--spacing-2);
        opacity: 0.6;
      }

      span {
        font-size: var(--font-size-sm);
        opacity: 0.8;
      }
    }

    &:hover .thumb-image {
      transform: scale(1.05);
    }
  }

  .card-status {
    position: absolute;
    top: 130px;
    left: 12px;
    z-index: 2;

    .status-tag {
      border: none;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(4px);

      i {
        margin-right: 4px;
      }
    }
  }

  .card-content {
    padding: 16px;
    padding-bottom: 60px; // 为操作按钮留空间

    .card-title {
      color: var(--color-text-primary);
      font-size: var(--font-size-lg);
      font-weight: var(--font-weight-semibold);
      margin: 0 0 var(--spacing-2) 0;
      line-height: var(--line-height-tight);
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      cursor: pointer;
      transition: color var(--duration-200) var(--ease-out);

      &:hover {
        color: var(--color-primary);
      }
    }

    .card-remark {
      color: var(--color-text-secondary);
      font-size: var(--font-size-sm);
      line-height: var(--line-height-normal);
      margin: 0 0 var(--spacing-3) 0;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .card-meta {
      .update-time {
        color: var(--color-text-tertiary);
        font-size: var(--font-size-xs);
        display: flex;
        align-items: center;
        gap: var(--spacing-1);

        i {
          font-size: var(--font-size-xs);
        }
      }
    }
  }

  .card-actions {
    position: absolute;
    bottom: 12px;
    left: 12px;
    right: 12px;
    display: flex;
    gap: var(--spacing-2);
    opacity: 0;
    visibility: hidden;
    transition: all var(--duration-200) var(--ease-out);

    &.show-on-mobile {
      @media (max-width: 768px) {
        opacity: 1;
        visibility: visible;
      }
    }

    .card-op-link {
      display: inline-flex;
      align-items: center;
      text-decoration: none;
      flex: 1;

      &:hover {
        text-decoration: none;
      }

      .el-button {
        width: 100%;
        border-radius: var(--radius-base);
        font-size: var(--font-size-xs);
        padding: 6px 12px;
      }
    }

    .el-button {
      flex: 0 0 auto;
      min-width: 32px;
      padding: 6px 8px;
      border-radius: var(--radius-base);
      font-size: var(--font-size-xs);
    }
  }
}

// 下拉菜单危险项样式
::v-deep .danger-item,
::v-deep .is-danger {
  color: var(--color-danger);

  &:hover {
    background: rgba(245, 108, 108, 0.1);
  }
}

// 更多菜单样式
::v-deep .xt-more .is-danger { 
  color: #e11d48; 
}
::v-deep .xt-more .is-danger i { 
  color: #e11d48; 
}

// 暗色主题适配
html.dark {
  .map-card {
    background: var(--color-bg-tertiary);
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);

    &:hover {
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
    }

    &.selected {
      box-shadow: 0 8px 24px rgba(64, 158, 255, 0.25);
    }

    .card-checkbox {
      background: rgba(0, 0, 0, 0.6);

      &:hover {
        background: rgba(0, 0, 0, 0.8);
      }
    }

    .card-thumb {
      .thumb-placeholder {
        background: linear-gradient(135deg, var(--color-bg-quaternary) 0%, var(--color-bg-tertiary) 100%);
      }
    }

    .status-tag {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }
  }
}

// 紧凑模式
.map-card.compact {
  .card-thumb {
    height: 120px;
  }

  .card-content {
    padding: 12px;
    padding-bottom: 50px;

    .card-title {
      font-size: var(--font-size-base);
      -webkit-line-clamp: 1;
    }

    .card-remark {
      -webkit-line-clamp: 1;
    }
  }

  .card-actions {
    bottom: 8px;
    left: 8px;
    right: 8px;
  }
}
</style>
