<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { jsonClone } from '@sa/utils';
import { fetchGetSchoolCollegeList } from '@/service/api/art/school-college';
import { fetchGetSchoolList } from '@/service/api/art/school';
import { fetchCreateSchoolMajor, fetchUpdateSchoolMajor } from '@/service/api/art/school-major';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'SchoolMajorOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Art.SchoolMajor | null;
  /** the default school id when opened from school list */
  defaultSchoolId?: CommonType.IdType | null;
}

const props = withDefaults(defineProps<Props>(), {
  rowData: null,
  defaultSchoolId: null
});

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

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});
const schoolOptions = ref<CommonType.Option<CommonType.IdType>[]>([]);
const schoolLoading = ref(false);
const collegeOptions = ref<CommonType.Option<CommonType.IdType>[]>([]);
const collegeLoading = ref(false);
const tagInputValue = ref('');
const tagList = ref<string[]>([]);

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

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增学校专业',
    edit: '编辑学校专业'
  };
  return titles[props.operateType];
});

type Model = Api.Art.SchoolMajorOperateParams;

const model = ref<Model>(createDefaultModel());

function createDefaultModel(): Model {
  return {
    majorId: null,
    schoolId: null,
    collegeId: null,
    majorCode: '',
    majorName: '',
    educationLevel: '',
    durationYears: null,
    majorCategory: '',
    degreeType: '',
    introduction: '',
    majorTags: [],
    tags: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'majorId' | 'schoolId' | 'collegeId' | 'majorName'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  majorId: createRequiredRule('主键ID不能为空'),
  schoolId: createRequiredRule('院校不能为空'),
  collegeId: createRequiredRule('学院不能为空'),
  majorName: createRequiredRule('专业名称不能为空')
};

async function getSchoolOptions() {
  schoolLoading.value = true;
  const { data, error } = await fetchGetSchoolList({
    pageNum: 1,
    pageSize: 1000,
    params: {}
  });
  if (!error) {
    schoolOptions.value = data.rows.map(item => ({
      value: item.schoolId,
      label: `${item.mainName || item.shortName || '未命名学校'} (${item.schoolId})`
    }));
  } else {
    schoolOptions.value = [];
  }
  schoolLoading.value = false;
}

async function getCollegeOptions(schoolId?: CommonType.IdType | null) {
  if (!schoolId) {
    collegeOptions.value = [];
    return;
  }
  collegeLoading.value = true;
  const { data, error } = await fetchGetSchoolCollegeList({
    pageNum: 1,
    pageSize: 1000,
    schoolId,
    params: {}
  });
  if (!error) {
    collegeOptions.value = data.rows.map(item => ({
      value: item.collegeId,
      label: item.collegeName
    }));
  } else {
    collegeOptions.value = [];
  }
  collegeLoading.value = false;
}

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 parseTagText(tagText?: string | null) {
  if (!tagText) return [];
  return tagText
    .split(/[,，]/)
    .map(item => item.trim())
    .filter(Boolean);
}

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

function addTag() {
  const values = tagInputValue.value
    .split(/[,，]/)
    .map(item => item.trim())
    .filter(Boolean);
  if (!values.length) return;
  tagList.value = normalizeStringList([...tagList.value, ...values]);
  tagInputValue.value = '';
}

function syncTagsToModel() {
  const normalizedMajorTags = normalizeStringList(tagList.value);
  model.value.majorTags = normalizedMajorTags;
  model.value.tags = normalizedMajorTags.join(',');
}

function handleUpdateModelWhenEdit() {
  model.value = createDefaultModel();
  tagList.value = [];
  tagInputValue.value = '';

  if (props.operateType === 'add' && props.defaultSchoolId !== null) {
    model.value.schoolId = props.defaultSchoolId;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, jsonClone(props.rowData));
    const majorTags = normalizeStringList(model.value.majorTags);
    const legacyTags = parseTagText(model.value.tags);
    tagList.value = majorTags.length ? majorTags : normalizeStringList(legacyTags);
  }

  syncTagsToModel();
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const {
    majorId,
    schoolId,
    collegeId,
    majorCode,
    majorName,
    educationLevel,
    durationYears,
    majorCategory,
    degreeType,
    introduction,
    remark
  } = model.value;
  const majorTags = normalizeStringList(tagList.value);
  const tags = majorTags.join(',');

  // request
  if (props.operateType === 'add') {
    const payload: Api.Art.SchoolMajorOperateParams = {
      schoolId,
      collegeId,
      majorCode,
      majorName,
      educationLevel,
      durationYears,
      majorCategory,
      degreeType,
      introduction,
      majorTags,
      remark,
      tags
    };
    const { error } = await fetchCreateSchoolMajor(payload);
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const payload: Api.Art.SchoolMajorOperateParams = {
      majorId,
      schoolId,
      collegeId,
      majorCode,
      majorName,
      educationLevel,
      durationYears,
      majorCategory,
      degreeType,
      introduction,
      majorTags,
      remark,
      tags
    };
    const { error } = await fetchUpdateSchoolMajor(payload);
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    getSchoolOptions();
    handleUpdateModelWhenEdit();
    getCollegeOptions(model.value.schoolId);
    restoreValidation();
  }
});

watch(
  tagList,
  values => {
    const normalizedValues = normalizeStringList(values);
    if (!isSameStringList(values, normalizedValues)) {
      tagList.value = normalizedValues;
      return;
    }
    syncTagsToModel();
  },
  { deep: true }
);

watch(
  () => model.value.schoolId,
  (schoolId, oldSchoolId) => {
    if (!visible.value || schoolId === oldSchoolId) return;
    if (oldSchoolId !== undefined) {
      model.value.collegeId = null;
    }
    getCollegeOptions(schoolId);
  }
);
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="院校" path="schoolId">
          <NSelect
            v-model:value="model.schoolId"
            :loading="schoolLoading"
            :options="schoolOptions"
            :disabled="props.defaultSchoolId !== null"
            placeholder="请选择院校"
            clearable
            filterable
          />
        </NFormItem>
        <NFormItem label="学院ID" path="collegeId">
          <NSelect
            v-model:value="model.collegeId"
            :loading="collegeLoading"
            :options="collegeOptions"
            placeholder="请选择学院"
            clearable
            filterable
          />
        </NFormItem>
        <NFormItem label="专业编码(可选)" path="majorCode">
          <NInput v-model:value="model.majorCode" placeholder="请输入专业编码(可选)" />
        </NFormItem>
        <NFormItem label="专业名称" path="majorName">
          <NInput v-model:value="model.majorName" placeholder="请输入专业名称" />
        </NFormItem>
        <NFormItem label="学历层次：本科/专科" path="educationLevel">
          <NInput v-model:value="model.educationLevel" placeholder="请输入学历层次：本科/专科" />
        </NFormItem>
        <NFormItem label="学制(3/4/5)" path="durationYears">
          <NInput v-model:value="model.durationYears" placeholder="请输入学制(3/4/5)" />
        </NFormItem>
        <NFormItem label="专业类别：工学/理学/艺术学..." path="majorCategory">
          <NInput v-model:value="model.majorCategory" placeholder="请输入专业类别：工学/理学/艺术学..." />
        </NFormItem>
        <NFormItem label="学位类型：工学学士/理学学士/艺术学学士..." path="degreeType">
          <NSelect
            v-model:value="model.degreeType"
            placeholder="请选择学位类型：工学学士/理学学士/艺术学学士..."
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="专业介绍" path="introduction">
          <NInput v-model:value="model.introduction" :rows="3" type="textarea" placeholder="请输入专业介绍" />
        </NFormItem>
        <NFormItem label="专业标签" path="majorTags">
          <NSpace vertical class="w-full">
            <NSpace class="w-full" :wrap-item="false">
              <NInput
                v-model:value="tagInputValue"
                class="flex-1"
                placeholder="输入标签后回车或点击确认，可用逗号一次输入多个"
                @keydown.enter.prevent="addTag"
              />
              <NButton type="primary" ghost @click="addTag">确认</NButton>
            </NSpace>
            <NDynamicTags v-model:value="tagList" />
          </NSpace>
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="model.remark" :rows="3" type="textarea" placeholder="请输入备注" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
