<template>
  <div class="app-container">
    <!-- 操作按钮 -->
    <el-button-group class="m-b-20">
      <el-button type="primary" icon="el-icon-plus" @click="$router.replace('/mapstyle/add')">添加</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      <el-button type="warning" icon="el-icon-edit" @click="toEditPage()">编辑</el-button>
    </el-button-group>

    <!-- 样式表格 -->
    <el-table
      class="m-t-20 w-100"
      ref="myTable"
      :data="styleListPaged"
      border
      tooltip-effect="dark"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="40" />
      <el-table-column align="center" label="排序" width="120">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.sort_order"
            size="mini"
            style="width: 80px;"
            placeholder="排序"
            @focus="tempSort = scope.row.sort_order"
            @blur="blurOrder(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="60">
        <template slot-scope="scope">{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="name" label="样式名称" width="160" min-width="160">
        <template slot-scope="scope">{{ displayName(scope.row, scope.$index) }}</template>
      </el-table-column>
      <el-table-column prop="style" label="样式/URL" min-width="260" show-overflow-tooltip>
        <template slot-scope="scope">{{ displayStyle(scope.row) }}</template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination class="m-t-20" layout="prev, pager, next" :current-page.sync="currentPage" :page-size="pageSize"
      :total="styleList.length" />
  </div>
</template>

<script>
export default {
  name: 'MapStyleIndex',
  data () {
    return {
      pageSize: 8,
      currentPage: 1,
      tempSort: '',
      multipleSelection: []
    }
  },
  computed: {
    // 来自全局 store 的地图样式列表（已被 MapBox 使用）
    styleList () {
      // 允许为数组或对象数组，尽量宽容显示
      return Array.isArray(this.$store.state.mapStyleList) ? this.$store.state.mapStyleList : []
    },
    styleListPaged () {
      const start = (this.currentPage - 1) * this.pageSize
      return this.styleList.slice(start, start + this.pageSize)
    },
    // 是否有选中的行
    hasSelection () {
      return this.multipleSelection.length > 0
    }
  },
  created () {
    setTimeout(() => {
      console.log(this.styleList)
    }, 1000)
  },
  methods: {
    // 处理表格选择变化
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 删除选中的样式
    async handleDelete () {
      const selected = this.$refs.myTable.selection || []
      if (!selected.length) {
        this.$message.warning('请先选择要删除的样式')
        return
      }

      const ids = selected.map(item => item.id).filter(Boolean)
      if (!ids.length) {
        this.$message.warning('选中的样式没有有效的ID')
        return
      }

      try {
        await this.$store.dispatch('fetchDelMapStyle', ids)
        // 清空选择
        this.$refs.myTable.clearSelection()
      } catch (error) {
        console.error('删除失败:', error)
      }
    },
    displayName (row, idx) {
      // 兼容样式为字符串或对象（包含 name/title）
      if (typeof row === 'string') return `样式 ${idx + 1}`
      return row.name || row.title || `样式 ${idx + 1}`
    },
    displayStyle (row) {
      if (typeof row === 'string') return row
      // 常见字段：style/url/id
      return row.style || row.url || JSON.stringify(row)
    },
    // 排序input失焦 更新排序
    async blurOrder (row) {
      if (this.tempSort !== row.sort_order) {
        if (!row || row.id == null) {
          this.$message.warning('该样式缺少ID，无法排序')
          return
        }
        await this.$store.dispatch('fetchOrderMapStyle', {
          id: row.id,
          sort_order: row.sort_order
        })
      }
    },
    toEditPage () {
      const sel = this.$refs.myTable.selection || []
      if (!sel.length) {
        this.$message.warning('请选择一条需要编辑的记录')
        return
      }
      if (sel.length > 1) {
        this.$message.warning('只能选择一条记录')
        return
      }
      const row = sel[0]
      if (!row || row.id == null) {
        this.$message.error('此样式缺少后端ID，无法编辑')
        return
      }
      this.$router.push('/mapstyle/edit/' + row.id)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/theme.scss";
</style>
