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

defineOptions({
  name: 'SchoolDormOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Art.SchoolDorm | 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 campusOptions = ref<CommonType.Option<CommonType.IdType>[]>([]);
const campusLoading = ref(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.SchoolDormOperateParams;

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

function createDefaultModel(): Model {
  return {
    dormId: null,
    campusId: null,
    roomSize: null,
    bunkBedDesk: null,
    privateBath: null,
    tags: '',
    description: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'dormId' | 'campusId'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  dormId: createRequiredRule('主键ID不能为空'),
  campusId: createRequiredRule('校区不能为空')
};

async function getCampusOptions() {
  campusLoading.value = true;
  const { data, error } = await fetchGetSchoolCampusList({
    pageNum: 1,
    pageSize: 1000,
    schoolId: props.defaultSchoolId,
    params: {}
  });
  if (!error) {
    campusOptions.value = data.rows.map(item => ({
      value: item.campusId,
      label: item.campusName
    }));
  } else {
    campusOptions.value = [];
  }
  campusLoading.value = false;
}

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

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, jsonClone(props.rowData));
  }
}

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

async function handleSubmit() {
  await validate();

  const { dormId, campusId, roomSize, bunkBedDesk, privateBath, tags, description, remark } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolDorm({
      campusId,
      roomSize,
      bunkBedDesk,
      privateBath,
      tags,
      description,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolDorm({
      dormId,
      campusId,
      roomSize,
      bunkBedDesk,
      privateBath,
      tags,
      description,
      remark
    });
    if (error) return;
  }

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

watch(visible, () => {
  if (visible.value) {
    getCampusOptions();
    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="campusId">
          <NSelect
            v-model:value="model.campusId"
            :loading="campusLoading"
            :options="campusOptions"
            placeholder="请选择校区"
            clearable
            filterable
          />
        </NFormItem>
        <NFormItem label="几人间(4/6/8...)" path="roomSize">
          <NInput v-model:value="model.roomSize" placeholder="请输入几人间(4/6/8...)" />
        </NFormItem>
        <NFormItem label="是否上床下桌(0否1是)" path="bunkBedDesk">
          <NInput v-model:value="model.bunkBedDesk" placeholder="请输入是否上床下桌(0否1是)" />
        </NFormItem>
        <NFormItem label="是否独立卫浴(0否1是)" path="privateBath">
          <NInput v-model:value="model.privateBath" placeholder="请输入是否独立卫浴(0否1是)" />
        </NFormItem>
        <NFormItem label="宿舍标签(冗余文本：空调/热水/洗衣房...)" path="tags">
          <NInput v-model:value="model.tags" placeholder="请输入宿舍标签(冗余文本：空调/热水/洗衣房...)" />
        </NFormItem>
        <NFormItem label="补充说明" path="description">
          <NInput v-model:value="model.description" :rows="3" type="textarea" 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>
