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

      <!-- 项目卡片网格 -->
      <div v-loading="loading" class="project-grid-wrapper">
        <el-row v-if="itemList.length > 0" :gutter="24" class="project-grid">
          <el-col
            v-for="item in itemList"
            :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="handleEnterProject(item)"
            >
              <!-- 选中标记 -->
              <div v-if="selectedId === item.id" class="selected-badge">
                <el-icon><Check /></el-icon>
              </div>

              <!-- 状态标记 -->
              <div class="status-badge" :class="item.status === '1' ? 'is-disabled' : 'is-enabled'">
                {{ item.status === '1' ? '已关闭' : '运行中' }}
              </div>

              <!-- 卡片内容 -->
              <div class="card-body">
                <div class="project-logo">
                  <el-image :src="getLogoUrl(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.itemName"
                  placement="top"
                  :show-after="500"
                >
                  <h3 class="project-name">{{ item.itemName }}</h3>
                </el-tooltip>

                <div class="stats-grid">
                  <div class="stat-item">
                    <span class="label">商品数</span>
                    <span class="value">{{ item.productCount ?? 0 }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="label">订单数</span>
                    <span class="value">{{ item.orderCount ?? 0 }}</span>
                  </div>
                  <div class="stat-item success">
                    <span class="label">已完成</span>
                    <span class="value">{{ item.completedCount ?? 0 }}</span>
                  </div>
                  <div class="stat-item warning">
                    <span class="label">待付款</span>
                    <span class="value">{{ item.waitPayCount ?? 0 }}</span>
                  </div>
                  <div class="stat-item info">
                    <span class="label">待发货</span>
                    <span class="value">{{ item.waitDeliverCount ?? 0 }}</span>
                  </div>
                  <div class="stat-item danger">
                    <span class="label">售后订单</span>
                    <span class="value">{{ item.refundCount ?? 0 }}</span>
                  </div>
                  <div class="stat-item primary">
                    <span class="label">订单金额</span>
                    <span class="value">¥{{ (item.orderAmount ?? 0).toLocaleString() }}</span>
                  </div>
                  <div class="stat-item danger">
                    <span class="label">售后金额</span>
                    <span class="value">¥{{ (item.refundAmount ?? 0).toLocaleString() }}</span>
                  </div>
                </div>
              </div>

              <div class="card-footer">
                <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(item)">编辑</el-button>
                <el-button
                  link
                  :type="item.status === '0' ? 'warning' : 'success'"
                  :icon="item.status === '0' ? 'VideoStop' : 'VideoPlay'"
                  @click.stop="handleChangeStatus(item)"
                >{{ item.status === '0' ? '关闭' : '开启' }}</el-button>
                <el-button link type="success" icon="Right" @click.stop="handleEnterProject(item)">进入项目</el-button>
              </div>
            </div>
          </el-col>
        </el-row>

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

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

    <!-- 添加或修改第三方对接项目管理对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      append-to-body
      destroy-on-close
      class="project-dialog"
    >
      <el-form
        ref="itemFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        style="padding: 20px 40px 0 20px"
      >
        <el-form-item label="Logo地址" prop="logo">
          <FileUpload v-model="form.logo" :limit="1" :file-type="['png', 'jpg', 'jpeg', 'gif', 'webp']" />
        </el-form-item>
        <el-form-item label="项目名" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入项目名" />
        </el-form-item>
        <el-form-item label="项目key" prop="itemKey">
          <el-input v-model="form.itemKey" placeholder="请输入项目key" />
        </el-form-item>
        <el-form-item label="项目用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入项目用户名" />
        </el-form-item>
        <el-form-item label="项目密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入项目密码" />
        </el-form-item>
        <el-form-item label="项目url" prop="url">
          <el-input v-model="form.url" placeholder="请输入项目url" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确定并保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Item" lang="ts">
import { listItem, getItem, addItem, updateItem, changeItemStatus } from '@/api/external/item';
import { ItemVO, ItemQuery, ItemForm } from '@/api/external/item/types';
import { useAppStore } from '@/store/modules/app';
import cache from '@/plugins/cache';
import { listByIds } from '@/api/system/oss';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const appStore = useAppStore();

const itemList = ref<ItemVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const total = ref(0);
const selectedId = ref<string | number | null>(null);
const logoUrlMap = ref<Record<string, string>>({});

const itemFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ItemForm = {
  id: undefined,
  logo: '',
  itemName: undefined,
  itemKey: undefined,
  userName: undefined,
  password: undefined,
  url: undefined,
  status: undefined,
  remark: undefined,
}
const data = reactive<PageData<ItemForm, ItemQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 12,
    itemName: undefined,
    itemKey: undefined,
    userName: undefined,
    password: undefined,
    url: undefined,
    status: undefined,
    platformCode: undefined,
    params: {
    }
  },
  rules: {
    itemName: [
      { required: true, message: "项目名不能为空", trigger: "blur" }
    ],
    itemKey: [
      { required: true, message: "项目key不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "项目用户名不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "项目密码不能为空", trigger: "blur" }
    ],
    url: [
      { required: true, message: "项目url不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询第三方对接项目管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listItem(queryParams.value);
  itemList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  // 解析 logo ossId 为 URL
  const ossIds = itemList.value
    .filter(item => item.logo && !item.logo.startsWith('http'))
    .map(item => item.logo);
  if (ossIds.length > 0) {
    const uniqueIds = [...new Set(ossIds)].join(',');
    const ossRes = await listByIds(uniqueIds);
    ossRes.data.forEach((oss: any) => {
      logoUrlMap.value[oss.ossId] = oss.url;
    });
  }
}

/** 获取 logo 显示 URL */
const getLogoUrl = (logo: string) => {
  if (!logo) return '';
  if (logo.startsWith('http')) return logo;
  return logoUrlMap.value[logo] || '';
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  itemFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.itemName = undefined;
  handleQuery();
}

/** 选中项目 */
const selectProject = (id: string | number) => {
  selectedId.value = id;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "新建项目";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ItemVO) => {
  reset();
  const _id = row?.id
  if (!_id) return;
  const res = await getItem(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "编辑项目";
}

/** 提交按钮 */
const submitForm = () => {
  itemFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateItem(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addItem(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 开启/关闭项目 */
const handleChangeStatus = async (row?: ItemVO) => {
  if (!row?.id) return;
  const isEnabled = row.status === '0';
  const actionText = isEnabled ? '关闭' : '开启';
  await proxy?.$modal.confirm(`您确定要${actionText}项目 "${row.itemName}" 吗？`);
  const newStatus = isEnabled ? '1' : '0';
  await changeItemStatus(row.id, newStatus);
  proxy?.$modal.msgSuccess(`${actionText}成功`);
  await getList();
}

/** 进入项目 */
const handleEnterProject = (row: ItemVO) => {
  if (!row?.id) return;
  // 存储项目ID和项目信息到本地缓存
  cache.local.setJSON('currentProjectId', row.id);
  cache.local.setJSON('currentProject', {
    id: row.id,
    itemName: row.itemName,
    itemKey: row.itemKey
  });
  // 显示侧边栏
  appStore.toggleSideBarHide(false);
  // 跳转到首页
  router.push('/index');
}

onMounted(() => {
  // 隐藏侧边栏
  appStore.toggleSideBarHide(true);
  getList();
});
</script>

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

/* 内容区域 */
.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-wrapper {
  min-height: 400px;
}

.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;
      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;
    }
  }

  .status-badge {
    position: absolute;
    top: 10px;
    left: 10px;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 11px;
    font-weight: 500;
    z-index: 10;

    &.is-enabled {
      background-color: #f0f9eb;
      color: #67c23a;
      border: 1px solid #b3e19d;
    }

    &.is-disabled {
      background-color: #fef0f0;
      color: #f56c6c;
      border: 1px solid #fbc4c4;
    }
  }
}

.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) {
  .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>
