<script setup lang="ts">
import { ref, toRaw, watch } from 'vue';
import { jsonClone } from '@sa/utils';
import { useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'SchoolDetailSearch'
});

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

const emit = defineEmits<Emits>();

const { formRef, validate, restoreValidation } = useNaiveForm();

const model = defineModel<Api.Art.SchoolDetailSearchParams>('model', { required: true });

const defaultModel = jsonClone(toRaw(model.value));
const detailTagInputValue = ref('');
const detailTagList = ref<string[]>([]);
const booleanOptions = [
  { value: 1, label: '是' },
  { value: 0, label: '否' }
];

function toNumberValue(value: CommonType.IdType | null | undefined) {
  if (value === null || value === undefined || value === '') return null;

  return typeof value === 'number' ? value : Number(value);
}

function normalizeStringList(values?: string[] | null) {
  if (!values?.length) return [];

  const uniqueValues = new Set<string>();

  values.forEach(value => {
    const normalizedValue = String(value).trim();
    if (normalizedValue) {
      uniqueValues.add(normalizedValue);
    }
  });

  return Array.from(uniqueValues);
}

function isSameStringList(source: string[], target: string[]) {
  if (source.length !== target.length) return false;
  return source.every((value, index) => value === target[index]);
}

function syncTagsToModel() {
  model.value.tags = normalizeStringList(detailTagList.value);
}

function addDetailTags() {
  const values = detailTagInputValue.value
    .split(/[,，]/)
    .map(item => item.trim())
    .filter(Boolean);

  if (!values.length) return;

  detailTagList.value = normalizeStringList([...detailTagList.value, ...values]);
  detailTagInputValue.value = '';
}

function resetModel() {
  Object.assign(model.value, jsonClone(defaultModel));
  detailTagInputValue.value = '';
  detailTagList.value = normalizeStringList(defaultModel.tags);
  syncTagsToModel();
}

async function reset() {
  await restoreValidation();
  resetModel();
  emit('search');
}

async function search() {
  await validate();
  emit('search');
}

watch(
  detailTagList,
  tags => {
    const normalizedTags = normalizeStringList(tags);

    if (!isSameStringList(tags, normalizedTags)) {
      detailTagList.value = normalizedTags;
      return;
    }

    syncTagsToModel();
  },
  { deep: true }
);

watch(
  () => model.value.tags,
  tags => {
    const normalizedTags = normalizeStringList(tags);

    if (!isSameStringList(detailTagList.value, normalizedTags)) {
      detailTagList.value = normalizedTags;
    }
  },
  { immediate: true }
);
</script>

<template>
  <NCard :bordered="false" size="small" class="school-search-card card-wrapper">
    <NCollapse>
      <NCollapseItem :title="$t('common.search')" name="art-school-detail-search">
        <NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
          <NGrid responsive="screen" item-responsive>
            <NFormItemGi span="24 s:12 m:6" label="详情ID" label-width="auto" path="detailId" class="pr-24px">
              <NInputNumber
                :value="toNumberValue(model.detailId)"
                class="w-full"
                clearable
                placeholder="请输入详情ID"
                @update:value="value => (model.detailId = value)"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="学校ID" label-width="auto" path="schoolId" class="pr-24px">
              <NInputNumber
                :value="toNumberValue(model.schoolId)"
                class="w-full"
                clearable
                placeholder="请输入学校ID"
                @update:value="value => (model.schoolId = value)"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="学校地址" label-width="auto" path="address" class="pr-24px">
              <NInput v-model:value="model.address" placeholder="请输入学校地址" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="联系电话" label-width="auto" path="contact" class="pr-24px">
              <NInput v-model:value="model.contact" placeholder="请输入联系电话" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="官网地址" label-width="auto" path="website" class="pr-24px">
              <NInput v-model:value="model.website" placeholder="请输入官网地址" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="院校图标" label-width="auto" path="schoolIcon" class="pr-24px">
              <NInput v-model:value="model.schoolIcon" placeholder="请输入院校图标地址" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="邮编" label-width="auto" path="postcode" class="pr-24px">
              <NInput v-model:value="model.postcode" placeholder="请输入邮编" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="外部学校ID" label-width="auto" path="univId" class="pr-24px">
              <NInputNumber v-model:value="model.univId" class="w-full" clearable placeholder="请输入外部学校ID" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="建校年份" label-width="auto" path="establishYear" class="pr-24px">
              <NInputNumber v-model:value="model.establishYear" class="w-full" clearable placeholder="请输入建校年份" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="占地面积(亩)" label-width="auto" path="campusAreaMu" class="pr-24px">
              <NInputNumber v-model:value="model.campusAreaMu" class="w-full" clearable placeholder="请输入占地面积" />
            </NFormItemGi>
            <NFormItemGi
              span="24 s:12 m:6"
              label="图书馆藏书量"
              label-width="auto"
              path="libraryCollection"
              class="pr-24px"
            >
              <NInputNumber
                v-model:value="model.libraryCollection"
                class="w-full"
                clearable
                placeholder="请输入图书馆藏书量"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="学生人数" label-width="auto" path="studentCount" class="pr-24px">
              <NInputNumber v-model:value="model.studentCount" class="w-full" clearable placeholder="请输入学生人数" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="教师人数" label-width="auto" path="teacherCount" class="pr-24px">
              <NInputNumber v-model:value="model.teacherCount" class="w-full" clearable placeholder="请输入教师人数" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="硕士点数量" label-width="auto" path="masterPoint" class="pr-24px">
              <NInputNumber v-model:value="model.masterPoint" class="w-full" clearable placeholder="请输入硕士点数量" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="博士点数量" label-width="auto" path="doctorPoint" class="pr-24px">
              <NInputNumber v-model:value="model.doctorPoint" class="w-full" clearable placeholder="请输入博士点数量" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="重点专业数" label-width="auto" path="keyMajorCount" class="pr-24px">
              <NInputNumber v-model:value="model.keyMajorCount" class="w-full" clearable placeholder="请输入重点专业数" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="就业率(%)" label-width="auto" path="employmentRate" class="pr-24px">
              <NInputNumber v-model:value="model.employmentRate" class="w-full" clearable placeholder="请输入就业率" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="满意度(%)" label-width="auto" path="satisfactionRate" class="pr-24px">
              <NInputNumber v-model:value="model.satisfactionRate" class="w-full" clearable placeholder="请输入满意度" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="是否985" label-width="auto" path="is985" class="pr-24px">
              <NSelect v-model:value="model.is985" :options="booleanOptions" clearable placeholder="请选择" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="是否211" label-width="auto" path="is211" class="pr-24px">
              <NSelect v-model:value="model.is211" :options="booleanOptions" clearable placeholder="请选择" />
            </NFormItemGi>
            <NFormItemGi
              span="24 s:12 m:6"
              label="是否双一流"
              label-width="auto"
              path="isDoubleFirstClass"
              class="pr-24px"
            >
              <NSelect v-model:value="model.isDoubleFirstClass" :options="booleanOptions" clearable placeholder="请选择" />
            </NFormItemGi>
            <NFormItemGi
              span="24 s:12 m:6"
              label="是否重点大学"
              label-width="auto"
              path="isKeyUniversity"
              class="pr-24px"
            >
              <NSelect v-model:value="model.isKeyUniversity" :options="booleanOptions" clearable placeholder="请选择" />
            </NFormItemGi>
            <NFormItemGi span="24" label="详情标签" label-width="auto" path="tags" class="pr-24px">
              <NSpace vertical class="w-full">
                <NSpace class="w-full" :wrap-item="false">
                  <NInput
                    v-model:value="detailTagInputValue"
                    class="flex-1"
                    placeholder="输入详情标签后回车或点击确认，可用逗号一次输入多个"
                    @keydown.enter.prevent="addDetailTags"
                  />
                  <NButton type="primary" ghost @click="addDetailTags">确认</NButton>
                </NSpace>
                <NDynamicTags v-model:value="detailTagList" />
              </NSpace>
            </NFormItemGi>
            <NFormItemGi :show-feedback="false" span="24" class="pr-24px">
              <NSpace class="w-full" justify="end">
                <NButton @click="reset">
                  <template #icon>
                    <icon-ic-round-refresh class="text-icon" />
                  </template>
                  {{ $t('common.reset') }}
                </NButton>
                <NButton type="primary" ghost @click="search">
                  <template #icon>
                    <icon-ic-round-search class="text-icon" />
                  </template>
                  {{ $t('common.search') }}
                </NButton>
              </NSpace>
            </NFormItemGi>
          </NGrid>
        </NForm>
      </NCollapseItem>
    </NCollapse>
  </NCard>
</template>

<style scoped></style>
