<template>
  <CommonListBlock
    ref="list2Ref"
    :show-total="true"
    :row-count="1"
    :row-type="5"
    :page-size="10"
    :drop-down-names="[
      {
        options: selfAssessmentProgressOptions,
        label: '状态',
        defaultSelectedValue: lastSelfAssessmentProgress,
      },
      {
        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>
      <div class="flex flex-row items-center gap-2">
        <a-button type="primary" @click="openDownloadModal">打包下载</a-button>
        <a-button @click="openExportExcelModal">导出Excel</a-button>
        <span>{{ progressHint }}</span>
      </div>
    </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>
      
      <div v-if="item.checkId && canReviewButPrevNotCompleted(item.progress)" class="flex flex-row items-center mr-3 text-sm">
        <ExclamationCircleOutlined /> 上一阶段未审核完成
      </div>
      <a-button
        type="primary"
        v-else-if="item.checkId && canReview(item.progress)"
        @click.stop="handleReviewSelfAssessment(item)"
      >
        审核
      </a-button>
      <a-button
        type="primary"
        v-else-if="item.agreementId && isCurrentLevelReviewed(item.progress)"
        disabled
      >
        已审核
      </a-button>
    </template>
  </CommonListBlock>

  <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>

  <a-modal
    v-model:open="showExportExcelModal"
    title="导出自查表汇总Excel"
    @ok="handleExportExcel"
    :confirmLoading="exporting"
    okText="导出"
    cancelText="取消"
  >
    <a-form layout="vertical">
      <a-form-item label="年份">
        <a-input-number v-model:value="exportYear" :min="2020" :max="2030" style="width: 100%" />
      </a-form-item>
      <a-form-item label="状态">
        <a-select v-model:value="exportProgress" 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-item label="等级">
        <span v-if="props.level != null">{{ selfAssessmentLevelOptions.find((opt) => opt.id === props.level)?.name }}</span>
        <a-select v-else v-model:value="exportLevel" style="width: 100%">
          <a-select-option v-for="opt in selfAssessmentLevelOptions" :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 { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useMemorizeVar } from '@/composeables/useMemorizeVar';
import { useReview } from './composeables/Review';
import { message } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import  AssessmentContentApi, { SelfAssessmentDetail } from '@/api/collect/AssessmentContent';
import CommonListBlock, { type DropdownCommonItem } from '@/components/content/CommonListBlock.vue';
import { LEVEL_NATIONAL, LEVEL_PROVINCE, LEVEL_DISTRICT } from '@/api/collect/AssessmentConsts';

const router = useRouter();
const route = useRoute();

const props = defineProps<{
  level?: number;
}>();

const list2Ref = ref<InstanceType<typeof CommonListBlock>>();

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

const showExportExcelModal = ref(false);
const exporting = ref(false);
const exportYear = ref(new Date().getFullYear() - 1);
const exportLevel = ref(props.level ?? 0);
const exportProgress = ref(-100);

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

const { canReview, canReviewButPrevNotCompleted, isCurrentLevelReviewed, progressHint } = useReview();

const selfAssessmentLevelOptions: DropdownCommonItem[] = [
  { id: 0, name: '全部等级' },
  { id: LEVEL_NATIONAL, name: '国家级' },
  { id: LEVEL_PROVINCE, name: '省级' },
  { id: LEVEL_DISTRICT, 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 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: '省文化和旅游厅审核完成' },
];

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(' · ') || '—',
    })),
  };
}

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,
      level: props.level ?? 0,
      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;
}

function openExportExcelModal() {
  exportProgress.value = lastSelfAssessmentProgress.value;
  exportLevel.value = lastSelfAssessmentLevel.value;
  showExportExcelModal.value = true;
}

async function handleExportExcel() {
  exporting.value = true;
  try {
    const progress = exportProgress.value > -50 ? exportProgress.value : undefined;
    const level = exportLevel.value > 0 ? exportLevel.value : undefined;
    await AssessmentContentApi.exportCheckExcel({
      year: exportYear.value,
      progress,
      level,
    });
    showExportExcelModal.value = false;
    message.success('导出成功');
  } catch (e: any) {
    message.error(e?.message || '导出失败');
  } finally {
    exporting.value = false;
  }
}

watch(() => props.level, () => {
  list2Ref.value?.reload();
  exportLevel.value = props.level ?? 0;
}, { immediate: true });

defineExpose({
  changeProgressFilter: (progress: number) => {
    lastSelfAssessmentProgress.value = progress;
    list2Ref.value?.setDropDownValue(progress, 0);
  },
  reload: () => list2Ref.value?.reload(),
});
</script>
