<template>
  <div class="recharge-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">

      <el-tab-pane label="通道管理" name="channels">
        <el-tabs v-model="channelQuery.data_type" style="margin-bottom: 15px;" @tab-click="getChannels">
          <el-tab-pane label="充值" name="1"></el-tab-pane>
          <el-tab-pane label="提现" name="2"></el-tab-pane>
          <el-tab-pane label="活动" name="3"></el-tab-pane>
        </el-tabs>

        <el-form :inline="true" :model="channelQuery" class="filter-form">
          <el-form-item label="名称">
            <el-input v-model="channelQuery.name" clearable placeholder="通道名称"></el-input>
          </el-form-item>
          <el-form-item label="标识(Key)">
            <el-input v-model="channelQuery.key" clearable placeholder="如: USDT"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="getChannels">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="channelLoading" :data="channelList" border
                  height="calc(100vh - 310px)"
                  style="width: 100%"
        >
          <el-table-column align="center" label="ID" prop="id" width="60"></el-table-column>
          <el-table-column label="名称" min-width="120" prop="name"></el-table-column>
          <el-table-column label="标识(Key)" prop="key" width="120"></el-table-column>
          <el-table-column label="类型" prop="type" width="100"></el-table-column>
          <el-table-column label="费率" prop="rate" width="100"></el-table-column>
          <el-table-column align="center" label="限额(最小/最大)" min-width="150">
            <template slot-scope="scope">
              {{ scope.row.min || '0' }} / {{ scope.row.max || '无' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="排序" prop="sort" width="80"></el-table-column>
          <el-table-column align="center" label="状态" prop="status" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="openChannelDialog(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="层级设置" name="groups">
        <div class="action-bar" style="margin-bottom: 20px;">
          <el-button icon="el-icon-plus" type="success" @click="openGroupDialog()">新增组合</el-button>
        </div>

        <el-table v-loading="groupLoading" :data="groupList" border
                  height="calc(100vh - 220px)"
                  style="width: 100%"
        >
          <el-table-column align="center" label="组合ID" prop="id" width="80"></el-table-column>
          <el-table-column label="组合名称" min-width="150" prop="name"></el-table-column>

          <el-table-column label="充值配置" min-width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="channel in scope.row.rechargeTypes"
                :key="channel.id"
                size="mini"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ channel.name }}
              </el-tag>
              <span v-if="!scope.row.rechargeTypes || scope.row.rechargeTypes.length === 0">-</span>
            </template>
          </el-table-column>

          <el-table-column label="提现配置" min-width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="channel in scope.row.withdrawTypes"
                :key="channel.id"
                size="mini"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ channel.name }}
              </el-tag>
              <span v-if="!scope.row.withdrawTypes || scope.row.withdrawTypes.length === 0">-</span>
            </template>
          </el-table-column>

          <el-table-column label="活动配置" min-width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="channel in scope.row.activityTypes"
                :key="channel.id"
                size="mini"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ channel.name }}
              </el-tag>
              <span v-if="!scope.row.activityTypes || scope.row.activityTypes.length === 0">-</span>
            </template>
          </el-table-column>

          <el-table-column align="center" fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="openGroupDialog(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :title="channelForm.id ? '编辑通道状态' : '新增通道'" :visible.sync="channelDialogVisible" width="550px">
      <el-form :model="channelForm" label-width="100px" size="small">
        <template v-if="!channelForm.id">
          <el-form-item label="通道名称">
            <el-input v-model="channelForm.name"></el-input>
          </el-form-item>
          <el-form-item label="标识(Key)">
            <el-input v-model="channelForm.key"></el-input>
          </el-form-item>
          <el-form-item label="类型(Type)">
            <el-input v-model="channelForm.type"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="费率">
                <el-input v-model="channelForm.rate"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序">
                <el-input-number v-model="channelForm.sort" style="width: 100%"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-form-item label="通道状态">
          <el-radio-group v-model="channelForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="channelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitChannelForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="groupForm.id ? '编辑组合' : '新增组合'" :visible.sync="groupDialogVisible" width="650px">
      <el-form :model="groupForm" label-width="80px" size="small">
        <el-form-item label="组合名称">
          <el-input v-model="groupForm.name" placeholder="请输入组合名称"></el-input>
        </el-form-item>

        <el-form-item label="充值通道">
          <div class="channel-selector-card">
            <el-checkbox-group v-model="groupForm.recharge_type">
              <el-checkbox
                v-for="(item, index) in rechargeChannelPool"
                :key="item.type || index"
                :label="item.type"
                border
                class="channel-checkbox-item"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item label="提现通道">
          <div class="channel-selector-card">
            <el-checkbox-group v-model="groupForm.withdraw_type">
              <el-checkbox
                v-for="(item, index) in withdrawChannelPool"
                :key="item.type || index"
                :label="item.type"
                border
                class="channel-checkbox-item"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item label="活动通道">
          <div class="channel-selector-card">
            <el-checkbox-group v-model="groupForm.activity_type">
              <el-checkbox
                v-for="(item, index) in activityChannelPool"
                :key="item.type || index"
                :label="item.type"
                border
                class="channel-checkbox-item"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="groupDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGroupForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getRechargeChannelList,
  updateRechargeChannel,
  getRechargeChannelGroupList,
  updateRechargeChannelGroup,
  getRechargeChannelGetChannel
} from '@/api/data'

export default {
  name: 'RechargeChannelPage',
  data() {
    return {
      activeTab: 'channels',
      // 通道列表
      channelLoading: false,
      channelList: [],
      channelQuery: { key: '', name: '', data_type: '1' },
      // 通道表单
      channelDialogVisible: false,
      channelForm: { id: null, status: 1, name: '', key: '', type: '', rate: '', sort: 0 },

      // 组合列表
      groupLoading: false,
      groupList: [],
      groupQuery: {},
      // 组合表单
      groupDialogVisible: false,
      groupForm: { id: null, name: '', recharge_type: [], withdraw_type: [], activity_type: [] },

      // 分别存储三种类型的候选通道池
      rechargeChannelPool: [],
      withdrawChannelPool: [],
      activityChannelPool: []
    }
  },
  created() {
    this.getChannels()
  },
  methods: {
    handleTabClick(tab) {
      if (tab.name === 'channels') this.getChannels()
      if (tab.name === 'groups') {
        this.getGroups()
        this.loadChannelPool()
      }
    },
    // --- 通道管理逻辑 ---
    async getChannels() {
      this.channelLoading = true
      try {
        const res = await getRechargeChannelList(this.channelQuery)
        if (res.code === 0) {
          this.channelList = res.data.data || []
        }
      } finally {
        this.channelLoading = false
      }
    },
    openChannelDialog(row) {
      if (row) {
        // 编辑模式：只关注 ID 和状态
        this.channelForm = { id: row.id, status: row.status }
      } else {
        // 兼容原逻辑
        this.channelForm = { id: null, status: 1, name: '', key: '', type: '', rate: '', sort: 0 }
      }
      this.channelDialogVisible = true
    },
    async submitChannelForm() {
      const res = await updateRechargeChannel(this.channelForm)
      if (res.code === 0) {
        this.$message.success('操作成功')
        this.channelDialogVisible = false
        this.getChannels()
      }
    },

    // --- 通道组合逻辑 ---
    async getGroups() {
      this.groupLoading = true
      try {
        const res = await getRechargeChannelGroupList(this.groupQuery)
        if (res.code === 0) {
          this.groupList = res.data.data || []
        }
      } finally {
        this.groupLoading = false
      }
    },

    // 按 data_type 请求三个列表
    async loadChannelPool() {
      this.rechargeChannelPool = await this.fetchChannelByDataType('1')
      this.withdrawChannelPool = await this.fetchChannelByDataType('2')
      this.activityChannelPool = await this.fetchChannelByDataType('3')
    },
    async fetchChannelByDataType(dataType) {
      const res = await getRechargeChannelGetChannel({ data_type: dataType })
      if (res.code === 0) {
        const list = res.data?.data || []
        const uniqueList = []
        const map = new Map()
        for (const item of list) {
          if (!map.has(item.type)) {
            map.set(item.type, true)
            uniqueList.push(item)
          }
        }
        return uniqueList
      }
      return []
    },

    openGroupDialog(row) {
      if (row) {
        this.groupForm = {
          id: row.id,
          name: row.name,
          recharge_type: row.recharge_type || [],
          withdraw_type: row.withdraw_type || [],
          activity_type: row.activity_type || []
        }
      } else {
        this.groupForm = { id: null, name: '', recharge_type: [], withdraw_type: [], activity_type: [] }
      }
      this.groupDialogVisible = true
    },
    async submitGroupForm() {
      const res = await updateRechargeChannelGroup(this.groupForm)
      if (res.code === 0) {
        this.$message.success('保存成功')
        this.groupDialogVisible = false
        this.getGroups()
      }
    }
  }
}
</script>

<style scoped>
.recharge-container {
  margin: 20px;
}

.filter-form {
  margin-bottom: 20px;
}

/* 选框组样式优化 */
.channel-selector-card {
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.channel-checkbox-item {
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 10px;
}
</style>
