<template>
  <div class="collection-container">
    <el-form class="search-form" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div v-loading="loading">
      <div class="collection-grid" v-if="collectionList && collectionList.length">
        <div class="collection-card" v-for="ic in collectionList" :key="ic.id" @click="goDetail(ic.relic)">
          <div class="collection-cover">
            <el-image
              v-if="ic.relic && ic.relic.coverImageUrl"
              :src="getFilePrefix + ic.relic.coverImageUrl"
              fit="cover"
            />
            <div v-else class="collection-cover-empty">—</div>
          </div>
          <div class="collection-info">
            <div class="collection-info-top">
              <div class="collection-name">{{ ic.relic && ic.relic.name ? ic.relic.name : ('#' + ic.itemId) }}</div>
              <el-button class="collection-unfav" type="danger" size="small" plain @click.stop="handleDelete(ic)">取消收藏</el-button>
            </div>
            <div class="collection-meta">
              <span class="collection-cat">{{ ic.relic && ic.relic.categoryInfo && ic.relic.categoryInfo.name ? ic.relic.categoryInfo.name : '—' }}</span>
              <span v-if="ic.relic && ic.relic.material" class="collection-tag">{{ ic.relic.material }}</span>
              <span v-if="ic.relic && ic.relic.age" class="collection-tag">{{ ic.relic.age }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="empty" v-else>
        <el-empty description="暂无收藏的藏品" />
      </div>
    </div>

    <div class="grid-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
  </div>
</template>

<script setup name="ItemCollection">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listItemCollection, getItemCollection, delItemCollection, addItemCollection, updateItemCollection } from "@/api/itemCollection";
import { getRelic } from "@/api/relic";
import { getCurrentSysUser } from "@/api/sysUser";

const { proxy } = getCurrentInstance();

const itemCollectionList = ref([]);
const collectionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const isAdd = ref(false)
const currentUserId = ref(null)
const getFilePrefix = proxy.getFilePrefix

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    name: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    itemId: [
      { required: true, message: "藏品id不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询收藏列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listItemCollection(queryParams.value)
    const list = Array.isArray(response.list) ? response.list : (response.data && response.data.list) || []
    const tot = response.total ?? (response.data && response.data.total) ?? 0
    itemCollectionList.value = list
    total.value = tot
    const ids = list.map(it => it.itemId).filter(Boolean)
    const uniqueIds = Array.from(new Set(ids))
    const detailMap = {}
    await Promise.all(uniqueIds.map(id => getRelic(id).then(r => {
      const d = r?.data || r
      detailMap[id] = d
    }).catch(() => {})))
    let result = list.map(ic => ({ ...ic, relic: detailMap[ic.itemId] || {} }))
    const kw = (queryParams.value.name || '').trim().toLowerCase()
    if (kw) {
      result = result.filter(ic => {
        const n = (ic.relic && ic.relic.name) ? String(ic.relic.name) : ''
        return n.toLowerCase().includes(kw)
      })
    }
    collectionList.value = result
  } finally {
    loading.value = false
  }
}

// 改变每页条数大小
function handleSizeChange(val) {
  queryParams.value.pageSize = val;
  getList();
}

// 换页
function handleCurrentChange(val) {
  queryParams.value.pageNum = val;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    itemId: null,
    createTime: null
  };
  const itemCollectionRef = proxy.$refs["itemCollectionRef"]
  if (itemCollectionRef) {
    itemCollectionRef.resetFields();
  }
}

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

/** 重置按钮操作 */
function resetQuery() {
  const queryRef = proxy.$refs["queryRef"]
  if (queryRef) {
    queryRef.resetFields();
  }
  // 保持为当前用户
  queryParams.value.userId = currentUserId.value
  queryParams.value.name = null
  handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加收藏";
  isAdd.value = true;
  // 新增时绑定当前用户ID
  form.value.userId = currentUserId.value
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getItemCollection(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改收藏";
    isAdd.value = false;
    // 保护性覆盖为当前用户
    form.value.userId = currentUserId.value
  });
}

/** 表单提交按钮 */
function submitForm() {
  proxy.$refs["itemCollectionRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {  // 添加
        addItemCollection(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      } else {  // 更新
        updateItemCollection(form.value).then(response => {
          proxy.$message({
            message: response.msg,
            type: 'success'
          })
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$confirm('确定要取消收藏该藏品吗？').then(function() {
    return delItemCollection(row.id);
  }).then(response => {
    getList();
    // proxy.$message({
    //   message: response.msg,
    //   type: 'success'
    // })
  }).catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/itemCollection/export', {
//     ...queryParams.value
//   }, `itemCollection_${new Date().getTime()}.xlsx`)
// }

// 仅查询当前登录用户的收藏
getCurrentSysUser().then(res => {
  const data = res?.data || {}
  const uid = data.id || data.userId || null
  currentUserId.value = uid
  queryParams.value.userId = uid
  getList();
}).catch(() => {
  // 获取当前用户失败时，不进行查询
  loading.value = false;
})

function goDetail(item) {
  if (!item || !item.id) return
  proxy.$router.push(`/tourist/relic/detail/${item.id}`)
}
</script>

<style scoped>
.collection-container { width: 80%; margin: 24px auto 40px; padding-top: 16px; }
.search-form { display: flex; justify-content: center; align-items: center; gap: 12px; }
.collection-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }
.collection-card { background: #f9f6f1; border: 1px solid #e7dfcf; border-radius: 12px; box-shadow: 0 6px 14px rgba(138,43,43,0.08); overflow: hidden; transition: transform 0.2s ease, box-shadow 0.2s ease; cursor: pointer; }
.collection-cover { width: 100%; height: 180px; position: relative; overflow: hidden; }
.collection-cover :deep(.el-image) { width: 100%; height: 100%; transition: transform 0.25s ease; }
.collection-cover:hover :deep(.el-image) { transform: scale(1.03); }
.collection-cover::after { content: ''; position: absolute; inset: 0; background: linear-gradient(0deg, rgba(0,0,0,0.06) 0%, rgba(0,0,0,0.02) 60%, rgba(0,0,0,0.05) 100%); pointer-events: none; }
.collection-cover-empty { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: #909399; }
.collection-info { padding: 14px; background: linear-gradient(180deg, #faf7f2 0%, #f7f3ea 100%); }
.collection-info-top { display: flex; justify-content: space-between; align-items: center; }
.collection-name { font-size: 16px; font-weight: 800; color: #2c1f1f; letter-spacing: 1px; }
.collection-name::after { content: ''; display: block; width: 36px; border-bottom: 2px solid #8a2b2b; margin: 6px 0 0; }
.collection-meta { margin-top: 8px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.collection-cat { font-size: 12px; color: #8a2b2b; background: #f5e9e2; border: 1px solid #e8d9cf; border-radius: 999px; padding: 2px 8px; }
.collection-tag { font-size: 12px; color: #2c1f1f; background: #efe9df; border: 1px solid #e0d6c7; border-radius: 999px; padding: 2px 8px; }
.grid-pagination { display: flex; justify-content: center; margin-top: 16px; }
.empty { display: flex; justify-content: center; padding: 32px 0; }
</style>
