<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { fetchGetSchoolInfo } from '@/service/api/art/school';
import SchoolCampusList from './school-campus/index.vue';
import SchoolCollegeList from './school-college/index.vue';
import SchoolDormList from './school-dorm/index.vue';
import SchoolEnrollPlanList from './school-enroll-plan/index.vue';
import SchoolMajorList from './school-major/index.vue';
import SchoolMediaList from './school-media/index.vue';
import SchoolNameList from './school-name/index.vue';
//import SchoolTagList from './school-tag/index.vue';

defineOptions({
  name: 'SchoolSubTableModal'
});

type SchoolSubModuleType =
  | 'schoolName'
  | 'schoolCampus'
  | 'schoolCollege'
  | 'schoolMajor'
  | 'schoolEnrollPlan'
  | 'schoolDorm'
  | 'schoolMedia';

type SchoolSubModuleOption = {
  key: SchoolSubModuleType;
  label: string;
};

interface Props {
  schoolId: CommonType.IdType | null;
  schoolName?: string;
  schoolData?: Api.Art.School | null;
  activeModule: SchoolSubModuleType;
}

const props = withDefaults(defineProps<Props>(), {
  schoolName: '',
  schoolData: null
});

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

const subModuleOptions: SchoolSubModuleOption[] = [
  { key: 'schoolName', label: '院校名称管理' },
  { key: 'schoolCampus', label: '校区管理' },
  { key: 'schoolCollege', label: '学院管理' },
  { key: 'schoolMajor', label: '专业管理' },
  { key: 'schoolEnrollPlan', label: '招生计划管理' },
  { key: 'schoolDorm', label: '宿舍管理' },
  { key: 'schoolMedia', label: '媒体管理' }
];

const activeTab = ref<SchoolSubModuleType>(props.activeModule);

const componentMap = {
  schoolName: SchoolNameList,
  schoolCampus: SchoolCampusList,
  schoolCollege: SchoolCollegeList,
  schoolMajor: SchoolMajorList,
  schoolEnrollPlan: SchoolEnrollPlanList,
  schoolDorm: SchoolDormList,
  schoolMedia: SchoolMediaList,
} as const;

const activeComponent = computed(() => componentMap[activeTab.value]);
const overviewLoading = ref(false);
const schoolInfo = ref<Api.Art.School | null>(props.schoolData);

const title = computed(() => {
  const moduleLabel = subModuleOptions.find(item => item.key === activeTab.value)?.label ?? '子表管理';
  const schoolLabel = props.schoolName || `学校ID：${props.schoolId ?? '-'}`;
  return `${schoolLabel} - ${moduleLabel}`;
});

const componentKey = computed(() => `${activeTab.value}-${props.schoolId ?? 'none'}`);

function formatFieldValue(value: unknown) {
  if (value === null || value === undefined || value === '') return '-';
  return String(value);
}

async function loadSchoolOverview() {
  if (props.schoolId === null) return;

  overviewLoading.value = true;

  const schoolRes = await fetchGetSchoolInfo(props.schoolId);

  if (!schoolRes.error) {
    schoolInfo.value = schoolRes.data;
  } else if (props.schoolData) {
    schoolInfo.value = props.schoolData;
  }

  overviewLoading.value = false;
}

watch(
  () => props.activeModule,
  value => {
    activeTab.value = value;
  }
);

watch(visible, show => {
  if (show) {
    activeTab.value = props.activeModule;
    loadSchoolOverview();
  }
});

watch(
  () => props.schoolId,
  value => {
    if (!visible.value || value === null) return;
    loadSchoolOverview();
  }
);

watch(
  () => props.schoolData,
  value => {
    if (!visible.value || !value) return;
    schoolInfo.value = value;
  }
);
</script>

<template>
  <NModal
    v-model:show="visible"
    preset="card"
    :title="title"
    :bordered="false"
    display-directive="show"
    class="max-w-96% w-1500px"
  >
    <div class="h-84vh flex-col overflow-hidden">
      <NCard title="院校信息（只读）" size="small" :bordered="true" :loading="overviewLoading" class="shrink-0">
        <NGrid :cols="24" :x-gap="16">
          <NGi :span="8">学校ID：{{ formatFieldValue(schoolInfo?.schoolId) }}</NGi>
          <NGi :span="8">学校编码：{{ formatFieldValue(schoolInfo?.mainCode) }}</NGi>
          <NGi :span="8">
            学校名称：{{ formatFieldValue(schoolInfo?.mainName || schoolInfo?.shortName || props.schoolName) }}
          </NGi>
          <NGi :span="8">
            省市区：{{
              formatFieldValue(
                [schoolInfo?.province, schoolInfo?.city, schoolInfo?.district].filter(Boolean).join(' / ')
              )
            }}
          </NGi>
          <NGi :span="8">大学类型：{{ formatFieldValue(schoolInfo?.universityType) }}</NGi>
          <NGi :span="8">办学性质：{{ formatFieldValue(schoolInfo?.schoolNature) }}</NGi>
          <NGi :span="8">学历层次：{{ formatFieldValue(schoolInfo?.educationLevel) }}</NGi>
          <NGi :span="8">主管部门：{{ formatFieldValue(schoolInfo?.supervisorDept) }}</NGi>
          <NGi :span="8">建校年份：{{ formatFieldValue(schoolInfo?.establishYear) }}</NGi>
        </NGrid>
      </NCard>
      <NDivider class="my-10px">子表管理区</NDivider>
      <div class="min-h-0 flex-col-stretch gap-10px overflow-hidden">
        <NTabs v-model:value="activeTab" type="line" animated class="shrink-0">
          <NTabPane v-for="item in subModuleOptions" :key="item.key" :name="item.key" :tab="item.label" />
        </NTabs>
        <div class="min-h-0 overflow-auto">
          <component
            :is="activeComponent"
            v-if="visible"
            :key="componentKey"
            :school-id="props.schoolId"
            :in-modal="true"
          />
        </div>
      </div>
    </div>
  </NModal>
</template>

<style scoped></style>
