<template>
  <div class="project-page">
    <!-- 顶部导航栏 -->
    <header class="navbar">
      <div class="nav-left">
        <el-icon class="logo-icon" :size="24"><Platform /></el-icon>
        <span class="system-name">API对接项目中心</span>
      </div>
      <nav class="nav-menu">
        <a href="#" class="nav-item active">项目管理</a>
      </nav>
      <div class="nav-right">
        <el-dropdown>
          <div class="user-info">
            <el-avatar :size="32" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            <span class="username">张三</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>个人中心</el-dropdown-item>
              <el-dropdown-item divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 主体内容 -->
    <main class="content-container">
      <div class="page-header">
        <div class="stats-info">
          共计项目数 <span class="count-highlight">{{ totalProjects }}</span> 个
        </div>
        <div class="header-actions">
          <el-input
            v-model="searchQuery"
            placeholder="搜索项目名称..."
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" icon="Plus" @click="handleAdd">新建项目</el-button>
        </div>
      </div>

      <!-- 项目卡片网格 -->
      <div v-if="pagedProjects.length > 0" class="project-grid-wrapper">
        <el-row :gutter="24" class="project-grid">
          <el-col 
            v-for="item in pagedProjects" 
            :key="item.id" 
            :xs="24" :sm="12" :md="12" :lg="8" :xl="6"
            class="grid-item"
          >
            <div 
              class="project-card" 
              :class="{ 'is-selected': selectedId === item.id }"
              @click="selectProject(item.id)"
              @dblclick="enterProject"
            >
              <!-- 选中标记 -->
              <div v-if="selectedId === item.id" class="selected-badge">
                <el-icon><Check /></el-icon>
              </div>

              <!-- 卡片内容 -->
              <div class="card-body">
                <div class="project-logo">
                  <el-image :src="item.logo" fit="cover">
                    <template #error>
                      <div class="image-placeholder">
                        <el-icon :size="40"><OfficeBuilding /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                
                <el-tooltip
                  effect="dark"
                  :content="item.name"
                  placement="top"
                  :show-after="500"
                >
                  <h3 class="project-name">{{ item.name }}</h3>
                </el-tooltip>
                
                <div class="stats-grid">
                  <div class="stat-item">
                    <span class="label">商品数</span>
                    <span class="value">{{ item.productCount }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">订单数</span>
                    <span class="value">{{ item.orderCount }}</span>
                  </div>
                  <div class="stat-item success">
                    <span class="label">已完成</span>
                    <span class="value">{{ item.completedCount }}</span>
                  </div>
                  <div class="stat-item warning">
                    <span class="label">待付款</span>
                    <span class="value">{{ item.unpaidCount }}</span>
                  </div>
                  <div class="stat-item info">
                    <span class="label">待发货</span>
                    <span class="value">{{ item.unshippedCount }}</span>
                  </div>
                  <div class="stat-item danger">
                    <span class="label">退款订单</span>
                    <span class="value">{{ item.refundCount }}</span>
                  </div>
                  <div class="stat-item primary">
                    <span class="label">订单金额</span>
                    <span class="value">¥{{ item.orderAmount.toLocaleString() }}</span>
                  </div>
                  <div class="stat-item danger">
                    <span class="label">退款金额</span>
                    <span class="value">¥{{ item.refundAmount.toLocaleString() }}</span>
                  </div>
                </div>
              </div>

              <div class="card-footer">
                <el-button link type="primary" icon="Edit" @click.stop="handleEdit(item)">编辑</el-button>
                <el-button link type="danger" icon="Delete" @click.stop="handleDelete(item)">删除</el-button>
                <el-button link type="primary" icon="Right" @click.stop="enterProject">进入项目</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-container">
        <el-empty 
          description="暂无相关项目信息" 
          :image-size="200"
        >
          <template #extra>
            <el-button type="primary" plain icon="Refresh" @click="searchQuery = ''">清除搜索</el-button>
          </template>
        </el-empty>
      </div>

      <!-- 分页栏 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalProjects"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="550px"
      destroy-on-close
      class="project-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        style="padding: 20px 40px 0 20px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="Logo 地址" prop="logo">
          <el-input v-model="form.logo" placeholder="请输入 Logo 图片 URL" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品数" prop="productCount">
              <el-input-number v-model="form.productCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单数" prop="orderCount">
              <el-input-number v-model="form.orderCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="待付款" prop="unpaidCount" label-width="70px">
              <el-input-number v-model="form.unpaidCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="待发货" prop="unshippedCount" label-width="70px">
              <el-input-number v-model="form.unshippedCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已完成" prop="completedCount" label-width="70px">
              <el-input-number v-model="form.completedCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="退款订单" prop="refundCount">
              <el-input-number v-model="form.refundCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退款金额" prop="refundAmount">
              <el-input-number v-model="form.refundAmount" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="项目金额" prop="orderAmount">
          <el-input-number v-model="form.orderAmount" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定并保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据接口
interface Project {
  id: number
  name: string
  logo: string
  productCount: number
  orderCount: number
  orderAmount: number
  refundCount: number
  refundAmount: number
  unpaidCount: number
  unshippedCount: number
  completedCount: number
}

// 按钮点击事件
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新建项目'
  dialogVisible.value = true
}

const handleEdit = (item: Project) => {
  dialogTitle.value = '编辑项目'
  Object.assign(form, item)
  dialogVisible.value = true
}

const handleDelete = (item: Project) => {
  ElMessageBox.confirm(
    `您确定要删除项目 "${item.name}" 吗？此操作不可恢复。`,
    '系统提示',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      buttonSize: 'default'
    }
  ).then(() => {
    allProjects.value = allProjects.value.filter(p => p.id !== item.id)
    ElMessage.success('项目已成功删除')
  }).catch(() => {})
}

// 表单逻辑
const dialogVisible = ref(false)
const dialogTitle = ref('新建项目')
const formRef = ref()
const form = reactive({
  id: 0,
  name: '',
  logo: '',
  productCount: 0,
  orderCount: 0,
  orderAmount: 0,
  refundCount: 0,
  refundAmount: 0,
  unpaidCount: 0,
  unshippedCount: 0,
  completedCount: 0
})

const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  logo: [{ required: true, message: '请输入 Logo 地址', trigger: 'blur' }]
}

const resetForm = () => {
  form.id = 0
  form.name = ''
  form.logo = ''
  form.productCount = 0
  form.orderCount = 0
  form.orderAmount = 0
  form.refundCount = 0
  form.refundAmount = 0
  form.unpaidCount = 0
  form.unshippedCount = 0
  form.completedCount = 0
}

const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (form.id === 0) {
        // 新增
        const newProject = {
          ...form,
          id: Math.max(...allProjects.value.map(p => p.id)) + 1
        }
        allProjects.value.unshift(newProject)
        ElMessage.success('项目创建成功')
      } else {
        // 修改
        const index = allProjects.value.findIndex(p => p.id === form.id)
        if (index !== -1) {
          allProjects.value[index] = { ...form }
          ElMessage.success('项目修改已保存')
        }
      }
      dialogVisible.value = false
    }
  })
}

// 模拟数据生成
const generateData = () => {
  const data: Project[] = []
  const companies = ['武汉钢铁集团有限公司', '中建三局第一建设工程有限公司', '长飞光纤光缆股份有限公司', '东风汽车集团有限公司', '人福医药集团股份公司', '斗鱼网络科技有限公司']
  
  for (let i = 1; i <= 36; i++) {
    const baseCompany = companies[i % companies.length]
    const orderCount = Math.floor(Math.random() * 500) + 50
    data.push({
      id: i,
      name: `${baseCompany} - 项目部 ${String.fromCharCode(64 + (i % 26 + 1))}`,
      logo: `https://picsum.photos/seed/${i + 100}/120/120`,
      productCount: Math.floor(Math.random() * 100) + 10,
      orderCount: orderCount,
      orderAmount: Math.floor(Math.random() * 100000) + 10000,
      refundCount: Math.floor(Math.random() * 10),
      refundAmount: Math.floor(Math.random() * 5000),
      unpaidCount: Math.floor(orderCount * 0.2),
      unshippedCount: Math.floor(orderCount * 0.3),
      completedCount: Math.floor(orderCount * 0.4)
    })
  }
  return data
}

const allProjects = ref<Project[]>(generateData())
const selectedId = ref<number | null>(null)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(12)

const totalProjects = computed(() => {
  return allProjects.value.filter(p => p.name.includes(searchQuery.value)).length
})

const pagedProjects = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allProjects.value
    .filter(p => p.name.includes(searchQuery.value))
    .slice(start, end)
})

const selectProject = (id: number) => {
  selectedId.value = id
}

const enterProject = () => {
  window.open('https://www.baidu.com', '_blank')
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}
</script>

<style scoped lang="scss">
.project-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航 */
.navbar {
  height: 60px;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 40px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;

  .nav-left {
    display: flex;
    align-items: center;
    margin-right: 60px;

    .logo-icon {
      color: #1890ff;
      margin-right: 12px;
    }

    .system-name {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .nav-menu {
    flex: 1;
    display: flex;
    gap: 32px;

    .nav-item {
      text-decoration: none;
      color: #666;
      font-weight: 500;
      font-size: 15px;
      padding: 4px 0;
      position: relative;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }

      &.active {
        color: #1890ff;
        
        &::after {
          content: '';
          position: absolute;
          bottom: -15px;
          left: 0;
          width: 100%;
          height: 3px;
          background: #1890ff;
          border-radius: 2px;
        }
      }
    }
  }

  .nav-right {
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 4px;
      transition: background 0.3s;

      &:hover {
        background: #f0f2f5;
      }

      .username {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

/* 内容区域 */
.content-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px 40px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .stats-info {
    font-size: 16px;
    color: #606266;

    .count-highlight {
      font-weight: bold;
      color: #1890ff;
      font-size: 18px;
      margin: 0 4px;
    }
  }

  .header-actions {
    display: flex;
    gap: 16px;

    .search-input {
      width: 240px;
    }
  }
}

/* 卡片网格 */
.project-grid {
  margin-top: 20px;
}

.grid-item {
  margin-bottom: 24px;
}

/* 项目卡片样式 */
.project-card {
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
    border-color: #1890ff;
  }

  &.is-selected {
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
    background-color: #f0f7ff;
  }

  .selected-badge {
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0 32px 32px 0;
    border-color: transparent #1890ff transparent transparent;
    z-index: 10;

    .el-icon {
      position: absolute;
      top: 4px;
      right: -28px;
      color: #ffffff;
      font-size: 14px;
      font-weight: bold;
    }
  }

  .card-body {
    padding: 24px;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;

    .project-logo {
      width: 80px;
      height: 80px;
      margin-bottom: 16px;
      border-radius: 50%;
      overflow: hidden;
      background: #f5f7fa;
      border: 2px solid #fff;
      box-shadow: 0 2px 8px rgba(0,0,0,0.05);

      .el-image {
        width: 100%;
        height: 100%;
      }

      .image-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #909399;
      }
    }

    .project-name {
      margin: 0 0 20px 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      text-align: center;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .stats-grid {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;

      .stat-item {
        display: flex;
        flex-direction: column;
        
        .label {
          font-size: 11px;
          color: #909399;
          margin-bottom: 2px;
        }

        .value {
          font-size: 13px;
          color: #303133;
          font-weight: 500;
        }

        &.primary .value { color: #1890ff; font-weight: bold; }
        &.danger .value { color: #f56c6c; }
        &.success .value { color: #67c23a; }
        &.warning .value { color: #e6a23c; }
        &.info .value { color: #909399; }
      }

      /* 最后两个金额占满一行或调整比例 */
      .stat-item:nth-last-child(2),
      .stat-item:last-child {
        grid-column: span 3;
        border-top: 1px dashed #ebeef5;
        padding-top: 8px;
        margin-top: 4px;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        .label { margin-bottom: 0; font-size: 12px; }
        .value { font-size: 15px; }
      }
    }
  }

  .card-footer {
    padding: 12px 16px;
    border-top: 1px solid #ebeef5;
    background: #fafafa;
    display: flex;
    justify-content: space-around;
    
    .el-button {
      font-size: 13px;
    }
  }
}

.empty-container {
  padding: 100px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  border-radius: 12px;
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .navbar {
    padding: 0 20px;
    .nav-menu { display: none; }
    .nav-left { margin-right: 0; flex: 1; }
  }
  .content-container {
    padding: 16px 20px;
  }
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    .header-actions {
      width: 100%;
      .search-input { flex: 1; }
    }
  }
}
</style>
