<template>
  <!-- 先注释掉 :showRaw="customSetting.showRaw"-->
  <h-b-form ref="formRef" name="use" :model="data" v-bind="formProps"></h-b-form>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, onMounted, ref, computed, watch } from 'vue';
import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '../../../utils/bus';
import { commonApi } from '@/api/commonApi/index';
import { useI18n } from '@crami/locale';
import { merge } from 'lodash-es';
import encoderRequest, {
  registerEncoderSessionId,
  judgeExistHbEncoder,
} from '@/utils/encoderRequest';
import { useForm, getPlatformConfig } from '@crami/bui-platform';

/**控件对外数据*/
const props = {
  options: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'Create',
  props: props,
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const customSetting = getPlatformConfig().customSetting;
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    // 计算studio是否配置弹窗按钮
    const isStudioButton = computed(() => {
      const paramsKeys = Object.keys(props.componentProps?.params); //取出配置信息key
      return paramsKeys.includes('okText') && paramsKeys.includes('cancelText');
    });

    console.log('props', props.componentProps?.params);
    //暴露出表单页面实例
    const instance = getCurrentInstance();
    instance.appContext.config.globalProperties.$createModel = instance;
    // 第二种方法，useForm调用查询方法

    const [formRef, formProps, formMethods] = useForm(
      {
        configApi: {
          // 测试使用admin接口，后续使用下面的
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...props.componentProps?.params,
            ...commonApi().studioCache.getMetaInfo.params,
            // type:(props.data && props.data.params != undefined) ? props.data.params?.type : 'form_view',
            // type: 'form',
            type: props?.componentProps?.params?.formType
              ? props.componentProps.params.formType
              : 'form',
            productLine:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.project
                : commonApi().studioCache.getMetaInfo.params?.productLine,
            mode: 'add',
            name:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.modelName
                : '',
          },
          method: commonApi().studioCache.getMetaInfo.method,
        },
        saveApi:
          props.componentProps.params.saveDataParams?.saveUrl?.length != 'undefined'
            ? {
                url: props.componentProps?.params?.saveDataParams?.saveUrl,
                method: 'post',
                type: 'json',
              }
            : {},
        // 设置form的各种配置信息
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                // showActionButtonGroup: !isStudioButton.value,
                isQuery: false, // 是否为查询表单
                submitOnReset: false,
                searchConfig: { resetText: '取消' },
                onReset: () => {
                  formMethods.clearValidate();
                  emit('end');
                },
              },
              // column: 2, // 一行展示几个
              isQuery: false,
              model: initData(), // 初始化值以及编辑回填值
              uniqueParams: uniqueParams(),
            };
            formMethods.setProps(_props, props);
            if (updateData.value && updateData.value) {
              updateData.value(props); //提供更新表单数据的方法，这个方法是业务页面穿进来的
            }

            registerEncoderSessionId(formRef);
          }
          return props;
        },
        immediate: true,
        // modelParams: props.componentProps || {},
      },
      undefined,
      emit,
      {
        isAdd: true,
        ...(props.componentProps?.params || {}),
      },
    );

    merge(formProps.submitter, {
      searchConfig: { resetText: t('platform.common.cancel') },
      showActionButtonGroup: !isStudioButton.value,
    });

    const initData = () => {
      return props.componentProps?.params?.setFormItem;
    };

    const uniqueParams = () => {
      return {
        objectType:
          props.componentProps.params != undefined ? props.componentProps.params.modelName : '', //唯一性校验
        NewObject: true, //唯一性校验
        connect: commonParams.value?.connect,
        // type: 'view',
        lang: commonParams.value?.lang,
      };
    };
    const updateData = ref();
    //表单提供更新数据的方法，供业务页面调用，接受的参数是一个方法，业务页面提供
    const handleUpdate = update => {
      updateData.value = update;
    };
    // const onFinish = (values: any) => {
    //   emit('end', values);
    //   console.log('Success:', values);
    // };
    onMounted(() => {
      bus.emit('getInstance', { ref: formRef });
    });

    const ok = async modalRef => {
      // 要求先校验表单再请求编码器更新状态接口
      if (judgeExistHbEncoder(formMethods)) {
        formMethods.validate().then(async () => {
          // 存在编码器组件时执行编码器更新状态接口
          const encoderResult = await encoderRequest(formMethods, 'save');
          encoderResult && formMethods.handleSubmit(modalRef);
        });
      } else {
        formMethods.handleSubmit(modalRef);
      }
    };

    const cancel = () => {
      // 处理编码器
      encoderRequest(formMethods, 'cancel');
      // 关闭弹窗事件
      emit('end', null);
    };

    return {
      FormData,
      formProps,
      formRef,
      handleUpdate,
      formMethods,
      ok,
      cancel,
      customSetting,
    };
  },
});
</script>
