<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { UploadFileInfo } from 'naive-ui';
import { fetchImportPreviewSchool, fetchImportSchoolData } from '@/service/api/art/school';
import { useDownload } from '@/hooks/business/download';
import { $t } from '@/locales';

defineOptions({
  name: 'SchoolImportModal'
});

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();
const { download } = useDownload();

const visible = defineModel<boolean>('visible', {
  default: false
});

const fileList = ref<UploadFileInfo[]>([]);
const previewLoading = ref(false);
const importLoading = ref(false);
const replaceAll = ref(false);
const selectedReplaceMainCodes = ref<string[]>([]);
const previewResult = ref<Api.Art.SchoolImportPreviewResult | null>(null);
const importResult = ref<Api.Art.SchoolImportExecuteResult | null>(null);

const conflictDetails = computed(() => {
  return previewResult.value?.details?.filter(item => item.status === 'CONFLICT') ?? [];
});

const invalidDetails = computed(() => {
  return previewResult.value?.details?.filter(item => item.status === 'INVALID') ?? [];
});

function getCurrentFile() {
  const currentFile = fileList.value[0]?.file;
  if (!currentFile) {
    window.$message?.warning('请先选择导入文件');
    return null;
  }
  return currentFile as File;
}

function resetState() {
  fileList.value = [];
  replaceAll.value = false;
  selectedReplaceMainCodes.value = [];
  previewResult.value = null;
  importResult.value = null;
}

async function handlePreview() {
  const file = getCurrentFile();
  if (!file) return;

  previewLoading.value = true;
  const { data, error } = await fetchImportPreviewSchool(file);
  previewLoading.value = false;

  if (error) return;

  previewResult.value = data;
  importResult.value = null;
  replaceAll.value = false;
  selectedReplaceMainCodes.value = [];
  window.$message?.success('导入预检完成');
}

async function handleImport() {
  if (!previewResult.value) {
    window.$message?.warning('请先执行导入预检');
    return;
  }

  const file = getCurrentFile();
  if (!file) return;

  importLoading.value = true;
  const { data, error } = await fetchImportSchoolData({
    file,
    replaceAll: replaceAll.value,
    replaceMainCodes: replaceAll.value ? [] : selectedReplaceMainCodes.value
  });
  importLoading.value = false;

  if (error) return;

  importResult.value = data;
  window.$message?.success($t('common.importSuccess'));
  emit('submitted');
}

function handleDownloadTemplate() {
  download('/art/school/importTemplate', {}, `院校主子表_${$t('common.importTemplate')}_${new Date().getTime()}.xlsx`);
}

function getTagType(status: Api.Art.SchoolImportDetail['status']): 'default' | 'success' | 'warning' | 'error' {
  if (status === 'SUCCESS') return 'success';
  if (status === 'FAILED' || status === 'INVALID') return 'error';
  if (status === 'CONFLICT' || status === 'SKIPPED') return 'warning';
  return 'default';
}

watch(
  () => fileList.value,
  () => {
    previewResult.value = null;
    importResult.value = null;
    replaceAll.value = false;
    selectedReplaceMainCodes.value = [];
  }
);

watch(visible, show => {
  if (show) {
    resetState();
  }
});
</script>

<template>
  <NModal
    v-model:show="visible"
    :title="$t('common.import')"
    preset="card"
    :bordered="false"
    display-directive="show"
    class="max-w-92% w-760px"
  >
    <div class="flex-col-stretch gap-12px">
      <NUpload
        v-model:file-list="fileList"
        :max="1"
        :file-size="50"
        accept=".xls,.xlsx"
        :multiple="false"
        directory-dnd
        :default-upload="false"
        list-type="text"
      >
        <NUploadDragger>
          <div class="mb-12px flex-center">
            <SvgIcon icon="material-symbols:unarchive-outline" class="text-58px color-#d8d8db dark:color-#a1a1a2" />
          </div>
          <NText class="text-16px">{{ $t('common.importTip') }}</NText>
          <NP depth="3" class="mt-8px text-center">
            {{ $t('common.importSize') }}
            <b class="text-red-500">50MB</b>
            {{ $t('common.importFormat') }}
            <b class="text-red-500">xls/xlsx</b>
            {{ $t('common.importEnd') }}
          </NP>
        </NUploadDragger>
      </NUpload>

      <NAlert
        v-if="previewResult"
        :title="`预检结果：共 ${previewResult.totalSchoolCount || 0} 所，冲突 ${previewResult.conflictCount || 0}，无效 ${previewResult.invalidCount || 0}`"
        type="info"
        :bordered="false"
      />

      <NCard v-if="previewResult && conflictDetails.length" title="冲突处理" size="small" :bordered="true">
        <NSpace vertical>
          <NCheckbox v-model:checked="replaceAll">冲突院校全部替换</NCheckbox>
          <NCheckboxGroup v-model:value="selectedReplaceMainCodes">
            <NSpace vertical>
              <NCheckbox
                v-for="item in conflictDetails"
                :key="`${item.mainCode || 'empty'}-${item.mainName || ''}`"
                :value="item.mainCode || ''"
                :disabled="replaceAll || !item.mainCode"
              >
                {{ `${item.mainCode || '-'} / ${item.mainName || '-'}：${item.message || ''}` }}
              </NCheckbox>
            </NSpace>
          </NCheckboxGroup>
        </NSpace>
      </NCard>

      <NCard v-if="previewResult && invalidDetails.length" title="无效数据" size="small" :bordered="true">
        <NScrollbar class="max-h-180px">
          <NSpace vertical>
            <NTag v-for="(item, index) in invalidDetails" :key="`${item.mainCode}-${index}`" type="error" size="small">
              {{ `${item.mainCode || '-'} / ${item.mainName || '-'}：${item.message || ''}` }}
            </NTag>
          </NSpace>
        </NScrollbar>
      </NCard>

      <NCard v-if="importResult" title="导入执行结果" size="small" :bordered="true">
        <NAlert
          :title="`总数 ${importResult.totalSchoolCount || 0}，成功 ${importResult.successCount || 0}，失败 ${importResult.failCount || 0}，跳过 ${importResult.skippedCount || 0}`"
          :bordered="false"
          type="success"
        />
        <NScrollbar class="mt-10px max-h-220px">
          <NSpace vertical>
            <NTag
              v-for="(item, index) in importResult.details || []"
              :key="`${item.mainCode}-${index}`"
              :type="getTagType(item.status)"
              size="small"
            >
              {{ `${item.status || '-'} | ${item.mainCode || '-'} / ${item.mainName || '-'}：${item.message || ''}` }}
            </NTag>
          </NSpace>
        </NScrollbar>
      </NCard>
    </div>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="handleDownloadTemplate">{{ $t('common.downloadTemplate') }}</NButton>
        <NButton :loading="previewLoading" @click="handlePreview">导入预检</NButton>
        <NButton type="primary" :loading="importLoading" @click="handleImport">{{ $t('common.import') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
