<template>
  <h-b-form ref="formRef" name="use" :model="data" v-bind="formProps"></h-b-form>
</template>

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

/**控件对外数据*/
const props = {
  options: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'Edit',
  props: props,
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    console.log('props', props.componentProps?.params);
    //暴露出表单页面实例
    const instance = getCurrentInstance();
    instance.appContext.config.globalProperties.$createModel = instance;

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

    // 第二种方法，useForm调用查询方法
    const [formRef, formProps, formMethods] = useForm(
      {
        configApi: {
          // url: '/api/studio-cache/page/getModelEditPage',
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...props.componentProps?.params,
            // type:(props.data && props.data.params != undefined) ? props.data.params?.type : 'form_view',
            ...commonApi().studioCache.getMetaInfo.params,
            // 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: 'edit',
            // modelName:
            //   props.componentProps && props.componentProps.params != undefined
            //     ? props.componentProps.params.modelName
            //     : '',
            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',
              }
            : {},
        dataSourceApi: {
          url: props.componentProps?.params?.queryUrl
            ? props.componentProps?.params?.queryUrl
            : commonApi().system.getObjectDataTestList.url,
          method: commonApi().system.getObjectDataTestList.method,
          params: {
            ...commonApi().system.getObjectDataTestList.params,
            ...(props.componentProps?.params?.getDataParams || {}),
          },
        },
        // 设置form的各种配置信息
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                showActionButtonGroup: !isStudioButton.value,
                //   showActionButtonGroup: true, // 显示按钮组
                //   showAdvancedButton: false, // 显示展开收起按钮
                isQuery: false, // 是否为查询表单
                //   autoSubmitOnEnter: true,
                // alwaysShowLines: 1, //  固定展开的行数
                // autoAdvancedLine: 1, // 默认展开的行数
                submitOnReset: false,
                searchConfig: { resetText: t('platform.common.cancel') },
                onReset: () => {
                  formMethods.clearValidate();
                  emit('end');
                },
              },
              // column: 1, // 一行展示几个
              isQuery: false,
              // model: initFormData,
              labelCol: { span: 12 },
              wrapperCol: { span: 24 },
              layout: 'vertical',
              // model: initData(), //初始化值以及编辑回填值
              uniqueParams: uniqueParams(),
            };
            formMethods.setProps(_props, props);
            if (updateData.value && updateData.value) {
              updateData.value(props); //提供更新表单数据的方法，这个方法是业务页面穿进来的
            }
          }
          return props;
        },

        immediate: true,
        // modelParams: props.componentProps?.params || {},
      },
      undefined,
      emit,
      {
        isAdd: false,
        ...(props.componentProps?.params || {}),
      },
    );
    merge(formProps.submitter, {
      searchConfig: { resetText: t('platform.common.cancel') },
    });
    const updateData = ref();
    //表单提供更新数据的方法，供业务页面调用，接受的参数是一个方法，业务页面提供
    const handleUpdate = update => {
      updateData.value = update;
    };

    const uniqueParams = () => {
      return {
        objectType:
          props.componentProps.params != undefined ? props.componentProps.params.modelName : '', //唯一性校验
        NewObject: false, //唯一性校验
        connect: getInfo(ICP_CONFIG)?.connect,
        // type: 'model',
        lang: getInfo(ICP_CONFIG)?.lang,
      };
    };

    onMounted(() => {
      bus.emit('getInstance', { ref: formRef });
    });

    const ok = () => {
      // hbform 点击确认可以直接调用如下方法，内嵌保存数据处理和弹窗关闭
      // formMethods是调用useForm时定义
      formMethods.handleSubmit();
    };

    const cancel = () => {
      // 处理编码器
      encoderRequest(formMethods);
      // 关闭弹窗事件
      emit('end', null);
    };
    return {
      FormData,
      formProps,
      formRef,
      handleUpdate,
      formMethods,
      ok,
      cancel,
    };
  },
});
</script>
