<template>
  <div class="new-app-container layout-vertical">
    <div style="margin-bottom: 15px;">
      <el-radio-group v-model="gameType" size="small" @change="onTabChange">
        <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-button label="lhc">六合彩</el-radio-button>
        <el-radio-button label="pc28">28</el-radio-button>
      </el-radio-group>
    </div>

    <template v-if="typeof gameType === 'number'">
      <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>
    </template>

    <template v-else-if="gameType === 'lhc'">
      <div style="height: calc(100% - 47px); overflow-y: auto;">
        <el-tree
          v-loading="loading"
          :data="lhcTableData"
          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 === 3" class="el-tag el-tag--primary el-tag--light">
                {{ data.numberName }}
              </span>
              <span v-else-if="data.level === 2">
                {{ data.gameplayName }}
              </span>
              <span v-else>
                {{ data.gameName }}
              </span>
            </span>

            <span class="node-actions">
              <span class="node-info-item">
                <span v-show="data.level === 3">
                  赔率:
                  <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 === 3">
                  最小:
                  <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 === 3">
                  最大:
                  <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="() => handleLhcEdit(data)">编辑</el-button>
              </span>
            </span>
          </span>
        </el-tree>
      </div>

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

    <template v-else-if="gameType === 'pc28'">
      <div style="height: calc(100% - 47px);">
        <YMTable
          ref="table"
          :table-key="1"
          :index="true"
          :selection="false"
          :table-options="tableOptions"
          :edit-form="editForm"
          :edit-config="pcEditConfig"
          :columns="columns"
          :rows-actions="rowsActions"
          :show-summary="false"
          :apis="apis"
          :custom-style="{ height: 'calc(100vh - 80px)' }"
        />
        <Dialog ref="dialog">
          <template slot="content" />
        </Dialog>
      </div>
    </template>
  </div>
</template>

<script>
import { getjisuGameList, jisuGameSetOdds } from '@/api/data.js'
import { lhcNumberList, lhcNumberSetOdds } from '@/api/data'
import Dialog from '@/components/Dialog/index.vue'

export default {
  name: 'JisuGameList',
  components: {
    Dialog
  },
  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' }
        ]
      },

      // --- 六合彩数据 ---
      lhcTableData: [],
      lhcDialogVisible: false,
      lhcCurrentRowData: null,
      lhcEditFormModel: {
        id: null,
        odds: '',
        maxinum: '',
        mininum: '',
        displayName: '',
        level: 1,
        game: '',
        gameplay: ''
      },

      // --- 28数据 ---
      visibleBasicDrawer: false,
      renderContent: '',
      searchForm: [],
      columns: [
        { label: '总和', prop: 'groups' },
        { label: '玩法', prop: 'keywords' },
        { label: '最高投注', prop: 'maxinum' },
        { label: '最低投注', prop: 'mininum' },
        { label: '倍率', prop: 'odds' }
      ],
      rowsActions: [
        { key: 'edit', label: '编辑' },
        { key: 'delete', label: '删除' }
      ],
      apis: {
        list: { url: 'gameplayRule', dataParam: 'data.data', resultParam: 'data', init: false },
        add: { url: 'gameplayRule/submit' },
        edit: { url: 'gameplayRule/submit' },
        delete: { url: 'gameplayRule/delete', method: 'post' }
      },
      tableOptions: {
        add: { show: true },
      },
      editForm: [
        {
          body: [
            { label: '总和', type: 'input', prop: 'groups', clearable: false, rules: [{ required: true, message: '请输入总和', trigger: 'blur' }] },
            { label: '玩法', type: 'input', prop: 'keywords', clearable: false, rules: [{ required: true, message: '请输入玩法', trigger: 'blur' }] },
            { label: '最高投注', type: 'input', prop: 'maxinum', clearable: false, rules: [{ required: true, message: '请输入最高投注', trigger: 'blur' }] },
            { label: '最低投注', type: 'input', prop: 'mininum', clearable: false, rules: [{ required: true, message: '请输入最低投注', trigger: 'blur' }] },
            { label: '倍率', type: 'input', prop: 'odds', clearable: false, rules: [{ required: true, message: '请输入倍率', trigger: 'blur' }] }
          ]
        }
      ],
      pcEditConfig: {}
    }
  },
  mounted() {
    this.onTabChange()
  },
  methods: {
    // Tab栏点击跳转方法
    onTabChange() {
      if (typeof this.gameType === 'number') {
        this.onSubmit()
      } else if (this.gameType === 'lhc') {
        this.onLhcSubmit()
      } else if (this.gameType === 'pc28') {
        this.$nextTick(() => {
          this.onPcSubmit()
        })
      }
    },

    // --- 极速系列方法 ---
    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
          }
        }
      })
    },

    // --- 六合彩方法 ---
    async onLhcSubmit() {
      this.loading = true
      try {
        const res = await lhcNumberList()
        let resData = []
        if (res && res.data) {
          resData = res.data.data ? res.data.data : res.data
        }
        this.lhcTableData = this.formatLhcTreeData(resData)
      } catch (error) {
        console.error('获取列表失败:', error)
      } finally {
        this.loading = false
      }
    },

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

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

        if (game.children) {
          const gameplayList = Array.isArray(game.children) ? game.children : Object.values(game.children)

          gameplayList.forEach(gameplay => {
            const gameplayNode = {
              uniqueKey: 'gameplay_' + (++uniqueId),
              id: gameplay.id || null,
              gameplayName: gameplay.name,
              odds: gameplay.odds || '',
              maxinum: gameplay.maxinum || '',
              mininum: gameplay.mininum || '',
              level: 2,
              game: game.name,
              gameplay: gameplay.name,
              children: []
            }

            if (gameplay.children && Array.isArray(gameplay.children)) {
              gameplayNode.children = gameplay.children.map(item => {
                return {
                  uniqueKey: 'num_' + (item.id || ++uniqueId),
                  id: item.id,
                  numberName: item.number,
                  odds: item.odds,
                  maxinum: item.maxinum,
                  mininum: item.mininum,
                  level: 3,
                  game: game.name,
                  gameplay: gameplay.name
                }
              })
            }
            gameNode.children.push(gameplayNode)
          })
        }
        return gameNode
      })
    },

    handleLhcEdit(row) {
      this.lhcCurrentRowData = row

      const name = row.level === 1 ? row.gameName : (row.level === 2 ? row.gameplayName : row.numberName)

      this.lhcEditFormModel = {
        id: row.id,
        odds: row.odds,
        maxinum: row.maxinum,
        mininum: row.mininum,
        displayName: name,
        level: row.level,
        game: row.game,
        gameplay: row.gameplay
      }
      this.lhcDialogVisible = true
      this.$nextTick(() => {
        this.$refs.lhcEditForm && this.$refs.lhcEditForm.clearValidate()
      })
    },

    updateLhcNodeAndChildrenData(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.updateLhcNodeAndChildrenData(child, newOdds, newMax, newMin)
        })
      }
    },

    confirmLhcEdit() {
      this.$refs.lhcEditForm.validate(async valid => {
        if (valid) {
          const params = {
            id: this.lhcEditFormModel.id,
            odds: this.lhcEditFormModel.odds,
            maxinum: this.lhcEditFormModel.maxinum,
            mininum: this.lhcEditFormModel.mininum
          }

          if (this.lhcEditFormModel.level === 1) {
            params.game = this.lhcEditFormModel.game
          } else if (this.lhcEditFormModel.level === 2) {
            params.game = this.lhcEditFormModel.game
            params.gameplay = this.lhcEditFormModel.gameplay
          }

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

            if (this.lhcCurrentRowData) {
              this.updateLhcNodeAndChildrenData(
                this.lhcCurrentRowData,
                this.lhcEditFormModel.odds,
                this.lhcEditFormModel.maxinum,
                this.lhcEditFormModel.mininum
              )
            }
          } catch (error) {
            console.error('提交失败:', error)
          } finally {
            this.submitLoading = false
          }
        }
      })
    },

    // --- 28方法 ---
    handleSubmit(formData) {
      console.log('提交数据:', formData)
    },
    handleClickDrawer(row) {
    },
    onValueChange(val) {
    },
    onPcSubmit(params) {
      this.$refs.table && this.$refs.table.getList(params)
    }
  }
}
</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>
