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

defineOptions({
  name: 'SchoolMediaOperateDrawer'
});

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

const props = withDefaults(defineProps<Props>(), {
  rowData: null,
  defaultBizType: null,
  defaultBizId: 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.SchoolMediaOperateParams;

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

function createDefaultModel(): Model {
  return {
    mediaId: null,
    bizType: '',
    bizId: null,
    mediaType: null,
    url: '',
    coverUrl: '',
    sortNo: null,
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'mediaId' | 'bizType' | 'bizId' | 'mediaType' | 'url'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  mediaId: createRequiredRule('主键ID不能为空'),
  bizType: createRequiredRule('业务类型：school/campus/college/major/dorm不能为空'),
  bizId: createRequiredRule('业务主键ID不能为空'),
  mediaType: createRequiredRule('媒体类型：1-图片 2-视频不能为空'),
  url: createRequiredRule('资源URL不能为空')
};

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

  if (props.operateType === 'add') {
    if (props.defaultBizType !== null) {
      model.value.bizType = props.defaultBizType;
    }
    if (props.defaultBizId !== null) {
      model.value.bizId = props.defaultBizId;
    }
  }

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

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

async function handleSubmit() {
  await validate();

  const { mediaId, bizType, bizId, mediaType, url, coverUrl, sortNo, remark } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolMedia({ bizType, bizId, mediaType, url, coverUrl, sortNo, remark });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolMedia({
      mediaId,
      bizType,
      bizId,
      mediaType,
      url,
      coverUrl,
      sortNo,
      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="业务类型：school/campus/college/major/dorm" path="bizType">
          <NSelect
            v-model:value="model.bizType"
            :disabled="props.defaultBizType !== null"
            placeholder="请选择业务类型：school/campus/college/major/dorm"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="业务主键ID" path="bizId">
          <NInput v-model:value="model.bizId" :disabled="props.defaultBizId !== null" placeholder="请输入业务主键ID" />
        </NFormItem>
        <NFormItem label="媒体类型：1-图片 2-视频" path="mediaType">
          <NSelect
            v-model:value="model.mediaType"
            placeholder="请选择媒体类型：1-图片 2-视频"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="资源URL" path="url">
          <NInput v-model:value="model.url" :rows="3" type="textarea" placeholder="请输入资源URL" />
        </NFormItem>
        <NFormItem label="封面URL(视频可用)" path="coverUrl">
          <NInput v-model:value="model.coverUrl" :rows="3" type="textarea" placeholder="请输入封面URL(视频可用)" />
        </NFormItem>
        <NFormItem label="排序" path="sortNo">
          <NInput v-model:value="model.sortNo" 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>
