<template>
  <div class="new-app-container layout-vertical">
    <div
      style="height:100%;  overflow-y: auto;"
    >
      <el-tree
        v-loading="loading"
        :data="tableData"
        node-key="uniqueKey"
        :default-expand-all="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="node-label">
            <span v-if="data.level === 2" class="el-tag el-tag--primary el-tag--light">
              {{ data.optionName }}
            </span>
            <span v-else>
              {{ data.gameName }}
            </span>
          </span>

          <span class="node-actions">
            <span class="node-info-item">
              <span v-show="data.level === 2">
                赔率:
                <span v-if="data.odds !== null && data.odds !== undefined && data.odds !== ''" style="color: #F56C6C; font-weight: bold;">
                  {{ data.odds }}
                </span>
                <span v-else>--</span>
              </span>
            </span>
            <span class="node-info-item">
              <span v-show="data.level === 2">
                最小:
                <span v-if="data.mininum !== null && data.mininum !== undefined && data.mininum !== ''" style="color: #67C23A; font-weight: bold;">
                  {{ data.mininum }}
                </span>
                <span v-else>--</span>
              </span>
            </span>
            <span class="node-info-item">
              <span v-show="data.level === 2">
                最大:
                <span v-if="data.maxinum !== null && data.maxinum !== undefined && data.maxinum !== ''" style="color: #E6A23C; font-weight: bold;">
                  {{ data.maxinum }}
                </span>
                <span v-else>--</span>
              </span>
            </span>

            <span class="node-btn">
              <el-button type="text" size="small" @click.stop="() => handleEdit(data)">编辑</el-button>
            </span>
          </span>
        </span>
      </el-tree>
    </div>

    <el-dialog :title="editConfig.title" :visible.sync="dialogVisible" width="400px" append-to-body>
      <el-form ref="editForm" :model="editFormModel" :rules="editRules" label-width="90px">
        <el-form-item label="名称">
          <el-input v-model="editFormModel.displayName" disabled />
        </el-form-item>
        <el-form-item label="赔率" prop="odds">
          <el-input v-model="editFormModel.odds" clearable placeholder="请输入赔率" />
        </el-form-item>
        <el-form-item label="最小限额" prop="mininum">
          <el-input v-model="editFormModel.mininum" clearable placeholder="请输入最小限额" />
        </el-form-item>
        <el-form-item label="最大限额" prop="maxinum">
          <el-input v-model="editFormModel.maxinum" clearable placeholder="请输入最大限额" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" :loading="submitLoading" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSportGameList, setSportGameOdds } from '@/api/data.js'

export default {
  name: 'SportGameList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      tableData: [],
      dialogVisible: false,
      editConfig: {
        title: '编辑设置'
      },
      currentRowData: null,
      editFormModel: {
        id: null,
        game_id: null,
        odds: '',
        maxinum: '',
        mininum: '',
        displayName: '',
        level: 1,
        game: ''
      },
      editRules: {
        odds: [
          { required: true, message: '请输入赔率', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?$/, message: '赔率必须是有效数字', trigger: 'blur' }
        ],
        mininum: [
          { required: true, message: '请输入最小限额', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?$/, message: '最小限额必须是有效数字', trigger: 'blur' }
        ],
        maxinum: [
          { required: true, message: '请输入最大限额', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?$/, message: '最大限额必须是有效数字', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.onSubmit()
  },
  methods: {
    async onSubmit() {
      this.loading = true
      try {
        const res = await getSportGameList()
        let resData = []
        if (res && res.data) {
          resData = res.data.data ? res.data.data : res.data
        }
        this.tableData = this.formatTreeData(resData)
      } catch (error) {
        console.error('获取列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    formatTreeData(data) {
      if (!data || !Array.isArray(data)) return []
      let uniqueId = 0

      return data.map(game => {
        const gameNode = {
          uniqueKey: 'game_' + (++uniqueId),
          id: game.id || null,
          game_id: game.id,
          gameName: game.name,
          odds: game.odds || '',
          maxinum: game.maxinum || '',
          mininum: game.mininum || '',
          level: 1,
          game: game.name,
          children: []
        }

        if (game.children && Array.isArray(game.children)) {
          gameNode.children = game.children.map(item => {
            return {
              uniqueKey: 'option_' + (item.id || ++uniqueId),
              id: item.id,
              game_id: item.game_id || game.id,
              optionName: item.name,
              odds: item.odds,
              maxinum: item.maxinum,
              mininum: item.mininum,
              level: 2,
              game: game.name
            }
          })
        }
        return gameNode
      })
    },

    handleEdit(row) {
      this.currentRowData = row

      const name = row.level === 1 ? row.gameName : row.optionName

      this.editFormModel = {
        id: row.id,
        game_id: row.game_id,
        odds: row.odds,
        maxinum: row.maxinum,
        mininum: row.mininum,
        displayName: name,
        level: row.level,
        game: row.game
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate()
      })
    },

    updateNodeAndChildrenData(node, newOdds, newMax, newMin) {
      node.odds = newOdds
      node.maxinum = newMax
      node.mininum = newMin
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.updateNodeAndChildrenData(child, newOdds, newMax, newMin)
        })
      }
    },

    confirmEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          const params = {
            id: this.editFormModel.id,
            game_id: this.editFormModel.game_id,
            odds: this.editFormModel.odds,
            mininum: this.editFormModel.mininum,
            maxinum: this.editFormModel.maxinum
          }

          this.submitLoading = true
          try {
            await setSportGameOdds(params)
            this.$message.success('修改成功')
            this.dialogVisible = false

            if (this.currentRowData) {
              this.updateNodeAndChildrenData(
                this.currentRowData,
                this.editFormModel.odds,
                this.editFormModel.maxinum,
                this.editFormModel.mininum
              )
            }
          } catch (error) {
            console.error('提交失败:', error)
          } finally {
            this.submitLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.new-app-container{
  height: calc(100vh - 100px);
  background: #fff;
  padding: 10px;
  margin: 20px;
  box-sizing: border-box;
  width: calc(100% - 40px);
  border-radius: 6px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 20px;
}
.node-label {
  flex: 1;
}
.node-actions {
  display: flex;
  align-items: center;
  width: 420px;
}
.node-info-item {
  width: 120px;
  text-align: left;
}
.node-btn {
  width: 60px;
  text-align: right;
}
::v-deep .el-tree-node__content {
  height: 40px;
  border-bottom: 1px solid #ebeef5;
}
</style>
