<template>
  <div class="config-list-container" style="padding: 10px;">
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      height="100%"
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" align="center" min-width="120"></el-table-column>

      <el-table-column prop="game" label="游戏标识" align="center" min-width="120"></el-table-column>

      <el-table-column label="状态" align="center" min-width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleSwitchChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="是否热门" align="center" min-width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_rec"
            :active-value="1"
            :inactive-value="0"
            @change="handleSwitchChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="排序" align="center" min-width="150">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.isEdit"
            v-model="scope.row.sort"
            :step="1"
            size="small"
            style="width: 120px;"
          ></el-input-number>
          <span v-else>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-button type="success" size="mini" @click="handleSave(scope.row)">保存</el-button>
            <el-button type="info" size="mini" @click="handleCancel(scope.row)">取消</el-button>
          </template>
          <template v-else>
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { gameList, setField } from '@/api/data.js'

export default {
  name: 'ConfigList',
  data() {
    return {
      tableData: [],
      loading: false
    }
  },
  created() {
    this.getListData()
  },
  methods: {
    // 获取列表数据
    async getListData() {
      this.loading = true
      try {
        const res = await gameList()
        // 假设接口正常返回code为0
        if (res && res.code === 0) {
          // 遍历注入控制视图和状态的辅助字段
          this.tableData = res.data.map(item => ({
            ...item,
            isEdit: false,
            _original: null
          }))
        }
      } catch (error) {
        console.error('获取列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 开启单行编辑
    handleEdit(row) {
      // 深拷贝备份当前行数据，用于取消编辑时还原
      row._original = JSON.parse(JSON.stringify(row))
      row.isEdit = true
    },

    // 取消编辑
    handleCancel(row) {
      // 还原数据并关闭编辑状态
      Object.assign(row, row._original)
      row.isEdit = false
    },

    // 状态或推荐开关切换触发保存
    async handleSwitchChange(row) {
      const submitData = this.tableData.map(item => {
        const { isEdit, _original, ...pureData } = item
        return pureData
      })

      try {
        const res = await setField({
          field: 'game_list',
          val: submitData
        })

        if (res && res.code === 0) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.msg || '保存失败')
          // 保存失败时重新获取数据还原开关状态
          this.getListData()
        }
      } catch (error) {
        console.error('保存接口异常:', error)
        this.$message.error('接口异常，保存失败')
        // 异常时重新获取数据还原开关状态
        this.getListData()
      }
    },

    // 提交保存
    async handleSave(row) {
      row.isEdit = false

      // 构造全量列表数据，剔除前端辅助字段
      const submitData = this.tableData.map(item => {
        const { isEdit, _original, ...pureData } = item
        return pureData
      })

      try {
        const res = await setField({
          field: 'game_list',
          val: submitData
        })

        // 假设接口保存成功返回code为0
        if (res && res.code === 0) {
          this.$message.success('保存成功')
          // 保存成功后可以选择重新拉取最新数据
          this.getListData()
        } else {
          this.$message.error(res.msg || '保存失败')
          this.handleCancel(row)
        }
      } catch (error) {
        console.error('保存接口异常:', error)
        this.$message.error('接口异常，保存失败')
        this.handleCancel(row)
      }
    }
  }
}
</script>

<style scoped>
.config-list-container {
  margin: 20px;
  height: calc(100vh - 90px);
  background-color: #fff;
}
</style>
