<template>
  <PageContainer title="模板查看下载">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="模板列表" name="templates">
        <el-form :inline="true" :model="templateQuery" class="wo-query-form">
          <el-form-item label="模板名称">
            <el-input v-model="templateQuery.templateName" clearable placeholder="请输入模板名称" class="w-input-md" />
          </el-form-item>
          <el-form-item label="模板类型">
            <el-select v-model="templateQuery.templateType" clearable placeholder="全部" class="w-input-md">
              <el-option
                v-for="item in templateTypeOptions"
                :key="item.typeCode"
                :label="item.typeName"
                :value="item.typeCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="模板状态">
            <el-select v-model="templateQuery.status" clearable placeholder="全部" class="w-input-md">
              <el-option v-for="item in templateStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="水印下载">
            <el-select v-model="templateQuery.watermarkEnabled" clearable placeholder="全部" class="w-input-md">
              <el-option v-for="item in watermarkFilterOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="canRead" type="primary" @click="handleTemplateSearch">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetTemplateQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="templateRows" empty-text="暂无模板数据">
          <el-table-column prop="templateName" label="模板名称" min-width="180" />
          <el-table-column label="模板类型" width="130">
            <template #default="{ row }">
              {{ getTemplateTypeLabel(row.templateType) }}
            </template>
          </el-table-column>
          <el-table-column label="适用范围" width="110">
            <template #default="{ row }">
              {{ getScopeTypeLabel(row.scopeType) }}
            </template>
          </el-table-column>
          <el-table-column prop="bizScene" label="业务场景" width="140" :formatter="bizSceneFormatter" />
          <el-table-column prop="currentVersionNo" label="当前版本" width="100" />
          <el-table-column prop="status" label="状态" width="110" :formatter="statusFormatter" />
          <el-table-column label="生效时间" min-width="220">
            <template #default="{ row }">
              {{ formatEffectiveTime(row) }}
            </template>
          </el-table-column>
          <el-table-column label="水印" width="90">
            <template #default="{ row }">
              {{ row.watermarkEnabled ? "开启" : "关闭" }}
            </template>
          </el-table-column>
          <el-table-column prop="downloadRateLimitPerHour" label="限流/小时" width="110" />
          <el-table-column prop="updatedAt" label="最近更新" width="180" />
          <el-table-column label="操作" min-width="280" fixed="right">
            <template #default="{ row }">
              <el-button size="small" v-if="canRead" @click="openDetailDrawer(row)">查看详情</el-button>
              <el-button size="small" v-if="canRead" @click="focusLogs(row)">
                {{ canReadAllLogs ? "查看下载日志" : "查看我的下载日志" }}
              </el-button>
              <el-button
                size="small"
                type="primary"
                v-if="canDownload"
                :disabled="isDownloadBlocked(row)"
                @click="handleDownload(row)"
              >
                下载
              </el-button>
              <el-button
                size="small"
                type="primary"
                v-if="canDownload"
                :disabled="isWatermarkDownloadBlocked(row)"
                @click="handleDownloadWatermark(row)"
              >
                水印下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          class="mt-md"
          background
          layout="total, prev, pager, next, sizes"
          :total="templateTotalCount"
          v-model:current-page="templatePageNo"
          v-model:page-size="templatePageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="loadTemplates"
          @current-change="loadTemplates"
        />
      </el-tab-pane>

      <el-tab-pane :label="canReadAllLogs ? '下载日志' : '我的下载日志'" name="logs">
        <div class="text-secondary mb-sm">
          {{ canReadAllLogs ? "支持按模板、下载人和时间范围查看全部下载记录。" : "当前仅展示当前账号的下载日志。" }}
        </div>

        <el-form :inline="true" :model="logQuery" class="wo-query-form">
          <el-form-item label="模板名称">
            <el-input v-model="logQuery.templateName" clearable placeholder="请输入模板名称" class="w-input-md" />
          </el-form-item>
          <el-form-item label="模板ID">
            <el-input-number v-model="logQuery.templateId" :min="1" class="w-input-sm" />
          </el-form-item>
          <el-form-item v-if="canReadAllLogs" label="下载人">
            <el-input v-model="logQuery.userKeyword" clearable placeholder="姓名或手机号" class="w-input-md" />
          </el-form-item>
          <el-form-item v-if="canReadAllLogs" label="用户ID">
            <el-input-number v-model="logQuery.userId" :min="1" class="w-input-sm" />
          </el-form-item>
          <el-form-item label="版本号">
            <el-input-number v-model="logQuery.versionNo" :min="1" class="w-input-sm" />
          </el-form-item>
          <el-form-item label="下载方式">
            <el-select v-model="logQuery.downloadType" clearable placeholder="全部" class="w-input-md">
              <el-option label="普通下载" value="NORMAL" />
              <el-option label="水印下载" value="WATERMARK" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="canReadAllLogs" label="IP">
            <el-input v-model="logQuery.ip" clearable placeholder="请输入 IP" class="w-input-md" />
          </el-form-item>
          <el-form-item label="下载时间">
            <el-date-picker
              v-model="logQuery.dateRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              range-separator="至"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button v-if="canRead" type="primary" @click="handleLogSearch">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetLogQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="logRows" empty-text="暂无下载记录">
          <el-table-column prop="templateName" label="模板名称" min-width="180">
            <template #default="{ row }">
              {{ row.templateName || `模板#${row.templateId}` }}
            </template>
          </el-table-column>
          <el-table-column prop="versionNo" label="版本号" width="90" />
          <el-table-column label="下载方式" width="120">
            <template #default="{ row }">
              {{ getDownloadTypeLabel(row.downloadType) }}
            </template>
          </el-table-column>
          <el-table-column v-if="canReadAllLogs" label="下载人" min-width="180">
            <template #default="{ row }">
              <span v-if="row.userName || row.userPhone">
                {{ row.userName || "-" }}<span v-if="row.userPhone"> / {{ row.userPhone }}</span>
              </span>
              <span v-else>{{ `用户#${row.userId}` }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="watermarkText" label="水印文案" min-width="160" show-overflow-tooltip />
          <el-table-column prop="objectKey" label="ObjectKey" min-width="260" show-overflow-tooltip />
          <el-table-column prop="ip" label="IP" width="140" />
          <el-table-column prop="downloadedAt" label="下载时间" width="180" />
          <el-table-column prop="userAgent" label="终端信息" min-width="220" show-overflow-tooltip />
        </el-table>

        <el-pagination
          class="mt-md"
          background
          layout="total, prev, pager, next, sizes"
          :total="logTotalCount"
          v-model:current-page="logPageNo"
          v-model:page-size="logPageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="loadLogs"
          @current-change="loadLogs"
        />
      </el-tab-pane>
    </el-tabs>

    <el-drawer v-model="detailVisible" title="模板详情" :size="DRAWER_SIZE.lg" destroy-on-close>
      <template v-if="detailRow">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">{{ detailRow.templateName || "-" }}</el-descriptions-item>
          <el-descriptions-item label="模板状态">{{ getStatusLabel(detailRow.status) }}</el-descriptions-item>
          <el-descriptions-item label="模板类型">{{ getTemplateTypeLabel(detailRow.templateType) }}</el-descriptions-item>
          <el-descriptions-item label="业务场景">{{ getBizSceneLabel(detailRow.bizScene) }}</el-descriptions-item>
          <el-descriptions-item label="适用范围">{{ getScopeTypeLabel(detailRow.scopeType) }}</el-descriptions-item>
          <el-descriptions-item label="当前版本">V{{ detailRow.currentVersionNo || 1 }}</el-descriptions-item>
          <el-descriptions-item label="生效时间">{{ formatEffectiveTime(detailRow) }}</el-descriptions-item>
          <el-descriptions-item label="水印下载">{{ detailRow.watermarkEnabled ? "开启" : "关闭" }}</el-descriptions-item>
          <el-descriptions-item label="下载限流/小时">{{ detailRow.downloadRateLimitPerHour ?? "-" }}</el-descriptions-item>
          <el-descriptions-item label="最近更新">{{ detailRow.updatedAt || "-" }}</el-descriptions-item>
          <el-descriptions-item label="下载状态">
            {{ isDownloadBlocked(detailRow) ? "当前不可下载" : "允许下载" }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="mt-md flex items-center gap-sm">
          <el-button v-if="canRead" @click="focusLogs(detailRow)">
            {{ canReadAllLogs ? "查看下载日志" : "查看我的下载日志" }}
          </el-button>
          <el-button v-if="canDownload" type="primary" :disabled="isDownloadBlocked(detailRow)" @click="handleDownload(detailRow)">
            下载
          </el-button>
          <el-button
            v-if="canDownload"
            type="primary"
            :disabled="isWatermarkDownloadBlocked(detailRow)"
            @click="handleDownloadWatermark(detailRow)"
          >
            水印下载
          </el-button>
        </div>

        <el-descriptions v-if="currentVersionDetail" class="mt-md" :column="2" border>
          <el-descriptions-item label="当前版本 ObjectKey">
            {{ currentVersionDetail.objectKey || detailRow.currentObjectKey || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="当前版本状态">
            {{ getStatusLabel(currentVersionDetail.versionStatus) }}
          </el-descriptions-item>
          <el-descriptions-item label="当前版本变更说明">
            {{ currentVersionDetail.changeLog || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="当前版本创建时间">
            {{ currentVersionDetail.createdAt || "-" }}
          </el-descriptions-item>
        </el-descriptions>

        <el-tabs class="mt-md">
          <el-tab-pane label="版本历史">
            <el-table :data="detailVersionRows" empty-text="暂无版本记录">
              <el-table-column prop="versionNo" label="版本号" width="90" />
              <el-table-column prop="versionStatus" label="状态" width="100" :formatter="statusFormatter" />
              <el-table-column label="当前生效" width="100">
                <template #default="{ row }">
                  {{ row.effective ? "是" : "否" }}
                </template>
              </el-table-column>
              <el-table-column prop="objectKey" label="ObjectKey" min-width="220" show-overflow-tooltip />
              <el-table-column prop="changeLog" label="变更说明" min-width="180" />
              <el-table-column prop="rollbackReason" label="回滚原因" min-width="180" />
              <el-table-column prop="createdAt" label="创建时间" width="180" />
            </el-table>
          </el-tab-pane>

          <el-tab-pane :label="canReadAllLogs ? '最近下载' : '我的最近下载'">
            <el-table :data="detailDownloadRows" empty-text="暂无下载记录">
              <el-table-column prop="downloadedAt" label="下载时间" width="180" />
              <el-table-column label="下载方式" width="120">
                <template #default="{ row }">
                  {{ getDownloadTypeLabel(row.downloadType) }}
                </template>
              </el-table-column>
              <el-table-column v-if="canReadAllLogs" label="下载人" min-width="180">
                <template #default="{ row }">
                  <span v-if="row.userName || row.userPhone">
                    {{ row.userName || "-" }}<span v-if="row.userPhone"> / {{ row.userPhone }}</span>
                  </span>
                  <span v-else>{{ `用户#${row.userId}` }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="watermarkText" label="水印文案" min-width="160" show-overflow-tooltip />
              <el-table-column prop="ip" label="IP" width="140" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-drawer>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import PageContainer from "../../components/PageContainer.vue";
import {
  downloadTemplate,
  downloadTemplateWatermark,
  fetchTemplateDownloadLogs,
  fetchTemplateTypeOptions,
  fetchTemplateVersions,
  fetchTemplates,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { DRAWER_SIZE } from "../../constants/ui";
import { useAuthStore } from "../../stores/auth";

type TemplateTypeCode = "AGENDA" | "SIGN_IN" | "INVITATION" | "OTHER";
type BizSceneCode = "MEETING_RECOMMEND" | "AUDIT_NOTIFY" | "SETTLEMENT";
type ScopeTypeCode = "ALL" | "PROJECT" | "MEETING";

const STATUS_LABELS: Record<string, string> = {
  ENABLED: "启用",
  DISABLED: "停用",
  DRAFT: "草稿",
  PUBLISHED: "已发布",
  ARCHIVED: "已归档",
};

const BIZ_SCENE_LABELS: Record<string, string> = {
  MEETING_RECOMMEND: "会议推荐",
  AUDIT_NOTIFY: "审核通知",
  SETTLEMENT: "结算",
};

const authStore = useAuthStore();
const route = useRoute();

const canRead = computed(() => authStore.hasPermission(PERMS.template.read));
const canDownload = computed(() => authStore.hasPermission(PERMS.template.download));
const canReadAllLogs = computed(() => authStore.hasPermission(PERMS.template.downloadLogReadAll));

const activeTab = ref<"templates" | "logs">("templates");

const templateRows = ref<any[]>([]);
const templatePageNo = ref(1);
const templatePageSize = ref(20);
const templateTotalCount = ref(0);

const logRows = ref<any[]>([]);
const logPageNo = ref(1);
const logPageSize = ref(20);
const logTotalCount = ref(0);

const detailVisible = ref(false);
const detailRow = ref<any | null>(null);
const detailVersionRows = ref<any[]>([]);
const detailDownloadRows = ref<any[]>([]);

const templateTypeOptions = ref<Array<{ typeCode: TemplateTypeCode; typeName: string; status: "ENABLED" | "DISABLED" }>>([]);

const templateStatusOptions = [
  { label: "草稿", value: "DRAFT" },
  { label: "已发布", value: "PUBLISHED" },
  { label: "已停用", value: "DISABLED" },
  { label: "已归档", value: "ARCHIVED" },
];

const scopeTypeOptions = [
  { label: "全部", value: "ALL" },
  { label: "项目级", value: "PROJECT" },
  { label: "会议级", value: "MEETING" },
];

const watermarkFilterOptions = [
  { label: "开启", value: "true" },
  { label: "关闭", value: "false" },
];

const templateQuery = ref({
  templateName: "",
  templateType: "" as TemplateTypeCode | "",
  status: "",
  watermarkEnabled: "" as "" | "true" | "false",
});

const logQuery = ref({
  templateId: undefined as number | undefined,
  templateName: "",
  userId: undefined as number | undefined,
  userKeyword: "",
  versionNo: undefined as number | undefined,
  downloadType: "" as "" | "NORMAL" | "WATERMARK",
  ip: "",
  dateRange: [] as string[],
});

const currentVersionDetail = computed(() => {
  if (!detailVersionRows.value.length) {
    return null;
  }
  const currentVersionNo = Number(detailRow.value?.currentVersionNo || 0);
  return (
    detailVersionRows.value.find((item) => Number(item.versionNo) === currentVersionNo) ||
    detailVersionRows.value.find((item) => Boolean(item.effective)) ||
    detailVersionRows.value[0]
  );
});

const getStatusLabel = (value?: unknown) => {
  const key = String(value ?? "").trim();
  return STATUS_LABELS[key] || key || "-";
};

const getBizSceneLabel = (value?: unknown) => {
  const key = String(value ?? "").trim();
  return BIZ_SCENE_LABELS[key] || key || "-";
};

const getTemplateTypeLabel = (code: string) =>
  templateTypeOptions.value.find((item) => item.typeCode === code)?.typeName || code || "-";

const getScopeTypeLabel = (code: ScopeTypeCode | string) =>
  scopeTypeOptions.find((item) => item.value === code)?.label || code || "-";

const getDownloadTypeLabel = (value?: unknown) => (String(value ?? "").trim() === "WATERMARK" ? "水印下载" : "普通下载");

const statusFormatter = (_row: any, _column: any, value: unknown) => getStatusLabel(value);
const bizSceneFormatter = (_row: any, _column: any, value: unknown) => getBizSceneLabel(value);

const formatEffectiveTime = (row: any) => {
  const start = String(row?.effectiveFrom || "").trim();
  const end = String(row?.effectiveTo || "").trim();
  if (!start && !end) {
    return "长期有效";
  }
  return `${start || "未设置"} ~ ${end || "未设置"}`;
};

const buildTemplateName = (row: any) => row?.templateName || `模板#${row?.id ?? "-"}`;
const isDownloadBlocked = (row?: any) => ["DISABLED", "ARCHIVED"].includes(String(row?.status || "").trim().toUpperCase());
const isWatermarkDownloadBlocked = (row?: any) => isDownloadBlocked(row) || !row?.watermarkEnabled;

const confirmAction = async (message: string, title: string) => {
  try {
    await ElMessageBox.confirm(message, title, {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    });
    return true;
  } catch {
    return false;
  }
};

const buildTemplateParams = () => ({
  templateName: templateQuery.value.templateName || undefined,
  templateType: templateQuery.value.templateType || undefined,
  status: templateQuery.value.status || undefined,
  watermarkEnabled: templateQuery.value.watermarkEnabled ? templateQuery.value.watermarkEnabled === "true" : undefined,
  pageNo: templatePageNo.value,
  pageSize: templatePageSize.value,
});

const buildLogParams = () => ({
  templateId: logQuery.value.templateId,
  templateName: logQuery.value.templateName || undefined,
  userId: canReadAllLogs.value ? logQuery.value.userId : undefined,
  userKeyword: canReadAllLogs.value ? logQuery.value.userKeyword || undefined : undefined,
  versionNo: logQuery.value.versionNo,
  downloadType: logQuery.value.downloadType || undefined,
  ip: canReadAllLogs.value ? logQuery.value.ip || undefined : undefined,
  downloadedFrom: logQuery.value.dateRange?.[0] || undefined,
  downloadedTo: logQuery.value.dateRange?.[1] || undefined,
  pageNo: logPageNo.value,
  pageSize: logPageSize.value,
});

const initQueryFromRoute = () => {
  const routeTemplateId = Number(route.query.templateId || 0);
  const routeTemplateName = String(route.query.templateName || "").trim();
  if (routeTemplateId > 0) {
    logQuery.value.templateId = routeTemplateId;
    activeTab.value = "logs";
  }
  if (routeTemplateName) {
    logQuery.value.templateName = routeTemplateName;
  }
};

const loadTemplateTypeOptions = async () => {
  if (!canRead.value) {
    templateTypeOptions.value = [];
    return;
  }
  const resp = await fetchTemplateTypeOptions();
  templateTypeOptions.value = resp?.data || [];
};

const loadTemplates = async () => {
  if (!canRead.value) {
    templateRows.value = [];
    templateTotalCount.value = 0;
    return;
  }
  const resp = await fetchTemplates(buildTemplateParams());
  templateRows.value = resp?.data?.list || [];
  templateTotalCount.value = Number(resp?.data?.total || 0);
};

const loadLogs = async () => {
  if (!canRead.value) {
    logRows.value = [];
    logTotalCount.value = 0;
    return;
  }
  const resp = await fetchTemplateDownloadLogs(buildLogParams());
  logRows.value = resp?.data?.list || [];
  logTotalCount.value = Number(resp?.data?.total || 0);
};

const refreshDetailData = async () => {
  if (!detailRow.value?.id || !canRead.value) {
    detailVersionRows.value = [];
    detailDownloadRows.value = [];
    return;
  }
  const [versionsResp, logsResp] = await Promise.all([
    fetchTemplateVersions(detailRow.value.id),
    fetchTemplateDownloadLogs({
      templateId: detailRow.value.id,
      pageNo: 1,
      pageSize: 10,
    }),
  ]);
  detailVersionRows.value = versionsResp?.data || [];
  detailDownloadRows.value = logsResp?.data?.list || [];
};

const openDetailDrawer = async (row: any) => {
  detailRow.value = { ...row };
  detailVisible.value = true;
  await refreshDetailData();
};

const handleTemplateSearch = async () => {
  templatePageNo.value = 1;
  await loadTemplates();
};

const handleLogSearch = async () => {
  logPageNo.value = 1;
  await loadLogs();
};

const resetTemplateQuery = async () => {
  templateQuery.value = {
    templateName: "",
    templateType: "",
    status: "",
    watermarkEnabled: "",
  };
  templatePageNo.value = 1;
  templatePageSize.value = 20;
  await loadTemplates();
};

const resetLogQuery = async () => {
  logQuery.value = {
    templateId: undefined,
    templateName: "",
    userId: undefined,
    userKeyword: "",
    versionNo: undefined,
    downloadType: "",
    ip: "",
    dateRange: [],
  };
  logPageNo.value = 1;
  logPageSize.value = 20;
  await loadLogs();
};

const focusLogs = async (row?: any) => {
  if (row?.id) {
    logQuery.value.templateId = Number(row.id);
    logQuery.value.templateName = row.templateName || "";
  }
  activeTab.value = "logs";
  logPageNo.value = 1;
  await loadLogs();
};

const handleDownload = async (row: any) => {
  if (isDownloadBlocked(row)) {
    ElMessage.warning("该模板已停用或归档，当前不可下载");
    return;
  }
  const resp = await downloadTemplate(row.id);
  const url = resp?.data?.signedUrl;
  if (!url) {
    ElMessage.error("获取下载链接失败");
    return;
  }
  window.open(url, "_blank");
  ElMessage.success("已生成下载链接并记录下载日志");
  await Promise.all([loadLogs(), refreshDetailData()]);
};

const handleDownloadWatermark = async (row: any) => {
  if (isWatermarkDownloadBlocked(row)) {
    ElMessage.warning(isDownloadBlocked(row) ? "该模板已停用或归档，当前不可下载" : "该模板未开启水印下载");
    return;
  }
  const confirmed = await confirmAction(
    `确认对「${buildTemplateName(row)}」执行水印下载？系统会记录本次下载日志。`,
    "水印下载",
  );
  if (!confirmed) {
    return;
  }
  const resp = await downloadTemplateWatermark(row.id, { watermarkText: "仅限内部使用" });
  const url = resp?.data?.signedUrl;
  if (!url) {
    ElMessage.error("获取水印下载链接失败");
    return;
  }
  window.open(url, "_blank");
  ElMessage.success("已生成水印下载链接并记录下载日志");
  await Promise.all([loadLogs(), refreshDetailData()]);
};

onMounted(async () => {
  initQueryFromRoute();
  await loadTemplateTypeOptions();
  await Promise.all([loadTemplates(), loadLogs()]);
});
</script>
