<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    @cancel="resetFields"
    title="新 增"
    @ok="handleOk"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="model" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { saveItemApi } from '/@/api/product/category';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  const schemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: '商品属性',
      colProps: {
        span: 18,
      },
      required: true,
      componentProps: {
        maxLength: 15,
      },
    },
    {
      field: 'sortOrder',
      component: 'InputNumber',
      label: '排序',
      defaultValue: 1,
      rules: [
        {
          required: false,
          // @ts-ignore
          validator: async (rule, value) => {
            if (value && (value < 0 || value > 1000)) {
              return Promise.reject('请输入正确的排序');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      colProps: {
        span: 24,
      },
    },
  ];
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['saveadd'],
    setup(_, context) {
      const modelRef = ref({});
      const { createMessage } = useMessage();
      const { t } = useI18n();
      const [
        registerForm,
        {
          // setFieldsValue,
          validate,
          resetFields,
          // getFieldsValue,
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        console.log('Data Received', data);
        // 方式1;
        // setFieldsValue({
        //   field2: data.data,
        //   field1: data.info,
        // });

        // // 方式2
        modelRef.value = { field2: data.data, field1: data.info };

        // setProps({
        //   model:{ field2: data.data, field1: data.info }
        // })
      }

      async function handleOk() {
        let data = await validate();
        let res = await saveItemApi(data);
        context && context.emit('saveadd', res);
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }

      return { register, resetFields, schemas, registerForm, model: modelRef, handleOk, t };
    },
  });
</script>
