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

defineOptions({
  name: 'SchoolDetailOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Art.SchoolDetail | 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 { 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.SchoolDetailOperateParams;

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

function createDefaultModel(): Model {
  return {
    detailId: null,
    schoolId: null,
    introduction: '',
    address: '',
    contact: '',
    email: '',
    website: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'detailId' | 'schoolId'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  detailId: createRequiredRule('主键ID不能为空'),
  schoolId: createRequiredRule('关联学校主表ID不能为空')
};

function handleUpdateModelWhenEdit() {
  model.value = createDefaultModel();

  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));
  }
}

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

async function handleSubmit() {
  await validate();

  const { detailId, schoolId, introduction, address, contact, email, website, remark } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolDetail({
      schoolId,
      introduction,
      address,
      contact,
      email,
      website,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolDetail({
      detailId,
      schoolId,
      introduction,
      address,
      contact,
      email,
      website,
      remark
    });
    if (error) return;
  }

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

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</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="关联学校主表ID" path="schoolId">
          <NInput
            v-model:value="model.schoolId"
            :disabled="props.defaultSchoolId !== null"
            placeholder="请输入关联学校主表ID"
          />
        </NFormItem>
        <NFormItem label="学校详细介绍（大文本）" path="introduction">
          <NInput
            v-model:value="model.introduction"
            :rows="3"
            type="textarea"
            placeholder="请输入学校详细介绍（大文本）"
          />
        </NFormItem>
        <NFormItem label="学校地址" path="address">
          <NInput v-model:value="model.address" placeholder="请输入学校地址" />
        </NFormItem>
        <NFormItem label="联系电话" path="contact">
          <NInput v-model:value="model.contact" placeholder="请输入联系电话" />
        </NFormItem>
        <NFormItem label="邮箱" path="email">
          <NInput v-model:value="model.email" placeholder="请输入邮箱" />
        </NFormItem>
        <NFormItem label="官网地址" path="website">
          <NInput v-model:value="model.website" placeholder="请输入官网地址" />
        </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>
