<template>
  <div class="new-app-container layout-vertical">
    <div style="margin-bottom: 15px;">
      <el-radio-group v-model="gameType" size="small" @change="onSubmit">
        <el-radio-button :label="1">极速赛车</el-radio-button>
        <el-radio-button :label="2">极速时时彩</el-radio-button>
        <el-radio-button :label="3">极速飞艇</el-radio-button>
        <el-radio-button :label="6">极速快3</el-radio-button>
        <el-radio-button :label="4">SG时时彩</el-radio-button>
        <el-radio-button :label="5">SG飞艇</el-radio-button>
        <el-radio-button :label="7">SG快3</el-radio-button>
      </el-radio-group>
    </div>

    <div
      style="height: calc(100% - 47px); 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.name }}
            </span>
            <span v-else>
              {{ data.name }}
            </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 { getjisuGameList, jisuGameSetOdds } from '@/api/data.js'

export default {
  name: 'JisuGameList',
  data() {
    return {
      gameType: 1,
      loading: false,
      submitLoading: false,
      tableData: [],
      dialogVisible: false,
      editConfig: {
        title: '编辑设置'
      },
      currentRowData: null,
      editFormModel: {
        id: null,
        gameplay: '',
        odds: '',
        maxinum: '',
        mininum: '',
        displayName: '',
        level: 1
      },
      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 getjisuGameList({ type: this.gameType })
        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(item1 => {
        const l1Node = {
          uniqueKey: 'l1_' + (++uniqueId),
          name: item1.gameplay,
          level: 1,
          gameplay: item1.gameplay,
          children: []
        }

        if (item1.children && Array.isArray(item1.children)) {
          l1Node.children = item1.children.map(item2 => {
            return {
              uniqueKey: 'l2_' + (item2.id || ++uniqueId),
              id: item2.id,
              name: item2.name,
              odds: item2.odds || '',
              maxinum: item2.maxinum || '',
              mininum: item2.mininum || '',
              level: 2,
              gameplay: item1.gameplay
            }
          })
        }
        return l1Node
      })
    },

    handleEdit(row) {
      this.currentRowData = row

      this.editFormModel = {
        id: row.id,
        gameplay: row.gameplay,
        odds: row.odds,
        maxinum: row.maxinum,
        mininum: row.mininum,
        displayName: row.name,
        level: row.level
      }
      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 = {
            type: this.gameType,
            odds: this.editFormModel.odds,
            mininum: this.editFormModel.mininum,
            maxinum: this.editFormModel.maxinum
          }

          if (this.editFormModel.level === 1) {
            params.gameplay = this.editFormModel.gameplay
          } else if (this.editFormModel.level === 2) {
            params.id = this.editFormModel.id
          }

          this.submitLoading = true
          try {
            await jisuGameSetOdds(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>
