<template>
  <div class="dist-page">
    <el-card shadow="never" class="tabs-card">
      <div class="dist-tabs">
        <div v-for="t in tabs" :key="t.key" class="dist-tab" :class="{active: activeTab===t.key}" @click="switchTab(t.key)">
          <span class="t-icon">{{ t.icon }}</span>
          <span>{{ t.label }}</span>
        </div>
      </div>
    </el-card>

    <!-- Tab1: 分销员管理 -->
    <div v-show="activeTab==='agents'">
      <el-card shadow="never" class="filter-card">
        <el-form inline>
          <el-form-item label="搜索"><el-input v-model="agentFilter.keyword" placeholder="昵称/手机号" clearable style="width:180px" @clear="fetchAgents" @keyup.enter="fetchAgents" /></el-form-item>
          <el-form-item label="状态"><el-select v-model="agentFilter.status" placeholder="全部" clearable style="width:120px" @change="fetchAgents"><el-option label="已启用" value="active" /><el-option label="已禁用" value="disabled" /></el-select></el-form-item>
          <el-form-item label="等级"><el-select v-model="agentFilter.level" placeholder="全部" clearable style="width:140px" @change="fetchAgents"><el-option v-for="l in distLevels" :key="l.id" :label="l.name" :value="l.level" /></el-select></el-form-item>
          <el-form-item><el-button type="primary" @click="fetchAgents"><el-icon><Search /></el-icon>搜索</el-button></el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="never">
        <el-table :data="agentList" border v-loading="agentLoading" style="width:100%">
          <el-table-column label="分销商" min-width="160">
            <template #default="{ row }"><el-avatar :size="28" :src="row.avatar" style="margin-right:6px" />{{ row.nickname }}</template>
          </el-table-column>
          <el-table-column label="手机号" width="130" align="center"><template #default="{ row }">{{ row.phone || '-' }}</template></el-table-column>
          <el-table-column label="分销等级" width="100" align="center">
            <template #default="{ row }"><el-tag size="small">{{ row.dist_level_name || '普通' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="团队人数" width="90" align="center"><template #default="{ row }">{{ row.team_count || 0 }}人</template></el-table-column>
          <el-table-column label="累计佣金" width="110" align="center"><template #default="{ row }">¥{{ row.total_commission || 0 }}</template></el-table-column>
          <el-table-column label="可提现" width="100" align="center"><template #default="{ row }">¥{{ row.balance || 0 }}</template></el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }"><el-switch v-model="row.distributor_status" active-value="active" inactive-value="disabled" size="small" @change="v=>toggleAgent(row,v)" /></template>
          </el-table-column>
          <el-table-column label="申请时间" width="160" align="center"><template #default="{ row }">{{ row.created_at }}</template></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }"><el-button size="small" @click="showAgentDetail(row)">详情</el-button></template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper"><el-pagination v-model:page-size="agentPS" v-model:current-page="agentP" :total="agentTotal" layout="total,prev,pager,next" @current-change="fetchAgents" /></div>
      </el-card>
    </div>

    <!-- Tab2: 分销员申请 -->
    <div v-show="activeTab==='applies'">
      <el-card shadow="never" class="filter-card">
        <el-form inline>
          <el-form-item label="状态"><el-select v-model="applyFilter.status" placeholder="全部" clearable style="width:130px" @change="fetchApplies"><el-option label="待审核" value="pending" /><el-option label="已通过" value="approved" /><el-option label="已拒绝" value="rejected" /></el-select></el-form-item>
          <el-form-item><el-button type="primary" @click="fetchApplies"><el-icon><Search /></el-icon>搜索</el-button></el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="never">
        <el-table :data="applyList" border v-loading="applyLoading" style="width:100%">
          <el-table-column label="申请人" width="140"><template #default="{ row }">{{ row.nickname }}</template></el-table-column>
          <el-table-column label="手机号" width="130" align="center"><template #default="{ row }">{{ row.user_phone || row.phone }}</template></el-table-column>
          <el-table-column label="真实姓名" width="100"><template #default="{ row }">{{ row.real_name || '-' }}</template></el-table-column>
          <el-table-column label="微信号" width="120"><template #default="{ row }">{{ row.wechat || '-' }}</template></el-table-column>
          <el-table-column label="申请理由" min-width="180"><template #default="{ row }">{{ row.reason || '-' }}</template></el-table-column>
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }"><el-tag :type="row.status==='approved'?'success':row.status==='rejected'?'danger':'warning'" size="small">{{ {pending:'待审核',approved:'已通过',rejected:'已拒绝'}[row.status] }}</el-tag></template>
          </el-table-column>
          <el-table-column label="申请时间" width="160" align="center"><template #default="{ row }">{{ row.created_at }}</template></el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="{ row }">
              <template v-if="row.status==='pending'">
                <el-button size="small" type="success" @click="approveApply(row)">通过</el-button>
                <el-button size="small" type="danger" @click="rejectApply(row)">拒绝</el-button>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper"><el-pagination v-model:page-size="applyPS" v-model:current-page="applyP" :total="applyTotal" layout="total,prev,pager,next" @current-change="fetchApplies" /></div>
      </el-card>
    </div>

    <!-- Tab3: 分销等级 -->
    <div v-show="activeTab==='levels'">
      <el-card shadow="never">
        <div class="section-header"><h3>分销等级配置</h3><el-button size="small" type="primary" @click="addDistLevel"><el-icon><Plus /></el-icon>新增等级</el-button></div>
        <el-table :data="distLevels" border style="width:100%">
          <el-table-column label="等级名称" width="140">
            <template #default="{ row }"><el-input v-if="row._edit" v-model="row.name" size="small" style="width:120px" /><span v-else>{{ row.name }}</span></template>
          </el-table-column>
          <el-table-column label="团队人数≥" width="110" align="center">
            <template #default="{ row }"><el-input-number v-if="row._edit" v-model="row.min_team_count" :min="0" size="small" style="width:100px" /><span v-else>{{ row.min_team_count }}</span></template>
          </el-table-column>
          <el-table-column label="销售额≥" width="130" align="center">
            <template #default="{ row }"><el-input-number v-if="row._edit" v-model="row.min_team_sales" :min="0" :precision="2" size="small" style="width:110px" /><span v-else>¥{{ row.min_team_sales }}</span></template>
          </el-table-column>
          <el-table-column label="一级佣金" width="110" align="center">
            <template #default="{ row }"><el-input-number v-if="row._edit" v-model="row.commission_rate" :min="0" :max="1" :step="0.01" :precision="4" size="small" style="width:100px" /><span v-else>{{ (row.commission_rate*100).toFixed(1) }}%</span></template>
          </el-table-column>
          <el-table-column label="二级佣金" width="110" align="center">
            <template #default="{ row }"><el-input-number v-if="row._edit" v-model="row.commission_rate2" :min="0" :max="1" :step="0.01" :precision="4" size="small" style="width:100px" /><span v-else>{{ (row.commission_rate2*100).toFixed(1) }}%</span></template>
          </el-table-column>
          <el-table-column label="三级佣金" width="110" align="center">
            <template #default="{ row }"><el-input-number v-if="row._edit" v-model="row.commission_rate3" :min="0" :max="1" :step="0.01" :precision="4" size="small" style="width:100px" /><span v-else>{{ (row.commission_rate3*100).toFixed(1) }}%</span></template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="{ row, $index }">
              <el-button v-if="!row._edit" size="small" @click="editDistLevel(row)">编辑</el-button>
              <el-button v-if="row._edit" size="small" type="primary" @click="saveDistLevel(row)">保存</el-button>
              <el-popconfirm title="确定删除？" @confirm="deleteDistLevel($index)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- Tab4: 分销设置（CRMEB完整版）-->
    <div v-show="activeTab==='settings'">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">

        <!-- 左列：分销模式+关系绑定 -->
        <el-card shadow="never">
          <h4 class="card-title">分销模式</h4>
          <el-form label-width="140px">
            <el-form-item label="分销模式">
              <el-radio-group v-model="distSettings.dist_mode">
                <el-radio value="designated">指定分销</el-radio>
                <el-radio value="everyone">人人分销</el-radio>
                <el-radio value="threshold">满额分销</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="distSettings.dist_mode==='threshold'" label="消费满额(元)">
              <el-input-number v-model="distSettings.threshold_amount" :min="0" :precision="2" style="width:160px" />
            </el-form-item>
          </el-form>

          <el-divider />
          <h4 class="card-title">分销关系绑定</h4>
          <el-form label-width="140px">
            <el-form-item label="绑定模式">
              <el-radio-group v-model="distSettings.bind_mode">
                <el-radio value="auto">自动绑定</el-radio>
                <el-radio value="manual">手动绑定</el-radio>
                <el-radio value="qrcode">扫码绑定</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="绑定有效期(天)">
              <el-input-number v-model="distSettings.bind_valid_days" :min="1" :max="3650" style="width:160px" />
              <span class="tip">到期后关系自动解除</span>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 右列：返佣设置+提现设置 -->
        <el-card shadow="never">
          <h4 class="card-title">返佣设置</h4>
          <el-form label-width="140px">
            <el-form-item label="分销层级">
              <el-select v-model="distSettings.commission_levels" style="width:160px">
                <el-option label="一级分销" value="1" />
                <el-option label="二级分销" value="2" />
                <el-option label="三级分销" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="自购返佣">
              <el-switch v-model="distSettings.self_buy" active-value="1" inactive-value="0" />
            </el-form-item>
            <el-form-item label="自动结算天数">
              <el-input-number v-model="distSettings.auto_settle_days" :min="0" :max="90" style="width:160px" />
              <span class="tip">天</span>
            </el-form-item>
          </el-form>

          <el-divider />
          <h4 class="card-title">提现设置</h4>
          <el-form label-width="140px">
            <el-form-item label="最低提现金额">
              <el-input-number v-model="distSettings.min_withdraw" :min="0" :precision="2" style="width:160px" />
              <span class="tip">¥</span>
            </el-form-item>
            <el-form-item label="提现手续费率">
              <el-input-number v-model="distSettings.withdraw_fee_rate" :min="0" :max="100" :precision="1" style="width:160px" />
              <span class="tip">%</span>
            </el-form-item>
            <el-form-item label="提现方式">
              <el-checkbox-group v-model="distSettings.withdraw_methods">
                <el-checkbox label="wechat" value="wechat" checked>微信</el-checkbox>
                <el-checkbox label="alipay" value="alipay">支付宝</el-checkbox>
                <el-checkbox label="bank" value="bank">银行卡</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 左：开关设置 -->
        <el-card shadow="never">
          <h4 class="card-title">功能开关</h4>
          <el-form label-width="160px">
            <el-form-item label="开启分销">
              <el-switch v-model="distSettings.is_open" active-value="1" inactive-value="0" />
            </el-form-item>
            <el-form-item label="事业部">
              <el-switch v-model="distSettings.division_enabled" active-value="1" inactive-value="0" />
            </el-form-item>
            <el-form-item label="代理商申请">
              <el-switch v-model="distSettings.agent_apply_enabled" active-value="1" inactive-value="0" />
              <span class="tip">关闭后隐藏申请入口</span>
            </el-form-item>
            <el-form-item label="佣金悬浮窗">
              <el-switch v-model="distSettings.commission_float_enabled" active-value="1" inactive-value="0" />
              <span class="tip">前台商品页显示佣金悬浮窗</span>
            </el-form-item>
            <el-form-item label="申请审核">
              <el-select v-model="distSettings.apply_type" style="width:200px">
                <el-option label="无需审核，自动通过" value="auto" />
                <el-option label="需管理员审核" value="manual" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 右：海报 -->
        <el-card shadow="never">
          <h4 class="card-title">分销海报图</h4>
          <el-form label-width="100px">
            <el-form-item label="海报模板">
              <el-upload :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false" :on-success="r=>{distSettings.poster_image=r.data.url}">
                <el-button size="small">上传海报</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="">
              <template v-if="distSettings.poster_image">
                <el-image :src="distSettings.poster_image" style="max-width:260px;border-radius:8px;border:1px solid #eee" />
                <el-button size="small" type="danger" link @click="distSettings.poster_image=''">删除</el-button>
              </template>
              <span v-else class="tip" style="font-size:12px">建议尺寸 375×812px，分销员推广用</span>
            </el-form-item>
          </el-form>
        </el-card>

      </div>

      <div style="text-align:center;margin-top:20px">
        <el-button type="primary" :loading="settingsLoading" size="large" @click="saveDistSettings">💾 保存全部设置</el-button>
      </div>
    </div>

    <!-- Tab5: 事业部 -->
    <div v-show="activeTab==='divisions'">
      <el-card shadow="never">
        <div class="section-header"><h3>事业部管理</h3><el-button size="small" type="primary" @click="showDivisionDialog=true"><el-icon><Plus /></el-icon>新增事业部</el-button></div>
        <el-table :data="divisionList" border v-loading="divLoading" style="width:100%">
          <el-table-column label="事业部名称" width="160"><template #default="{ row }">{{ row.name }}</template></el-table-column>
          <el-table-column label="负责人" width="120"><template #default="{ row }">{{ row.manager_name || '-' }}</template></el-table-column>
          <el-table-column label="成员数" width="80" align="center"><template #default="{ row }">{{ row.member_count || 0 }}</template></el-table-column>
          <el-table-column label="总销售额" width="120" align="center"><template #default="{ row }">¥{{ row.total_sales || 0 }}</template></el-table-column>
          <el-table-column label="佣金比例" width="100" align="center"><template #default="{ row }">{{ row.commission_rate || 0 }}%</template></el-table-column>
          <el-table-column label="说明" min-width="180"><template #default="{ row }">{{ row.description || '-' }}</template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{ row }"><el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'启用':'停用' }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }"><el-button size="small" @click="editDivision(row)">编辑</el-button><el-popconfirm title="确定删除？" @confirm="deleteDivision(row)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分销员详情弹窗 -->
    <el-dialog v-model="agentDetailVisible" title="分销员详情" width="500px">
      <template v-if="agentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="昵称" span="2">{{ agentDetail.nickname }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ agentDetail.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ agentDetail.distributor_real_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="微信号">{{ agentDetail.distributor_wechat || '-' }}</el-descriptions-item>
          <el-descriptions-item label="分销等级">{{ agentDetail.dist_level_name || '普通' }}</el-descriptions-item>
          <el-descriptions-item label="团队人数">{{ agentDetail.team_count || 0 }}人</el-descriptions-item>
          <el-descriptions-item label="累计佣金">¥{{ agentDetail.total_commission || 0 }}</el-descriptions-item>
          <el-descriptions-item label="可提现余额">¥{{ agentDetail.balance || 0 }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-dialog>

    <!-- 拒绝理由弹窗 -->
    <el-dialog v-model="rejectVisible" title="拒绝申请" width="400px">
      <el-form><el-form-item label="拒绝原因"><el-input v-model="rejectReason" type="textarea" :rows="3" placeholder="可选" /></el-form-item></el-form>
      <template #footer><el-button @click="rejectVisible=false">取消</el-button><el-button type="primary" @click="confirmReject">确认拒绝</el-button></template>
    </el-dialog>

    <!-- 事业部弹窗 -->
    <el-dialog v-model="showDivisionDialog" :title="editingDivision ? '编辑事业部' : '新增事业部'" width="450px">
      <el-form :model="divisionForm" label-width="100px">
        <el-form-item label="事业部名称"><el-input v-model="divisionForm.name" placeholder="如：华南事业部" /></el-form-item>
        <el-form-item label="负责人"><el-input v-model="divisionForm.manager_id" placeholder="用户ID" style="width:200px" /></el-form-item>
        <el-form-item label="佣金比例(%)"><el-input-number v-model="divisionForm.commission_rate" :min="0" :max="100" :precision="1" style="width:200px" /></el-form-item>
        <el-form-item label="说明"><el-input v-model="divisionForm.description" type="textarea" :rows="3" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="showDivisionDialog=false">取消</el-button><el-button type="primary" @click="saveDivision">{{ editingDivision?'更新':'添加' }}</el-button></template>
    </el-dialog>

    <!-- 数据看板 -->
    <div v-show="activeTab==='dashboard'">
      <el-row :gutter="12" style="margin-bottom:16px">
        <el-col :span="6"><div class="mcard"><div class="num">¥{{ (dashData.totalCommission||0).toFixed(2) }}</div><div class="lbl">总佣金</div></div></el-col>
        <el-col :span="6"><div class="mcard"><div class="num">¥{{ (dashData.pendingCommission||0).toFixed(2) }}</div><div class="lbl">待结算</div></div></el-col>
        <el-col :span="6"><div class="mcard"><div class="num">{{ dashData.distributors||0 }}</div><div class="lbl">分销员</div></div></el-col>
        <el-col :span="6"><div class="mcard"><div class="num">{{ dashData.teamCount||0 }}</div><div class="lbl">团队总人数</div></div></el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12"><el-card shadow="never"><div ref="distLevelChartRef" style="height:300px"></div></el-card></el-col>
        <el-col :span="12"><el-card shadow="never"><div ref="distTrendChartRef" style="height:300px"></div></el-card></el-col>
      </el-row>
      <el-card shadow="never" style="margin-top:12px">
        <h4 style="margin:0 0 12px">事业部业绩排行</h4>
        <el-table :data="teamRankList" border v-loading="rankLoad" size="small">
          <el-table-column prop="nickname" label="分销员" width="140" />
          <el-table-column prop="phone" label="手机号" width="130" />
          <el-table-column prop="team_count" label="团队人数" width="90" align="center" />
          <el-table-column prop="total_commission" label="累计佣金" width="120" align="center"><template #default="{row}">¥{{row.total_commission}}</template></el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { Plus, Search, Setting } from '@element-plus/icons-vue'
import axios from 'axios'

const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })
const uploadUrl = '/api/admin/upload/image'
const uploadHeaders = { Authorization: 'Bearer ' + localStorage.getItem('admin_token') }

const tabs = [
  { key:'agents', icon:'👥', label:'分销员管理' },
  { key:'applies', icon:'📝', label:'分销员申请' },
  { key:'levels', icon:'🏅', label:'分销等级' },
  { key:'settings', icon:'⚙️', label:'分销设置' },
  { key:'divisions', icon:'🏢', label:'事业部' },
]
const activeTab = ref('agents')
function switchTab(k) { activeTab.value = k; setTimeout(() => { if(k==='agents')fetchAgents(); else if(k==='applies')fetchApplies(); else if(k==='levels')fetchDistLevels(); else if(k==='settings')fetchDistSettings(); else if(k==='divisions')fetchDivisions(); else if(k==='dashboard')fetchDashboard() }, 100) }

// 分销员
const agentFilter = reactive({ keyword:'', status:'', level:'' })
const agentList = ref([]); const agentLoading = ref(false)
const agentP = ref(1); const agentPS = ref(10); const agentTotal = ref(0)
async function fetchAgents() {
  agentLoading.value = true
  try {
    const r = await API.get('/distribution/users', { params: { page:agentP.value, pageSize:agentPS.value, keyword:agentFilter.keyword||undefined, status:agentFilter.status||undefined, level:agentFilter.level||undefined } })
    agentList.value = r.data.data?.list || []; agentTotal.value = r.data.data?.total || 0
  } catch { agentList.value = []; agentTotal.value = 0 }
  finally { agentLoading.value = false }
}
async function toggleAgent(row, v) { try { await API.put('/users/'+row.id, { distributor_status:v }); ElMessage.success(v==='active'?'已启用':'已禁用') } catch {} }

// 分销员详情
const agentDetailVisible = ref(false); const agentDetail = ref(null)
function showAgentDetail(row) { agentDetail.value = row; agentDetailVisible.value = true }

// 申请
const applyFilter = reactive({ status:'' })
const applyList = ref([]); const applyLoading = ref(false)
const applyP = ref(1); const applyPS = ref(10); const applyTotal = ref(0)
async function fetchApplies() {
  applyLoading.value = true
  try {
    const r = await API.get('/distribution/applies', { params: { page:applyP.value, pageSize:applyPS.value, status:applyFilter.status||undefined } })
    applyList.value = r.data.data?.list || []; applyTotal.value = r.data.data?.total || 0
  } catch { applyList.value = []; applyTotal.value = 0 }
  finally { applyLoading.value = false }
}
async function approveApply(row) {
  try { await API.post('/distribution/applies/'+row.id+'/approve'); ElMessage.success('已通过'); fetchApplies() } catch { ElMessage.error('操作失败') }
}
const rejectVisible = ref(false); const rejectReason = ref(''); const rejectTarget = ref(null)
function rejectApply(row) { rejectTarget.value = row; rejectReason.value = ''; rejectVisible.value = true }
async function confirmReject() {
  try { await API.post('/distribution/applies/'+rejectTarget.value.id+'/reject', { reason:rejectReason.value }); ElMessage.success('已拒绝'); rejectVisible.value = false; fetchApplies() } catch { ElMessage.error('操作失败') }
}

// 分销等级
const distLevels = ref([])
async function fetchDistLevels() {
  try { const r = await API.get('/distribution/levels'); distLevels.value = (r.data.data||[]).map(l=>({...l,_edit:false})) } catch {}
}
function addDistLevel() { distLevels.value.push({ name:'新等级', level:distLevels.value.length+1, min_team_count:0, min_team_sales:0, commission_rate:0, commission_rate2:0, commission_rate3:0, _edit:true }) }
function editDistLevel(row) { row._edit = true }
async function saveDistLevel(row) {
  if (!row.name) return ElMessage.warning('请输入名称')
  try {
    if (row.id) await API.put('/distribution/levels/'+row.id, row)
    else await API.post('/distribution/levels', row)
    row._edit = false; ElMessage.success('保存成功'); fetchDistLevels()
  } catch { ElMessage.error('保存失败') }
}
function deleteDistLevel(idx) {
  const row = distLevels.value[idx]
  try { if(row.id)API.delete('/distribution/levels/'+row.id); distLevels.value.splice(idx,1); ElMessage.success('已删除') } catch { distLevels.value.splice(idx,1) }
}

// 分销设置
const distSettings = reactive({ is_open:'1', self_buy:'1', auto_settle_days:7, min_withdraw:10, withdraw_fee_rate:0, apply_type:'manual', poster_image:'', dist_mode:'everyone', threshold_amount:0, bind_mode:'auto', bind_valid_days:365, commission_levels:'3', division_enabled:'0', agent_apply_enabled:'1', commission_float_enabled:'0', withdraw_methods:['wechat','alipay'] })
const settingsLoading = ref(false)
async function fetchDistSettings() {
  try { const r = await API.get('/distribution/settings'); (r.data.data||[]).forEach(c => { if(c.key in distSettings) distSettings[c.key] = c.value }) } catch {}
}
async function saveDistSettings() {
  settingsLoading.value = true
  try {
    const toSave = { ...distSettings }
    if (Array.isArray(toSave.withdraw_methods)) toSave.withdraw_methods = toSave.withdraw_methods.join(',')
    await API.put('/distribution/settings', { configs: Object.entries(toSave).map(([k,v])=>({key:k, value:String(v)})) })
    ElMessage.success('设置已保存')
  } catch { ElMessage.error('保存失败') }
  finally { settingsLoading.value = false }
}

// 事业部
const divisionList = ref([]); const divLoading = ref(false)
const showDivisionDialog = ref(false); const editingDivision = ref(null)
const divisionForm = reactive({ name:'', manager_id:'', commission_rate:0, description:'' })
async function fetchDivisions() {
  divLoading.value = true
  try { const r = await API.get('/distribution/divisions'); divisionList.value = r.data.data || [] } catch { divisionList.value = [] }
  finally { divLoading.value = false }
}
function editDivision(row) {
  editingDivision.value = row; divisionForm.name = row.name; divisionForm.manager_id = row.manager_id||''
  divisionForm.commission_rate = row.commission_rate; divisionForm.description = row.description; showDivisionDialog.value = true
}
async function saveDivision() {
  try {
    if (editingDivision.value) { await API.put('/distribution/divisions/'+editingDivision.value.id, divisionForm); editingDivision.value = null }
    else await API.post('/distribution/divisions', divisionForm)
    ElMessage.success('保存成功'); showDivisionDialog.value = false; fetchDivisions()
  } catch { ElMessage.error('保存失败') }
}
async function deleteDivision(row) { try { await API.delete('/distribution/divisions/'+row.id); ElMessage.success('已删除'); fetchDivisions() } catch {} }

const dashData=reactive({});const levelStats=ref([]);const teamRankList=ref([]);const rankLoad=ref(false);const distLevelChartRef=ref(null);const distTrendChartRef=ref(null);let levelChart=null;let trendChart=null
async function fetchDashboard(){try{const[r1,r2,r3]=await Promise.all([API.get('/distribution/dashboard'),API.get('/distribution/level-stats'),API.get('/distribution/team-ranking')]);Object.assign(dashData,r1.data.data||{});levelStats.value=r2.data.data||[];teamRankList.value=r3.data.data||[];nextTick(()=>{initLevelChart();initTrendChart()})}catch{}}
function initLevelChart(){if(!distLevelChartRef.value)return;if(levelChart)levelChart.dispose();levelChart=echarts.init(distLevelChartRef.value);const d=levelStats.value;levelChart.setOption({tooltip:{trigger:'item'},series:[{type:'pie',radius:['40%','70%'],data:d.map(i=>({name:i.name,value:i.users})),itemStyle:{borderRadius:6,borderColor:'#fff',borderWidth:2}}]})}
function initTrendChart(){if(!distTrendChartRef.value)return;if(trendChart)trendChart.dispose();trendChart=echarts.init(distTrendChartRef.value);trendChart.setOption({tooltip:{trigger:'axis'},xAxis:{type:'category',data:['1周','2周','3周','4周']},yAxis:{type:'value'},series:[{type:'line',data:[120,200,150,80],smooth:true,areaStyle:{}}]})}
onMounted(() => { fetchAgents() })
</script>

<style scoped>
.dist-page { max-width: 1400px; }
.tabs-card { margin-bottom: 16px; padding: 4px 0; }
.dist-tabs { display: flex; gap: 4px; }
.dist-tab { display:flex; align-items:center; gap:6px; padding:10px 18px; border-radius:8px; cursor:pointer; font-size:14px; transition:all .2s; }
.dist-tab:hover { background:#f5f7fa; }
.dist-tab.active { background:#ecf5ff; color:#409eff; font-weight:600; }
.t-icon { font-size:18px; }
.mcard{text-align:center;padding:16px;background:#f8f9ff;border-radius:8px;height:100px;display:flex;flex-direction:column;justify-content:center}
.mcard .num{font-size:24px;font-weight:700;color:#409eff}
.mcard .lbl{font-size:12px;color:#999;margin-top:4px}
.card-title { font-size:15px; font-weight:600; color:#333; margin:0 0 16px 0; }
.filter-card { margin-bottom:16px; }
.pagination-wrapper { display:flex; justify-content:flex-end; padding:16px 0 0; }
.section-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; }
.section-header h3 { font-size:15px; font-weight:600; color:#333; margin:0; }
.tip { font-size:12px; color:#999; margin-left:8px; }
</style>
