<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>企业产品管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleTypes">
          <i class="fa-solid fa-layer-group"></i>
          分类管理
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <i class="fa-solid fa-plus"></i>
          添加产品
        </el-button>
        <el-button @click="refresh" :loading="loading">
          <i class="fa-solid fa-refresh"></i>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider></el-divider>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input v-model="searchForm.keyword" placeholder="请输入产品名称搜索" clearable style="width: 200px; margin-right: 10px"
        @keyup.enter="handleSearch" />
      <el-select v-model="searchForm.status" placeholder="状态筛选" clearable style="width: 120px; margin-right: 10px">
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
      <el-button type="primary" @click="handleSearch">
        <el-icon>
          <Search />
        </el-icon>
        搜索
      </el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="productsList" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="thumb" label="产品图片" min-width="150" align="center">
        <template #default="{ row }">
          <el-image v-if="row.thumb" :src="getImageUrl(row.thumb)" :preview-src-list="[getImageUrl(row.thumb)]"
            fit="cover" class="product-thumb" :preview-teleported="true" lazy>
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-image>

          <span v-else class="text-gray">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="产品名称" min-width="150" align="center" />
      <el-table-column prop="desc" label="产品描述" min-width="150" align="center" />
      <el-table-column prop="url" label="跳转地址" min-width="150" align="center" />
      <el-table-column prop="sort" label="排序" width="80" align="center" />
      <el-table-column prop="create_time" label="创建时间" width="180" align="center" />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon>
              <Edit />
            </el-icon>
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handlePageChange" />
    </div>

    <!-- 添加/编辑组件 -->
    <EditDialog v-model="dialogVisible" :title="dialogTitle" :is-edit="isEdit" :row-data="currentRow"
      @success="handleSuccess" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, Edit, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  getProductsList,
  updateProducts,
  deleteProducts
} from '@/api/products'
import EditDialog from './components/edit.vue'

// @ts-ignore
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const router = useRouter()

// 获取图片完整URL
// 接口可能返回：
// 1) 绝对地址：http(s)://...
// 2) 以 / 开头的相对路径：/storage/uploads/xxx.png
// 3) 不以 / 开头的相对路径：storage/uploads/xxx.png
const getImageUrl = (imagePath) => {
  if (!imagePath) return "";
  if (typeof imagePath !== 'string') imagePath = String(imagePath);
  if (imagePath.startsWith("http")) return imagePath;

  const base = (API_BASE_URL ?? '').replace(/\/$/, '');
  const path = imagePath.startsWith('/') ? imagePath : `/${imagePath}`;
  return base + path;
};

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

// 数据列表
const productsList = ref([])
const selectedIds = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentRow = ref({})

// 获取列表
const fetchList = async () => {
  loading.value = true
  try {
    const res = await getProductsList({
      page: pagination.page,
      limit: pagination.limit,
      keyword: searchForm.keyword,
      status: searchForm.status
    })
    if (res.code === 200) {
      productsList.value = res.data.list
      pagination.total = res.data.total
    }
  } catch (error) {
    console.error('获取企业产品列表失败:', error)
    ElMessage.error('获取企业产品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  pagination.page = 1
  fetchList()
}

// 刷新
const refresh = () => {
  fetchList()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.limit = val
  fetchList()
}

const handlePageChange = (val) => {
  pagination.page = val
  fetchList()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加企业产品'
  currentRow.value = {}
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑企业产品'
  currentRow.value = row
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该企业产品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteProducts(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除企业产品失败:', error)
      ElMessage.error('删除企业产品失败')
    }
  }
}

// 编辑成功回调
const handleSuccess = () => {
  fetchList()
}

// 跳转到产品分类管理页
const handleTypes = () => {
  router.push('/apps/cms/products/types')
}

// 初始化
onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.container-box {
  padding: 20px;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-bar h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
