<script setup lang="ts">
import { computed } from 'vue';
import { RDMS_OBJECT_DIRECTION_DICT_CODE } from '@/constants/dict';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessUserPicker from '@/components/custom/business-user-picker.vue';
import DictSelect from '@/components/custom/dict-select.vue';

defineOptions({ name: 'ProductCreateBaseForm' });

export interface ProductCreateBaseForm {
  code: string;
  name: string;
  directionCode: string;
  managerUserId: string | null;
  description: string;
}

interface Props {
  managerUserOptions: Api.SystemManage.UserSimple[];
}

defineProps<Props>();

const model = defineModel<ProductCreateBaseForm>('modelValue', { required: true });

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

const rules = computed(
  () =>
    ({
      name: [createRequiredRule('请输入产品名称')],
      directionCode: [createRequiredRule('请选择产品方向')],
      managerUserId: [createRequiredRule('请选择产品经理')]
    }) satisfies Record<string, App.Global.FormRule[]>
);

async function runValidate(): Promise<boolean> {
  try {
    await validate();
    return true;
  } catch {
    return false;
  }
}

defineExpose({ validate: runValidate });
</script>

<template>
  <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
    <ElRow :gutter="16">
      <ElCol :span="12">
        <ElFormItem label="产品名称" prop="name">
          <ElInput v-model="model.name" clearable maxlength="128" placeholder="请输入产品名称" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="12">
        <ElFormItem label="产品编码" prop="code">
          <ElInput v-model="model.code" clearable placeholder="不填则由后端自动生成" />
        </ElFormItem>
      </ElCol>
      <ElCol :span="12">
        <ElFormItem label="产品方向" prop="directionCode">
          <DictSelect
            v-model="model.directionCode"
            :dict-code="RDMS_OBJECT_DIRECTION_DICT_CODE"
            filterable
            placeholder="请选择产品方向"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :span="12">
        <ElFormItem label="产品经理" prop="managerUserId">
          <BusinessUserPicker
            v-model="model.managerUserId"
            :user-options="managerUserOptions"
            title="选择产品经理"
            placeholder="请选择产品经理"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :span="24">
        <ElFormItem label="产品描述" prop="description">
          <ElInput
            v-model="model.description"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入产品描述"
          />
        </ElFormItem>
      </ElCol>
    </ElRow>
  </ElForm>
</template>
