<template>
  <ele-page :multi-card="false">
<!--    <top-search />-->
    <ele-card :body-style="{ paddingTop: '8px' }">
      <el-button
        type="primary"
        class="ele-btn-icon"
        :icon="PlusOutlined"
        v-permission="'system:dict:add'"
        @click="openEdit()"
      >
        创建模版
      </el-button>
      <el-row :gutter="16">
        <el-col
          v-for="item in data"
          :key="item.id"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="24"
        >
          <ele-card
            shadow="hover"
            :body-style="{ padding: 0, border: '1px solid #e6e6e6' }"
            style="margin-top: 16px; overflow: hidden; cursor: pointer"
          >
            <el-image
              :src="item.preview"
              class="template-image"
              fit="contain"
              alt="模板预览图"
            />
            <div style="padding: 14px 24px 24px 24px">

                  <div  style="display: flex;justify-content: space-between">

                    <ele-text size="md" style="max-height: 100%">
                      {{ item.name }}
                    </ele-text>
                    <div style="display: flex; flex-direction:row; justify-content: space-around; align-items: center">
                      <el-button type="danger" size="small" :icon="Delete" circle @click="removeTemplate(item)" />
                      <el-button type="info" size="small" :icon="DocumentCopy" circle @click="copyTemplate(item)" />
                      <el-button type="primary" size="small" :icon="Edit" circle @click="editTemplate(item)" />
                    </div>
                  </div>

                  <ele-ellipsis
                    :max-line="2"
                    type="placeholder"
                    style="margin: 8px 0 16px 0; max-height: 100%"
                  >
                    模版编码：{{ item.uuid }}
                  </ele-ellipsis>
                  <div style="display: flex; align-items: center">
                    <ele-text type="placeholder" style="flex: 1">
                      创建时间：{{ item.createTime }}
                    </ele-text>
                  </div>
                </div>
          </ele-card>
        </el-col>
    </el-row>
    </ele-card>
  </ele-page>

</template>

<script lang="ts" setup>
  // 类型声明放在setup顶部
  interface Item {
    id: number;
    uid: number;
    name: string;
    uuid: string;
    createTime: string;
    preview: string;
  }
  import { ref } from 'vue';
  import { PlusOutlined } from 'ele-admin-plus/es/icons';
  import { getPosterTemplateList, copyPosterTemplate, delPosterTemplate, getEditorToken } from '@/api/barmgr/poster';
  import { Delete, DocumentCopy, Edit } from '@element-plus/icons-vue';
  import { EleMessage } from 'ele-admin-plus';
  import { getFastToken } from '@/utils/token-util.js';
  import { VITE_API_STORE_URL } from '@/config/setting';

  defineOptions({ name: 'ListCardProject' });

  /** 数据 */
  const data = ref<Item[]>([]);


  /** 查询数据 */
  const query = () => {
    getPosterTemplateList().then((res) => {
      data.value = res.data.private;
    });
  };
  const token = getFastToken();
  const screenWidth = screen.availWidth;
  const screenHeight = screen.availHeight;
  const fastUrl = VITE_API_STORE_URL;

  /** 打开新建 */
  const openEdit = async () => {
    try {
      const res = await getEditorToken({ purpose: 'create' });
      console.log('[openEdit] getEditorToken返回:', res);
      if (res && res.fastPosterUrl && res.editorToken) {
        const url = `${res.fastPosterUrl}?editorToken=${res.editorToken}`;
        console.log('[openEdit] 跳转URL:', url);
        window.location.href = url;
      } else {
        console.error('[openEdit] 获取编辑器令牌失败:', res);
        EleMessage.error(res.msg || '获取编辑器令牌失败');
      }
    } catch (e) {
      console.error('[openEdit] 网络异常:', e);
      EleMessage.error(e.message || '网络异常，无法打开编辑器');
    }
  };

  /** 编辑模板 */
  const editTemplate = async (item: Item) => {
    try {
      // 确保传递正确的模板ID，支持id和uuid字段
      const templateId = item.uuid || item.id;
      const posterId = item.id;
      console.log('[editTemplate] 模板数据:', item, '使用templateId:', templateId);
      
      if (!templateId) {
        EleMessage.error('模板ID缺失，无法编辑');
        return;
      }
      
      const res = await getEditorToken({ templateId: templateId, purpose: 'edit' });
      console.log('[editTemplate] getEditorToken返回:', res);
      if (res && res.fastPosterUrl && res.editorToken) {
        // 增加posterId参数
        const url = `${res.fastPosterUrl}?editorToken=${res.editorToken}&templateId=${templateId}&posterId=${posterId}`;
        console.log('[editTemplate] 跳转URL:', url);
        window.location.href = url;
      } else {
        console.error('[editTemplate] 获取编辑器令牌失败:', res);
        EleMessage.error(res.msg || '获取编辑器令牌失败');
      }
    } catch (e) {
      console.error('[editTemplate] 网络异常:', e);
      EleMessage.error(e.message || '网络异常，无法打开编辑器');
    }
  };

  /** 删除模板 */
  const removeTemplate = (item: Item) => {
    console.log('删除模板:', item.name);
    delPosterTemplate(item.id).then((res) => {
      EleMessage.success({ message: '删除成功', plain: true });
      query();
    })
  };

  /** 复制模板 */
  const copyTemplate = (item: Item) => {
    copyPosterTemplate(item.id).then((res) => {
      EleMessage.success({ message: '复制成功', plain: true });
      query();
    })
  };

  query();
</script>

<style scoped>
.template-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  object-position: center;
  display: block;
  transition: transform 0.3s ease;
}

.template-image:hover {
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .template-image {
    height: 160px;
  }
}

@media (max-width: 480px) {
  .template-image {
    height: 120px;
  }
}
</style>
