<template>
  <a-tabs v-model:activeKey="activeKey" centered type="card">
    <a-tab-pane key="1" tab="传承人列表">
      <CommonListBlock
        ref="listRef"
        :show-total="true"
        :row-count="1"
        :row-type="5"
        :page-size="10"
        :drop-down-names="[
          {
            options: selfAssessmentProgressOptions,
            label: '状态',
            defaultSelectedValue: lastSelfAssessmentProgress,
          },
          {
            options: selfAssessmentLevelOptions,
            label: '等级',
            defaultSelectedValue: lastSelfAssessmentLevel,
          },
          {
            options: [
              { id: 0, name: '全部审核' },
              { id: 1, name: '审核通过' },
              { id: 2, name: '审核退回' },
            ],
            label: '审核状态',
            defaultSelectedValue: 0,
          }
        ]"
        :load="(page: number, pageSize: number, _tag: number, searchText: string, drop: number[]) => loadSelfAssessmentAdminList(page, pageSize, searchText, drop)"
        :show-detail="handleReviewSelfAssessment"
      >
        <template #headLeft>
          <a-button type="primary" @click="openDownloadModal">打包下载</a-button>
        </template>
        <template #itemRight="{ item }">
          <a-popover v-if="item.rejectType && item.rejectType > 0" title="退回原因" trigger="hover">
            <template #content>
              <div style="max-width: 300px">{{ item.rejectReason || '无' }}</div>
            </template>
            <span class="mr-3 text-sm" style="color: #f5222d; cursor: pointer;">
              <ExclamationCircleOutlined /> 已退回
            </span>
          </a-popover>
          <span 
            v-else 
            class="mr-3 text-sm text-gray-600"
          >
            {{ selfAssessmentProgressLabel(item.progress) }}
          </span>
          <a-button type="link" @click.stop="router.push({ name: 'CollectEvaluationForm', query: { id: item.checkId ?? item.id, userId: item.userId } })">编辑</a-button>
          <a-button
            type="primary"
            v-if="canReview(item)"
            @click.stop="handleReviewSelfAssessment(item)"
          >
            审核
          </a-button>
        </template>
      </CommonListBlock>
    </a-tab-pane>
    <a-tab-pane key="2" tab="审核记录">
      <CommonListBlock
        ref="listRef"
        :show-total="true"
        :row-count="1"
        :row-type="5"
        :page-size="10"
        :drop-down-names="[
          {
            options: checkLogStatusOptions,
            label: '状态',
            defaultSelectedValue: lastCheckLogStatus,
          },
          {
            options: checkLogReviewTypeOptions,
            label: '审核环节',
            defaultSelectedValue: lastCheckLogReviewType,
          },
        ]"
        :load="(page: number, pageSize: number, _tag: number, searchText: string, drop: number[]) => loadCheckLogList(page, pageSize, searchText, drop)"
        :show-detail="() => {}"
      >
        <template #itemRight="{ item }">
          <a-tag :color="item.status === 1 ? 'green' : 'red'">{{ item.statusText || (item.status === 1 ? '通过' : '退回') }}</a-tag>
          <span class="mr-3 text-sm text-gray-600">{{ item.reviewTypeText }}</span>
        </template>
      </CommonListBlock>
    </a-tab-pane>
  </a-tabs>

  <a-modal
    v-model:open="showDownloadModal"
    title="打包下载自查表"
    @ok="handleDownloadZip"
    :confirmLoading="downloading"
    okText="下载"
    cancelText="取消"
  >
    <a-form layout="vertical">
      <a-form-item label="年份">
        <a-input-number v-model:value="downloadYear" :min="2020" :max="2030" style="width: 100%" />
      </a-form-item>
      <a-form-item label="状态">
        <a-select v-model:value="downloadProgress" style="width: 100%">
          <a-select-option v-for="opt in downloadProgressOptions" :key="opt.id" :value="opt.id">{{ opt.name }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { ExclamationCircleOutlined, InfoCircleOutlined } from '@ant-design/icons-vue';
import CommonListBlock, { type DropdownCommonItem } from '@/components/content/CommonListBlock.vue';
import AssessmentContentApi, { SelfAssessmentDetail } from '@/api/collect/AssessmentContent';
import { useMemorizeVar } from '@/composeables/useMemorizeVar';
import { useAuthStore } from '@/stores/auth';
import { GROUP_TO_REVIEW_PROGRESS } from './composeables/GroupData';

const router = useRouter();

const activeKey = ref('1');
const listRef = ref<any>(null);

const showDownloadModal = ref(false);
const downloading = ref(false);
const downloadYear = ref(new Date().getFullYear() - 1);
const downloadProgress = ref(-100);

const { variable: lastSelfAssessmentProgress } = useMemorizeVar('adminSelfAssessmentProgress', -100);
const { variable: lastSelfAssessmentLevel } = useMemorizeVar('adminSelfAssessmentLevel', 0);
const { variable: lastCheckLogStatus } = useMemorizeVar('adminCheckLogStatus', 0);
const { variable: lastCheckLogReviewType } = useMemorizeVar('adminCheckLogReviewType', 0);

const selfAssessmentLevelOptions: DropdownCommonItem[] = [
  { id: 0, name: '全部等级' },
  { id: 23, name: '国家级' },
  { id: 24, name: '省级' },
  { id: 25, name: '市级' },
];

const selfAssessmentProgressOptions: DropdownCommonItem[] = [
  { id: -100, name: '全部状态' },
  { id: -1, name: '未提交' },
  { id: 0, name: '草稿' },
  { id: 1, name: '已提交审核' },
  { id: 2, name: '项目保护单位审核完成' },
  { id: 3, name: '县（区）文旅部门审核完成' },
  { id: 4, name: '设区市文旅部门/省非遗中心审核完成' },
  { id: 5, name: '省文化和旅游厅审核完成' },
];

const checkLogStatusOptions: DropdownCommonItem[] = [
  { id: 0, name: '全部状态' },
  { id: 1, name: '通过' },
  { id: 2, name: '退回' },
];

const checkLogReviewTypeOptions: DropdownCommonItem[] = [
  { id: 0, name: '全部环节' },
  { id: 1, name: '自评阶段' },
  { id: 2, name: '项目保护单位' },
  { id: 3, name: '县（区）文旅部门' },
  { id: 4, name: '设区市文旅部门、省非遗中心' },
  { id: 5, name: '省文化和旅游厅' },
];

const downloadProgressOptions: DropdownCommonItem[] = [
  { id: -100, name: '全部状态' },
  { id: -1, name: '未提交' },
  { id: 0, name: '草稿' },
  { id: 1, name: '已提交审核' },
  { id: 2, name: '项目保护单位审核完成' },
  { id: 3, name: '县（区）文旅部门审核完成' },
  { id: 4, name: '设区市文旅部门/省非遗中心审核完成' },
  { id: 5, name: '省文化和旅游厅审核完成' },
];


const authStore = useAuthStore();
const currentUserGroups = computed(() => authStore.userInfo?.adminGroup || []);

function canReview(item: SelfAssessmentDetail) { 
  const currentUserGroup = currentUserGroups.value.find((group) => GROUP_TO_REVIEW_PROGRESS[group.id]);
  const currentUserReviewProgress = GROUP_TO_REVIEW_PROGRESS[currentUserGroup?.id ?? 0] ?? 0;
  return item.checkId 
    && item.progress != null && item.progress >= 1 && item.progress < 5 //必须已经提交
    && item.progress < currentUserReviewProgress; // 当前审核阶段未完成
}

function selfAssessmentProgressLabel(progress: number | null | undefined) {
  if (progress === null || progress === undefined)
    return '未填写';
  const hit = selfAssessmentProgressOptions.find((o) => o.id === progress);
  return hit?.name ?? `进度 ${progress}`;
}

async function loadSelfAssessmentAdminList(page: number, pageSize: number, searchText: string, dropDownValues: number[]) {
  const pv = dropDownValues?.[0];
  const lv = dropDownValues?.[1];
  const st = dropDownValues?.[2];
  lastSelfAssessmentProgress.value = pv ?? -100;
  lastSelfAssessmentLevel.value = lv ?? 0;
  const progress = pv != null && pv > -50 ? pv : undefined;
  const level = lv != null && lv > 0 ? lv : undefined;
  const list = await AssessmentContentApi.getInheritorList({
    year: new Date().getFullYear(),
    page,
    pageSize,
    keywords: searchText?.trim() || undefined,
    progress,
    level,
    logStatus: st > 0 ? st : undefined,
  });
  return {
    page,
    total: list.total,
    data: list.data.map((row) => ({
      ...row,
      id: row.id,
      userId: row.userId,
      title: row.title ?? '?',
      desc: [row.mobile, row.unit, row.ichTitle].filter(Boolean).join(' · ') || '—',
    })),
  };
}

async function loadCheckLogList(page: number, pageSize: number, searchText: string, dropDownValues: number[]) {
  const sv = dropDownValues?.[0];
  const rv = dropDownValues?.[1];
  lastCheckLogStatus.value = sv ?? 0;
  lastCheckLogReviewType.value = rv ?? 0;
  const status = sv != null && sv > 0 ? sv : undefined;
  const reviewType = rv != null && rv > 0 ? rv : undefined;
  const list = await AssessmentContentApi.getCheckLogList({
    year: new Date().getFullYear(),
    page,
    pageSize,
    keywords: searchText?.trim() || undefined,
    status,
    reviewType,
  });
  return {
    page,
    total: list.total,
    data: list.data.map((row) => ({
      ...row,
      id: row.id,
      title: row.inheritor ?? '?',
      desc: [
        row.reviewTypeText,
        row.statusText,
        row.reason,
        row.createtime,
      ].filter(Boolean).join(' · ') || '—',
    })),
  };
}

function handleReviewSelfAssessment(item: SelfAssessmentDetail) {
  const cid = item.checkId;
  const uid = item.userId;
  if (!cid || !uid) {
    message.warning('缺少自查表 ID 或传承人用户 ID');
    return;
  }
  router.push({
    name: 'CollectEvaluationFormReview',
    query: {
      id: String(cid),
      userId: String(uid),
      ...(item.progress != null && item.progress !== undefined ? { progress: String(item.progress) } : {}),
    },
  });
}

async function handleDownloadZip() {
  downloading.value = true;
  try {
    const progress = downloadProgress.value > -50 ? downloadProgress.value : undefined;
    await AssessmentContentApi.downloadCheckZip({
      year: downloadYear.value,
      progress,
    });
    showDownloadModal.value = false;
    message.success('下载成功');
  } catch (e: any) {
    message.error(e?.message || '下载失败');
  } finally {
    downloading.value = false;
  }
}

function openDownloadModal() {
  downloadProgress.value = lastSelfAssessmentProgress.value;
  showDownloadModal.value = true;
}

defineExpose({
  reload: () => listRef.value?.reload(),
})
</script>
