<template>
  <n-modal v-model:show="modalVisible" preset="card" :title="title" class="w-700px">
    <n-form ref="formRef" label-placement="left" :label-width="80" :model="formModel" :rules="rules">
      <n-grid :cols="48" :x-gap="18">
        <n-form-item-grid-item :span="25" label="指标名称" path="name">
          <n-input v-model:value="formModel.name" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="25" label="分类ID" path="category_id">
          <n-input-number v-model:value="formModel.category_id" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="25" label="是否展示" path="is_show">
          <n-select v-model:value="formModel.is_show" :options="IndicatorsOptions" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="25" label="指标描述" path="description">
          <n-input v-model:value="formModel.description" type="textarea" placeholder="请输入指标描述" />
        </n-form-item-grid-item>
      </n-grid>
      <n-space class="w-full pt-16px" :size="24" justify="end">
        <n-button class="w-72px" @click="closeModal">取消</n-button>
        <n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
      </n-space>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue';
import type { FormInst, FormItemRule } from 'naive-ui';
import { IndicatorsOptions } from '@/constants';
import { createRequiredFormRule } from '@/utils';
import { fetchIndicatorsAdd, fetchIndicatorsEdit } from '@/service/api/event';

export interface Props {
  /** 弹窗可见性 */
  visible: boolean;
  /**
   * 弹窗类型
   * add: 新增
   * edit: 编辑
   */
  type?: 'add' | 'edit';
  /** 编辑的表格行数据 */
  editData?: BackgroundField.Field | null;
}

export type ModalType = NonNullable<Props['type']>;

defineOptions({ name: 'TableActionModal' });

const props = withDefaults(defineProps<Props>(), {
  type: 'add',
  editData: null
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const emit = defineEmits<Emits>();

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});
const closeModal = () => {
  modalVisible.value = false;
};
const titles: Record<ModalType, string> = {
  add: '添加字段',
  edit: '编辑字段'
};

const title = computed(() => {
  return titles[props.type];
});

const formRef = ref<HTMLElement & FormInst>();

type FormModel = Pick<
  ApiBackground.Indicators,
  'id' | 'name' | 'category_id' | 'particle_size' | 'is_show' | 'description'
>;

const formModel = reactive<FormModel>(createDefaultFormModel());

const rules: Record<keyof FormModel, FormItemRule | FormItemRule[]> = {
  name: createRequiredFormRule('请输入指标字段名'),
  particle_size: createRequiredFormRule('请选择指标颗粒度'),
  category_id: createRequiredFormRule('请选择分类id'),
  description: createRequiredFormRule('请输入字段描述'),
  is_show: createRequiredFormRule(),
  id: createRequiredFormRule()
};

function createDefaultFormModel(): FormModel {
  return {
    id: 0,
    name: '',
    particle_size: null,
    category_id: null,
    is_show: null,
    description: ''
  };
}

function handleUpdateFormModel(model: Partial<FormModel>) {
  Object.assign(formModel, model);
}

function handleUpdateFormModelByModalType() {
  const handlers: Record<ModalType, () => void> = {
    add: () => {
      const defaultFormModel = createDefaultFormModel();
      handleUpdateFormModel(defaultFormModel);
    },
    edit: () => {
      if (props.editData) {
        handleUpdateFormModel(props.editData);
      }
    }
  };

  handlers[props.type]();
}

async function handleSubmit() {
  formRef.value?.validate();
  const params: Array<ApiBackground.Indicators> = [formModel];

  if (props.type === 'add') {
    const data = fetchIndicatorsAdd(params);
    data.then(res => {
      if (res.data) {
        window.$message?.success(`${titles[props.type]}成功！`);
      }
    });
  }

  if (props.type === 'edit') {
    const data = fetchIndicatorsEdit(formModel);
    data.then(res => {
      if (res.data) {
        window.$message?.success(`${titles[props.type]}成功！`);
      }
    });
  }
  closeModal();
}

watch(
  () => props.visible,
  newValue => {
    if (newValue) {
      handleUpdateFormModelByModalType();
    }
  }
);
</script>

<style scoped></style>
