<script setup lang="ts">
import type { MemberMessageTemplateDto } from '#/api/member/message-reach';
import type { MessageTemplatePager } from '#/views/member/message-reach/types';

import { Button, Empty, Pagination, Spin, Tag } from 'ant-design-vue';

import {
  formatInteger,
  MESSAGE_TEMPLATE_CATEGORY_COLOR_MAP,
  MESSAGE_TEMPLATE_CATEGORY_TEXT_MAP,
} from '../composables/message-reach-page/helpers';

defineProps<{
  canManage: boolean;
  loading: boolean;
  pager: MessageTemplatePager;
}>();

const emit = defineEmits<{
  (event: 'delete', templateId: string): void;
  (event: 'edit', templateId: string): void;
  (event: 'pageChange', page: number, pageSize: number): void;
  (event: 'use', template: MemberMessageTemplateDto): void;
}>();
</script>

<template>
  <div class="mmr-template-wrap">
    <Spin :spinning="loading">
      <div v-if="pager.items.length > 0" class="mmr-template-grid">
        <article
          v-for="item in pager.items"
          :key="item.templateId"
          class="mmr-template-card"
        >
          <div class="mmr-template-head">
            <div class="mmr-template-name">{{ item.name }}</div>
            <Tag :color="MESSAGE_TEMPLATE_CATEGORY_COLOR_MAP[item.category]">
              {{ MESSAGE_TEMPLATE_CATEGORY_TEXT_MAP[item.category] }}
            </Tag>
          </div>

          <div class="mmr-template-preview">
            {{ item.content }}
          </div>

          <div class="mmr-template-foot">
            <span class="mmr-template-usage">
              已使用 {{ formatInteger(item.usageCount) }}次
            </span>
            <div class="mmr-template-actions">
              <Button
                size="small"
                type="primary"
                :disabled="!canManage"
                @click="emit('use', item)"
              >
                使用
              </Button>
              <Button
                type="link"
                size="small"
                class="mmr-action-link"
                :disabled="!canManage"
                @click="emit('edit', item.templateId)"
              >
                编辑
              </Button>
              <Button
                type="link"
                size="small"
                danger
                class="mmr-action-link"
                :disabled="!canManage"
                @click="emit('delete', item.templateId)"
              >
                删除
              </Button>
            </div>
          </div>
        </article>
      </div>

      <div v-else class="mmr-template-empty">
        <Empty description="暂无消息模板" />
      </div>
    </Spin>

    <div class="mmr-pagination">
      <Pagination
        :current="pager.page"
        :page-size="pager.pageSize"
        :total="pager.totalCount"
        show-size-changer
        :show-total="(value) => `共 ${value} 条`"
        :page-size-options="['12', '24', '48']"
        @change="(page, pageSize) => emit('pageChange', page, pageSize)"
      />
    </div>
  </div>
</template>
