<template>
  <a-layout style="min-height: 100vh" class="admin-layout">
    <a-layout-sider :width="250" theme="dark" collapsible :collapsed-width="64" class="admin-sider">
      <div class="sider-header">
        <a-avatar :size="36" style="background: linear-gradient(135deg, #722ed1 0%, #b37feb 100%)">
          <icon-safe />
        </a-avatar>
        <span class="sider-title" v-if="!$attrs.collapsed">超级管理员</span>
      </div>
      <a-menu :selected-keys="[active]" @menu-item-click="onMenuClick" theme="dark">
        <a-menu-item key="overview">
          <template #icon><icon-dashboard /></template>
          <span v-if="!$attrs.collapsed">数据概览</span>
        </a-menu-item>
        <a-menu-item key="orders">
          <template #icon><icon-file /></template>
          <span v-if="!$attrs.collapsed">订单管理</span>
        </a-menu-item>
        <a-menu-item key="risk">
          <template #icon><icon-exclamation /></template>
          <span v-if="!$attrs.collapsed">风控审核</span>
          <a-badge v-if="risks.length > 0" :count="risks.length" :max-count="99" />
        </a-menu-item>
        <a-menu-item key="products">
          <template #icon><icon-apps /></template>
          <span v-if="!$attrs.collapsed">商品管理</span>
        </a-menu-item>
        <a-menu-item key="audit">
          <template #icon><icon-check-circle /></template>
          <span v-if="!$attrs.collapsed">审核管理</span>
        </a-menu-item>
        <a-menu-item key="users">
          <template #icon><icon-user-group /></template>
          <span v-if="!$attrs.collapsed">用户管理</span>
        </a-menu-item>
        <a-menu-item key="banners">
          <template #icon><icon-apps /></template>
          <span v-if="!$attrs.collapsed">轮播图设置</span>
        </a-menu-item>
        <a-menu-item key="reviews">
          <template #icon><icon-message /></template>
          <span v-if="!$attrs.collapsed">评价管理</span>
        </a-menu-item>
        <a-menu-item key="logistics">
          <template #icon><icon-send /></template>
          <span v-if="!$attrs.collapsed">物流总览</span>
        </a-menu-item>
        <a-menu-item key="inventory">
          <template #icon><icon-storage /></template>
          <span v-if="!$attrs.collapsed">库存总览</span>
        </a-menu-item>
        <a-menu-item key="profile">
          <template #icon><icon-user /></template>
          <span v-if="!$attrs.collapsed">个人信息</span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>
    <a-layout class="admin-main">
      <a-layout-header class="admin-header">
        <div class="header-left">
          <span class="page-title">{{ titleMap[active] }}</span>
        </div>
        <div class="header-right">
          <a-space>
            <a-tag color="purple" size="small">
              <template #icon><icon-trophy /></template>
              管理员
            </a-tag>
            <a-button @click="goHome">
              <template #icon><icon-home /></template>
              前台首页
            </a-button>
            <a-dropdown>
              <a-button shape="circle">
                <template #icon><icon-user /></template>
              </a-button>
              <template #content>
                <a-doption @click="active = 'profile'">
                  <template #icon><icon-settings /></template>
                  个人信息
                </a-doption>
                <a-doption @click="logout">
                  <template #icon><icon-export /></template>
                  退出登录
                </a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </div>
      </a-layout-header>
      <a-layout-content class="admin-content">
        <a-card v-if="active==='overview'" :bordered="false" class="overview-card">
          <div class="stats-row">
            <a-card class="stat-card" :bordered="false">
              <div class="stat-icon orders">
                <icon-file :size="32" />
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ overview.orderCount || 0 }}</div>
                <div class="stat-label">订单总量</div>
              </div>
            </a-card>
            <a-card class="stat-card" :bordered="false">
              <div class="stat-icon sales">
                <icon-gift :size="32" />
              </div>
              <div class="stat-info">
                <div class="stat-value">¥{{ (overview.salesAmount || 0).toLocaleString() }}</div>
                <div class="stat-label">平台销售额</div>
              </div>
            </a-card>
            <a-card class="stat-card" :bordered="false">
              <div class="stat-icon users">
                <icon-user-group :size="32" />
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ users.length }}</div>
                <div class="stat-label">注册用户</div>
              </div>
            </a-card>
            <a-card class="stat-card" :bordered="false">
              <div class="stat-icon risks">
                <icon-exclamation :size="32" />
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ risks.length }}</div>
                <div class="stat-label">待处理风控</div>
              </div>
            </a-card>
          </div>

          <a-row :gutter="16" style="margin-top: 20px">
            <a-col :xs="24" :md="12">
              <a-card title="品类占比" size="small">
                <div ref="categoryChartRef" style="height: 280px;"></div>
              </a-card>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-card title="热销排行 Top10" size="small">
                <div ref="hotChartRef" style="height: 280px;"></div>
              </a-card>
            </a-col>
          </a-row>

          <a-divider />
          <a-card title="通知公告" size="small">
            <a-timeline v-if="overview.notifications && overview.notifications.length">
              <a-timeline-item v-for="(note, idx) in overview.notifications" :key="idx" :color="idx === 0 ? 'red' : 'purple'">
                {{ note }}
              </a-timeline-item>
            </a-timeline>
            <a-empty v-else description="暂无公告" />
          </a-card>
        </a-card>

        <a-card v-if="active==='orders'" :bordered="false" class="content-card">
          <template #title>
            <a-space>
              <span>订单管理</span>
              <a-tag color="blue">共 {{ orders.length }} 个订单</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-button @click="loadOrders">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <a-table :columns="orderColumns" :data="orders" :pagination="{ pageSize: 8 }" :bordered="false">
            <template #status="{ record }">
              <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
            </template>
            <template #actions="{ record }">
              <a-space>
                <a-button size="mini" type="primary" shape="round" @click="openOrderModal(record)">修改</a-button>
                <a-button size="mini" v-if="record.status === 'REFUND_REQUESTED'" @click="auditRefund(record, true)">通过退款</a-button>
                <a-button size="mini" status="danger" v-if="record.status === 'REFUND_REQUESTED'" @click="auditRefund(record, false)">驳回退款</a-button>
                <a-button size="mini" v-if="record.status === 'SHIPPED' || record.status === 'PAID'" @click="auditShipment(record, true)">发货审核</a-button>
              </a-space>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='risk'" :bordered="false" class="content-card">
          <template #title>
            <a-space>
              <span>风控审核</span>
              <a-badge :count="risks.length" :show-zero="true" />
            </a-space>
          </template>
          <template #extra>
            <a-button @click="loadRisks">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <a-table :columns="riskColumns" :data="risks" :pagination="{ pageSize: 8 }" :bordered="false">
            <template #riskType="{ record }">
              <a-tag :color="getRiskColor(record.riskType)">{{ record.riskType }}</a-tag>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='products'" :bordered="false" class="content-card">
          <template #title>
            <a-space>
              <span>商品管理</span>
              <a-tag color="green">共 {{ products.length }} 件商品</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-space>
              <a-button type="primary" @click="openProductModal()">
                <template #icon><icon-plus /></template>
                新增商品
              </a-button>
              <a-button @click="loadProducts">
                <template #icon><icon-refresh /></template>
                刷新
              </a-button>
            </a-space>
          </template>
          <a-table :columns="productColumns" :data="products" :pagination="{ pageSize: 8 }" :bordered="false">
            <template #approved="{ record }">
              <a-switch :model-value="record.approved" @change="() => toggleApprove(record)" />
            </template>
            <template #actions="{ record }">
              <a-space>
                <a-button size="mini" type="primary" shape="round" @click="openProductModal(record)">编辑</a-button>
                <a-popconfirm content="确定删除此商品吗？" @ok="deleteProduct(record.id)">
                  <a-button size="mini" status="danger" shape="round">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='audit'" :bordered="false" class="content-card">
          <template #title>
            <a-space>
              <span>商家审核管理</span>
              <a-tag color="orange">共 {{ applications.length }} 个申请</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-button @click="loadApplications">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <a-table :columns="applyColumns" :data="applications" :pagination="{ pageSize: 8 }" :bordered="false">
            <template #status="{ record }">
              <a-tag :color="getAuditStatusColor(record.status)">{{ getAuditStatusText(record.status) }}</a-tag>
            </template>
            <template #actions="{ record }">
              <a-button size="mini" type="primary" shape="round" @click="openAuditModal(record)">审核</a-button>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='users'" :bordered="false" class="content-card">
          <template #title>
            <a-space>
              <span>用户管理</span>
              <a-tag color="cyan">共 {{ users.length }} 个用户</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-space>
              <a-button type="primary" @click="openUserModal()">
                <template #icon><icon-user-add /></template>
                新增用户
              </a-button>
              <a-button @click="loadUsers">
                <template #icon><icon-refresh /></template>
                刷新
              </a-button>
            </a-space>
          </template>
          <a-table :columns="userColumns" :data="users" :pagination="{ pageSize: 8 }" :bordered="false">
            <template #role="{ record }">
              <a-tag :color="getRoleColor(record.role)">{{ record.role }}</a-tag>
            </template>
            <template #enabled="{ record }">
              <a-switch :model-value="record.enabled" disabled />
            </template>
            <template #actions="{ record }">
              <a-space>
                <a-button size="mini" type="primary" shape="round" @click="openUserModal(record)">编辑</a-button>
                <a-popconfirm content="确定删除此用户吗？" @ok="deleteUser(record.id)">
                  <a-button size="mini" status="danger" shape="round">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='banners'" :bordered="false" class="content-card">
          <template #title>轮播图设置</template>
          <template #extra>
            <a-space>
              <a-button type="primary" @click="openBannerModal()">
                <template #icon><icon-plus /></template>
                新增轮播图
              </a-button>
              <a-button @click="loadBanners">
                <template #icon><icon-refresh /></template>
                刷新
              </a-button>
            </a-space>
          </template>
          <a-table :columns="bannerColumns" :data="banners" :pagination="false" :bordered="false">
            <template #imageUrl="{ record }">
              <img :src="record.imageUrl" style="width: 80px; height: 40px; object-fit: cover; border-radius: 4px" />
            </template>
            <template #enabled="{ record }">
              <a-switch :model-value="record.enabled" @change="(v) => { record.enabled = v; openBannerModal(record) }" />
            </template>
            <template #actions="{ record }">
              <a-space>
                <a-button size="mini" type="primary" shape="round" @click="openBannerModal(record)">编辑</a-button>
                <a-popconfirm content="确定删除此轮播图吗？" @ok="deleteBanner(record.id)">
                  <a-button size="mini" status="danger" shape="round">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='reviews'" :bordered="false" class="content-card">
          <template #title>
            <a-space>
              <span>评价管理</span>
              <a-tag color="pink">共 {{ reviews.length }} 条评价</a-tag>
            </a-space>
          </template>
          <template #extra>
            <a-button @click="loadReviews">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <a-table :columns="reviewColumns" :data="reviews" :pagination="{ pageSize: 8 }" :bordered="false">
            <template #rating="{ record }">
              <a-rate :model-value="record.rating" readonly />
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='logistics'" :bordered="false" class="content-card">
          <template #title>物流总览</template>
          <template #extra>
            <a-button @click="loadLogistics">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <a-table :columns="logisticsColumns" :data="logistics" :pagination="{ pageSize: 8 }" :bordered="false" />
        </a-card>

        <a-card v-if="active==='inventory'" :bordered="false" class="content-card">
          <template #title>库存总览</template>
          <template #extra>
            <a-button @click="loadInventory">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <a-table :columns="inventoryColumns" :data="inventory" :pagination="{ pageSize: 8 }" :bordered="false" />
        </a-card>

        <a-card v-if="active==='profile'" :bordered="false" class="content-card">
          <template #title>个人信息</template>
          <a-form :model="profile" layout="vertical" style="max-width: 500px">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="账号">
                  <a-input v-model="profile.username" disabled>
                    <template #prefix><icon-user /></template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="角色">
                  <a-input v-model="profile.role" disabled>
                    <template #prefix><icon-trophy /></template>
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
<a-form-item label="昵称">
                  <a-input v-model="profile.nickname">
                    <template #prefix><icon-relation /></template>
                  </a-input>
                </a-form-item>
<a-form-item label="手机号">
                  <a-input v-model="profile.phone">
                    <template #prefix><icon-phone /></template>
                  </a-input>
                </a-form-item>
<a-form-item label="地址">
                  <a-input v-model="profile.address">
                    <template #prefix><icon-location /></template>
                  </a-input>
                </a-form-item>
            <a-button type="primary" @click="saveProfile">
              <template #icon><icon-check /></template>
              保存修改
            </a-button>
          </a-form>
        </a-card>
      </a-layout-content>
    </a-layout>
  </a-layout>

  <a-modal v-model:visible="orderModalVisible" title="修改订单" :ok-text="'保存'" cancel-text="取消" @ok="submitOrderModal">
    <a-form :model="orderForm" layout="vertical">
      <a-form-item label="订单状态">
        <a-select v-model="orderForm.status">
          <a-option value="PENDING_PAYMENT">待支付</a-option>
          <a-option value="PAID">已支付</a-option>
          <a-option value="SHIPPED">已发货</a-option>
          <a-option value="COMPLETED">已完成</a-option>
          <a-option value="REFUND_REQUESTED">退款中</a-option>
          <a-option value="REFUNDED">已退款</a-option>
          <a-option value="CANCELLED">已取消</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="物流信息">
        <a-input v-model="orderForm.logisticsInfo" placeholder="请输入物流信息" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="auditModalVisible" title="审核商家入驻申请" :ok-text="'提交审核'" cancel-text="取消" @ok="submitAuditModal">
    <a-form :model="auditForm" layout="vertical">
      <a-form-item label="审核结果">
        <a-radio-group v-model="auditForm.status">
          <a-radio value="APPROVED">通过</a-radio>
          <a-radio value="REJECTED">拒绝</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="审核备注">
        <a-textarea v-model="auditForm.remark" placeholder="请输入审核备注（可选）" :rows="3" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="userModalVisible" :title="userForm.id ? '编辑用户' : '新增用户'" :ok-text="userForm.id ? '保存' : '添加'" cancel-text="取消" @ok="submitUserModal" width="520">
    <a-form :model="userForm" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="账号" required>
            <a-input v-model="userForm.username" placeholder="请输入账号" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="密码" :required="!userForm.id">
            <a-input-password v-model="userForm.password" :placeholder="userForm.id ? '留空则不修改' : '请输入密码'" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="角色" required>
        <a-select v-model="userForm.role" placeholder="选择用户角色">
          <a-option value="CUSTOMER">顾客</a-option>
          <a-option value="MERCHANT">商家</a-option>
          <a-option value="ADMIN">管理员</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="昵称">
        <a-input v-model="userForm.nickname" placeholder="请输入昵称" />
      </a-form-item>
      <a-form-item label="账号状态">
        <a-switch v-model="userForm.enabled" />
        <span style="margin-left: 8px">{{ userForm.enabled ? '启用' : '禁用' }}</span>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="bannerModalVisible" :title="bannerForm.id ? '编辑轮播图' : '新增轮播图'" :ok-text="bannerForm.id ? '保存' : '添加'" cancel-text="取消" @ok="submitBannerModal" width="500">
    <a-form :model="bannerForm" layout="vertical">
      <a-form-item label="图片URL" required>
        <a-input v-model="bannerForm.imageUrl" placeholder="请输入轮播图图片URL" allow-clear />
      </a-form-item>
      <a-form-item label="跳转链接">
        <a-input v-model="bannerForm.linkUrl" placeholder="点击轮播图跳转的URL（可选）" allow-clear />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="排序">
            <a-input-number v-model="bannerForm.sortNo" :min="1" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="启用状态">
            <a-switch v-model="bannerForm.enabled" />
            <span style="margin-left: 8px">{{ bannerForm.enabled ? '启用' : '禁用' }}</span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="productModalVisible" :title="productForm.id ? '编辑商品' : '新增商品'" :ok-text="productForm.id ? '保存' : '添加'" cancel-text="取消" @ok="submitProductModal" width="600">
    <a-form :model="productForm" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="16">
          <a-form-item label="商品名称" required>
            <a-input v-model="productForm.name" placeholder="请输入商品名称" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="分类">
            <a-select v-model="productForm.category" placeholder="选择分类">
              <a-option value="奶粉">奶粉</a-option>
              <a-option value="尿裤">尿裤</a-option>
              <a-option value="辅食">辅食</a-option>
              <a-option value="玩具">玩具</a-option>
              <a-option value="服饰">服饰</a-option>
              <a-option value="用品">用品</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="商品描述">
        <a-textarea v-model="productForm.description" placeholder="请输入商品描述" :rows="3" />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="价格" required>
            <a-input-number v-model="productForm.price" :min="0" :precision="2" :step="0.01" style="width: 100%" prefix="¥" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="库存" required>
            <a-input-number v-model="productForm.stock" :min="0" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="商品图片">
        <a-input v-model="productForm.imageUrl" placeholder="请输入商品图片URL" allow-clear />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="所属商家">
            <a-select v-model="productForm.merchantId" placeholder="选择商家" allow-search>
              <a-option v-for="m in merchantOptions" :key="m.value" :value="m.value">{{ m.label }}</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审核状态">
            <a-switch v-model="productForm.approved" />
            <span style="margin-left: 8px">{{ productForm.approved ? '已上架' : '待审核' }}</span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="orderModalVisible" title="修改订单" @ok="submitOrderModal">
    <a-form :model="orderForm" layout="vertical">
      <a-form-item label="订单状态">
        <a-select v-model="orderForm.status">
          <a-option value="PENDING_PAYMENT">PENDING_PAYMENT</a-option>
          <a-option value="PAID">PAID</a-option>
          <a-option value="SHIPPED">SHIPPED</a-option>
          <a-option value="COMPLETED">COMPLETED</a-option>
          <a-option value="REFUND_REQUESTED">REFUND_REQUESTED</a-option>
          <a-option value="REFUNDED">REFUNDED</a-option>
          <a-option value="CANCELLED">CANCELLED</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="物流信息">
        <a-input v-model="orderForm.logisticsInfo" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="auditModalVisible" title="审核商家" @ok="submitAuditModal">
    <a-form :model="auditForm" layout="vertical">
      <a-form-item label="审核结果">
        <a-select v-model="auditForm.status">
          <a-option value="APPROVED">通过</a-option>
          <a-option value="REJECTED">拒绝</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="备注">
        <a-input v-model="auditForm.remark" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="userModalVisible" :title="userForm.id ? '编辑用户' : '新增用户'" @ok="submitUserModal">
    <a-form :model="userForm" layout="vertical">
      <a-form-item label="账号"><a-input v-model="userForm.username" /></a-form-item>
      <a-form-item label="密码"><a-input v-model="userForm.password" /></a-form-item>
      <a-form-item label="角色">
        <a-select v-model="userForm.role">
          <a-option value="CUSTOMER">CUSTOMER</a-option>
          <a-option value="MERCHANT">MERCHANT</a-option>
          <a-option value="ADMIN">ADMIN</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="昵称"><a-input v-model="userForm.nickname" /></a-form-item>
      <a-form-item label="是否启用"><a-switch v-model="userForm.enabled" /></a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="bannerModalVisible" :title="bannerForm.id ? '编辑轮播图' : '新增轮播图'" @ok="submitBannerModal">
    <a-form :model="bannerForm" layout="vertical">
      <a-form-item label="图片URL"><a-input v-model="bannerForm.imageUrl" /></a-form-item>
      <a-form-item label="跳转URL"><a-input v-model="bannerForm.linkUrl" /></a-form-item>
      <a-form-item label="排序"><a-input-number v-model="bannerForm.sortNo" style="width: 100%" /></a-form-item>
      <a-form-item label="启用">
        <a-switch v-model="bannerForm.enabled" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="productModalVisible" :title="productForm.id ? '编辑商品' : '新增商品'" @ok="submitProductModal">
    <a-form :model="productForm" layout="vertical">
      <a-form-item label="商品名称"><a-input v-model="productForm.name" /></a-form-item>
      <a-form-item label="分类"><a-input v-model="productForm.category" /></a-form-item>
      <a-form-item label="描述"><a-input v-model="productForm.description" /></a-form-item>
      <a-form-item label="价格"><a-input-number v-model="productForm.price" style="width: 100%" /></a-form-item>
      <a-form-item label="库存"><a-input-number v-model="productForm.stock" style="width: 100%" /></a-form-item>
      <a-form-item label="图片URL"><a-input v-model="productForm.imageUrl" /></a-form-item>
      <a-form-item label="所属商家">
        <a-select v-model="productForm.merchantId" placeholder="请选择商家">
          <a-option v-for="m in merchantOptions" :key="m.value" :value="m.value">{{ m.label }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="审核通过"><a-switch v-model="productForm.approved" /></a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { onMounted, reactive, ref, watch, nextTick, onUnmounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { api } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const active = ref('overview')

const categoryChartRef = ref(null)
const hotChartRef = ref(null)
let categoryChart = null
let hotChart = null

const titleMap = {
  overview: '数据概览', orders: '订单管理', risk: '风控审核', products: '商品管理', audit: '审核管理',
  users: '用户管理', banners: '轮播图设置', reviews: '评价管理', logistics: '物流总览', inventory: '库存总览', profile: '个人信息'
}

const overview = reactive({})
const orders = ref([])
const risks = ref([])
const products = ref([])
const applications = ref([])
const users = ref([])
const merchantOptions = ref([])
const banners = ref([])
const reviews = ref([])
const logistics = ref([])
const inventory = ref([])
const profile = reactive({ username: '', role: '', nickname: '', phone: '', address: '' })

const orderModalVisible = ref(false)
const auditModalVisible = ref(false)
const userModalVisible = ref(false)
const bannerModalVisible = ref(false)
const productModalVisible = ref(false)

const orderForm = reactive({ id: null, status: 'PAID', logisticsInfo: '' })
const auditForm = reactive({ id: null, status: 'APPROVED', remark: '' })
const userForm = reactive({ id: null, username: '', password: '', role: 'CUSTOMER', nickname: '', enabled: true })
const bannerForm = reactive({ id: null, imageUrl: '', linkUrl: '', sortNo: 1, enabled: true })
const productForm = reactive({ id: null, name: '', category: '', description: '', price: 0, stock: 0, imageUrl: '', merchantId: null, approved: false })

const orderColumns = [
  { title: '订单号', dataIndex: 'orderNo', width: 180 },
  { title: '金额', dataIndex: 'totalAmount', render: ({ record }) => `¥${record.totalAmount}`, width: 100 },
  { title: '状态', slotName: 'status', width: 100 },
  { title: '物流信息', dataIndex: 'logisticsInfo', ellipsis: true },
  { title: '下单时间', dataIndex: 'createdAt', render: ({ record }) => formatDate(record.createdAt), width: 160 },
  { title: '操作', slotName: 'actions', width: 280 }
]

const productColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '商品名', dataIndex: 'name' },
  { title: '分类', dataIndex: 'category', width: 80 },
  { title: '价格', dataIndex: 'price', render: ({ record }) => `¥${record.price}`, width: 80 },
  { title: '库存', dataIndex: 'stock', width: 70 },
  { title: '商家', dataIndex: 'merchantUsername', width: 100 },
  { title: '审核', slotName: 'approved', width: 80 },
  { title: '操作', slotName: 'actions', width: 140 }
]

const applyColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '申请人', dataIndex: 'applicantNickname' },
  { title: '账号', dataIndex: 'applicantUsername', width: 120 },
  { title: '资质说明', dataIndex: 'qualification', ellipsis: true },
  { title: '状态', slotName: 'status', width: 90 },
  { title: '审核备注', dataIndex: 'remark', ellipsis: true },
  { title: '操作', slotName: 'actions', width: 80 }
]

const userColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '账号', dataIndex: 'username' },
  { title: '昵称', dataIndex: 'nickname', width: 100 },
  { title: '角色', slotName: 'role', width: 90 },
  { title: '状态', slotName: 'enabled', width: 70 },
  { title: '操作', slotName: 'actions', width: 140 }
]

const riskColumns = [
  { title: '订单号', dataIndex: 'orderNo', width: 180 },
  { title: '状态', dataIndex: 'status', width: 100 },
  { title: '金额', dataIndex: 'totalAmount', render: ({ record }) => `¥${record.totalAmount}`, width: 100 },
  { title: '风险类型', slotName: 'riskType', width: 120 },
  { title: '风险说明', dataIndex: 'riskReason' }
]

const bannerColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '图片', slotName: 'imageUrl', width: 100 },
  { title: '跳转链接', dataIndex: 'linkUrl', ellipsis: true },
  { title: '排序', dataIndex: 'sortNo', width: 70 },
  { title: '状态', slotName: 'enabled', width: 70 },
  { title: '操作', slotName: 'actions', width: 140 }
]

const reviewColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '订单号', dataIndex: 'orderNo', width: 160 },
  { title: '商品', dataIndex: 'productName' },
  { title: '顾客', dataIndex: 'customerUsername', width: 100 },
  { title: '评分', slotName: 'rating', width: 180 },
  { title: '内容', dataIndex: 'content', ellipsis: true },
  { title: '时间', dataIndex: 'createdAt', width: 160 }
]

const logisticsColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '订单号', dataIndex: 'orderNo', width: 160 },
  { title: '商家', dataIndex: 'merchantUsername', width: 100 },
  { title: '状态', dataIndex: 'status', width: 100 },
  { title: '备注', dataIndex: 'note', ellipsis: true },
  { title: '时间', dataIndex: 'createdAt', width: 160 }
]

const inventoryColumns = [
  { title: 'ID', dataIndex: 'id', width: 60 },
  { title: '商品', dataIndex: 'productName' },
  { title: '商家', dataIndex: 'merchantUsername', width: 100 },
  { title: '变动', dataIndex: 'changeQty', width: 80 },
  { title: '备注', dataIndex: 'note', ellipsis: true },
  { title: '时间', dataIndex: 'createdAt', width: 160 }
]

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

const getStatusColor = (status) => {
  const colors = { 'PENDING_PAYMENT': 'orange', 'PAID': 'blue', 'SHIPPED': 'cyan', 'COMPLETED': 'green', 'REFUND_REQUESTED': 'orange', 'REFUNDED': 'purple', 'CANCELLED': 'gray' }
  return colors[status] || 'gray'
}

const getStatusText = (status) => {
  const texts = { 'PENDING_PAYMENT': '待支付', 'PAID': '已支付', 'SHIPPED': '已发货', 'COMPLETED': '已完成', 'REFUND_REQUESTED': '退款中', 'REFUNDED': '已退款', 'CANCELLED': '已取消' }
  return texts[status] || status
}

const getRiskColor = (type) => {
  const colors = { 'HIGH_AMOUNT': 'red', 'SHIP_DELAY': 'orange', 'NO_LOGISTICS': 'purple', 'REFUND_PENDING': 'orange' }
  return colors[type] || 'gray'
}

const getAuditStatusColor = (status) => {
  const colors = { 'PENDING': 'orange', 'APPROVED': 'green', 'REJECTED': 'red' }
  return colors[status] || 'gray'
}

const getAuditStatusText = (status) => {
  const texts = { 'PENDING': '待审核', 'APPROVED': '已通过', 'REJECTED': '已拒绝' }
  return texts[status] || status
}

const getRoleColor = (role) => {
  const colors = { 'ADMIN': 'purple', 'MERCHANT': 'blue', 'CUSTOMER': 'green' }
  return colors[role] || 'gray'
}

const onMenuClick = (key) => { active.value = key }
const goHome = () => router.push('/')
const logout = async () => { await userStore.logout(); router.replace('/login') }

const loadOverview = async () => {
  Object.assign(overview, await api.adminOverview())
  await nextTick()
  initCharts()
}

const initCharts = () => {
  if (!overview.categoryRatio) overview.categoryRatio = {}
  if (!overview.hotProducts) overview.hotProducts = {}

  const categoryData = Object.entries(overview.categoryRatio).map(([name, value]) => ({ name, value }))
  if (categoryChart) {
    categoryChart.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', left: 'left' },
      series: [{ type: 'pie', radius: ['40%', '70%'], data: categoryData, itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 } }]
    })
  } else if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
    categoryChart.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', left: 'left' },
      series: [{ type: 'pie', radius: ['40%', '70%'], data: categoryData, itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 } }]
    })
  }

  const hotEntries = Object.entries(overview.hotProducts).sort((a, b) => b[1] - a[1]).slice(0, 10)
  const hotData = hotEntries.map(([name, value]) => ({ name: name.length > 8 ? name.substring(0, 8) + '...' : name, value }))
  if (hotChart) {
    hotChart.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'value' },
      yAxis: { type: 'category', data: hotData.map(d => d.name).reverse() },
      series: [{ type: 'bar', data: hotData.map(d => d.value).reverse(), itemStyle: { borderRadius: [0, 4, 4, 0] } }]
    })
  } else if (hotChartRef.value) {
    hotChart = echarts.init(hotChartRef.value)
    hotChart.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'value' },
      yAxis: { type: 'category', data: hotData.map(d => d.name).reverse() },
      series: [{ type: 'bar', data: hotData.map(d => d.value).reverse(), itemStyle: { borderRadius: [0, 4, 4, 0] } }]
    })
  }
}

const handleResize = () => { categoryChart?.resize(); hotChart?.resize() }

watch(active, async (v) => {
  if (v === 'overview') { await loadOverview(); await nextTick(); initCharts() }
  if (v === 'orders') return loadOrders()
  if (v === 'risk') return loadRisks()
  if (v === 'products') return loadProducts()
  if (v === 'audit') return loadApplications()
  if (v === 'users') return loadUsers()
  if (v === 'banners') return loadBanners()
  if (v === 'reviews') return loadReviews()
  if (v === 'logistics') return loadLogistics()
  if (v === 'inventory') return loadInventory()
  if (v === 'profile') return loadProfile()
})

const loadOrders = async () => { orders.value = await api.adminOrders() }
const loadRisks = async () => { risks.value = await api.adminOrderRisks() }
const loadProducts = async () => { products.value = await api.adminProductViews() }
const loadApplications = async () => { applications.value = await api.adminMerchantApplications() }
const loadUsers = async () => { users.value = await api.adminUsers() }
const loadBanners = async () => { banners.value = await api.adminBanners() }
const loadReviews = async () => { reviews.value = await api.adminReviews() }
const loadLogistics = async () => { logistics.value = await api.adminLogistics() }
const loadInventory = async () => { inventory.value = await api.adminInventory() }

const loadProfile = async () => {
  const me = await api.me()
  profile.username = me.username
  profile.role = me.role
  profile.nickname = me.nickname || ''
  profile.phone = me.phone || ''
  profile.address = me.address || ''
}

const openOrderModal = (row) => {
  orderForm.id = row.id
  orderForm.status = row.status
  orderForm.logisticsInfo = row.logisticsInfo || ''
  orderModalVisible.value = true
}

const submitOrderModal = async () => {
  await api.adminUpdateOrder(orderForm.id, { status: orderForm.status, logisticsInfo: orderForm.logisticsInfo })
  Message.success('订单已更新')
  orderModalVisible.value = false
  await loadOrders()
}

const openAuditModal = (row) => {
  auditForm.id = row.id
  auditForm.status = row.status === 'APPROVED' ? 'APPROVED' : 'REJECTED'
  auditForm.remark = row.remark || ''
  auditModalVisible.value = true
}

const submitAuditModal = async () => {
  await api.adminAuditMerchantApplication(auditForm.id, { status: auditForm.status, remark: auditForm.remark })
  Message.success('审核完成')
  auditModalVisible.value = false
  await loadApplications()
}

const openUserModal = (row = null) => {
  if (row) {
    userForm.id = row.id
    userForm.username = row.username
    userForm.password = ''
    userForm.role = row.role
    userForm.nickname = row.nickname || ''
    userForm.enabled = row.enabled !== false
  } else {
    userForm.id = null
    userForm.username = ''
    userForm.password = ''
    userForm.role = 'CUSTOMER'
    userForm.nickname = ''
    userForm.enabled = true
  }
  userModalVisible.value = true
}

const submitUserModal = async () => {
  const username = (userForm.username || '').trim()
  const password = (userForm.password || '').trim()
  if (!username) return Message.warning('请输入账号')
  if (!userForm.id && !password) return Message.warning('请输入密码')
  await api.adminSaveUser({ ...userForm, username, password })
  Message.success(userForm.id ? '用户已更新' : '用户已新增')
  userModalVisible.value = false
  await loadUsers()
}

const deleteUser = async (id) => {
  await api.adminDeleteUser(id)
  Message.success('用户已删除')
  await loadUsers()
}

const auditRefund = async (row, approve) => {
  const remark = window.prompt(approve ? '请输入退款通过备注（可为空）' : '请输入驳回原因（可为空）', '') || ''
  await api.adminAuditRefund(row.id, { approve, remark })
  Message.success(approve ? '退款审核已通过' : '退款审核已驳回')
  await Promise.all([loadOrders(), loadRisks()])
}

const auditShipment = async (row, approve) => {
  const remark = window.prompt(approve ? '请输入发货审核备注（可为空）' : '请输入驳回原因（可为空）', '') || ''
  await api.adminAuditShipment(row.id, { approve, remark })
  Message.success(approve ? '发货审核已通过' : '发货审核已驳回')
  await Promise.all([loadOrders(), loadRisks()])
}

const openBannerModal = (row = null) => {
  if (row) {
    bannerForm.id = row.id
    bannerForm.imageUrl = row.imageUrl || ''
    bannerForm.linkUrl = row.linkUrl || ''
    bannerForm.sortNo = row.sortNo || 1
    bannerForm.enabled = !!row.enabled
  } else {
    bannerForm.id = null
    bannerForm.imageUrl = ''
    bannerForm.linkUrl = ''
    bannerForm.sortNo = 1
    bannerForm.enabled = true
  }
  bannerModalVisible.value = true
}

const submitBannerModal = async () => {
  await api.adminSaveBanner({ ...bannerForm })
  Message.success(bannerForm.id ? '轮播图已更新' : '轮播图已新增')
  bannerModalVisible.value = false
  await loadBanners()
}

const deleteBanner = async (id) => {
  await api.adminDeleteBanner(id)
  Message.success('轮播图已删除')
  await loadBanners()
}

const openProductModal = (row = null) => {
  if (row) {
    productForm.id = row.id
    productForm.name = row.name || ''
    productForm.category = row.category || ''
    productForm.description = row.description || ''
    productForm.price = row.price || 0
    productForm.stock = row.stock || 0
    productForm.imageUrl = row.imageUrl || ''
    productForm.merchantId = row.merchantId || null
    productForm.approved = !!row.approved
  } else {
    productForm.id = null
    productForm.name = ''
    productForm.category = ''
    productForm.description = ''
    productForm.price = 0
    productForm.stock = 0
    productForm.imageUrl = ''
    productForm.merchantId = null
    productForm.approved = false
  }
  if (merchantOptions.value.length === 0) loadMerchantOptions()
  productModalVisible.value = true
}

const submitProductModal = async () => {
  if (!productForm.merchantId) return Message.warning('请选择所属商家')
  await api.adminSaveProduct({ ...productForm })
  Message.success(productForm.id ? '商品已更新' : '商品已新增')
  productModalVisible.value = false
  await loadProducts()
}

const toggleApprove = async (row) => {
  await api.adminApproveProduct(row.id, { approved: !row.approved })
  Message.success(!row.approved ? '已上架' : '已下架')
  await loadProducts()
}

const deleteProduct = async (id) => {
  await api.adminDeleteProduct(id)
  Message.success('商品已删除')
  await loadProducts()
}

const saveProfile = async () => {
  await api.updateMe({ nickname: profile.nickname, phone: profile.phone, address: profile.address })
  Message.success('已保存')
}

const loadMerchantOptions = async () => {
  const list = await api.adminUsers()
  merchantOptions.value = list.filter((u) => u.role === 'MERCHANT').map((u) => ({ label: `${u.nickname || u.username} (${u.username})`, value: u.id }))
}

import { IconSafe, IconDashboard, IconFile, IconExclamation, IconApps, IconCheckCircle, IconUserGroup, IconMessage, IconSend, IconStorage, IconUser, IconTrophy, IconHome, IconExport, IconSettings, IconGift, IconPlus, IconRefresh, IconUserAdd, IconRelation, IconPhone, IconLocation, IconCheck } from '@arco-design/web-vue/es/icon'

onMounted(async () => {
  try {
    await userStore.fetchMe()
    if (userStore.role !== 'ADMIN') {
      Message.warning('请使用管理员账号访问')
      return router.replace('/login')
    }
    await Promise.all([loadOverview(), loadUsers(), loadMerchantOptions(), loadProfile()])
    window.addEventListener('resize', handleResize)
  } catch (e) {
    Message.error(e.message)
    router.replace('/login')
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  categoryChart?.dispose()
  hotChart?.dispose()
})
</script>

<style scoped>
.admin-layout {
  background: #f0f2f5;
}

.admin-sider {
  background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%);
}

.sider-header {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 0 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.sider-title {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
}

.admin-main {
  background: #f0f2f5;
}

.admin-header {
  background: #fff;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  height: 64px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.admin-content {
  padding: 24px;
  overflow: auto;
}

.overview-card {
  border-radius: 12px;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stat-card {
  border-radius: 12px;
  background: linear-gradient(135deg, #f0f5ff 0%, #fff 100%);
  border: none;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.stat-icon.orders {
  background: linear-gradient(135deg, #1890ff 0%, #69c0ff 100%);
  color: #fff;
}

.stat-icon.sales {
  background: linear-gradient(135deg, #52c41a 0%, #95de64 100%);
  color: #fff;
}

.stat-icon.users {
  background: linear-gradient(135deg, #722ed1 0%, #b37feb 100%);
  color: #fff;
}

.stat-icon.risks {
  background: linear-gradient(135deg, #fa8c16 0%, #ffc069 100%);
  color: #fff;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #888;
  margin-top: 4px;
}

.content-card {
  border-radius: 12px;
}

:deep(.arco-btn-primary) {
  background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
  border-color: transparent;
}

:deep(.arco-card-header) {
  border-bottom: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .stats-row {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
