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

<script lang="ts">
import { computed, defineComponent, reactive } from 'vue';
import { useForm } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { HModal } from '@crami/ui';
import { BForm as HBForm } from '@crami/bui';
import { useHttp } from '@crami/http';
import { message } from 'ant-design-vue';
import { useI18n } from '@crami/locale';

/**控件对外数据*/
const formProps = {
  options: {
    type: Object,
  },
  data: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'SaveCodePrograme',
  props: formProps,
  components: {
    HBForm,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    // 第二种方法，useForm调用查询方法
    const [formRef, formProps, formMethods] = useForm(
      {
        isAutoSave: 'false',
        immediate: true,
        // 设置form的各种配置信息
        beforeSetData: (type, prop) => {
          if (type === 'data') {
            model['ENAME'] =
              props.componentProps.params.EID.ENAME +
              t('code.codeProgramme.saveCodePrograme.ename');
          }
          if (type === 'config') {
            const _props: any = {
              // column: 2, // 一行展示几个
              isQuery: false,
              uniqueParams: uniqueParams(),
              submitter: {
                showResetButton: false,
                showSubmitButton: false,
                showAdvancedButton: false,
                showActionButtonGroup: false,
                isQuery: false,
              },
            };
            formMethods.setProps(_props, prop);
            formMethods.updateSchema(
              [
                {
                  dataIndex: 'ENAME',
                  title: t('code.codeProgramme.saveCodePrograme.enameTitle'),
                  fieldProps: {},
                  width: '100%',
                  formItemProps: {
                    rules: [
                      {
                        pattern: /^([\s\S]{0,200})?$/,
                        message: t('code.codeProgramme.saveCodePrograme.enameLengthRule'),
                        trigger: 'change',
                      },
                      {
                        required: true,
                        pattern: /^\s*(\S+\s*)+/,
                        message: t('code.codeProgramme.saveCodePrograme.enameHasRule'),
                        trigger: 'change',
                      },
                    ],
                  },
                },
              ],
              prop,
            );
          }
          return prop;
        },
        onApiFinish: () => {
          // 刚打开弹窗就进行校验，处理另存为时编码方案名称未修改就是错误的情况
          formMethods.validate();
        },
      },
      undefined,
      emit,
      {
        isAdd: true,
        ...(props.componentProps?.params || {}),
      },
    );
    const submitter = reactive({
      isQuery: false, // 是否为查询表单
      submitOnReset: false,
      searchConfig: { resetText: t('code.common.cancel') },
      onReset: () => {
        formMethods.clearValidate();
        HModal.destroyAll();
      },
    });
    formProps.submitter = submitter;

    const model = reactive({}); // 初始化值以及编辑回填值

    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 onFinish = () => {
      formMethods
        .validate()
        .then(res => {
          submitApi(res);
        })
        .catch(err => {
          console.info('---validate', err);
        });
    };
    const submitApi = async (res: any) => {
      const data = await useHttp({
        url: '/api/codemanagement/codeManagement/saveAsCodeScheme',
        method: 'post',
        params: {
          objectId: props.componentProps?.params.EID.EID,
          codeSchemeName: res.ENAME,
          connect: commonParams.value?.connect,
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          userId: commonParams.value.user_id,
          userGroup: commonParams.value?.userGroup,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (data.code === 200) {
        message.success(data.msg);
        HModal.destroyAll();
        bus.emit('endCodeEvent');
      } else {
        message.error(data.msg);
      }
    };
    return {
      t,
      formRef,
      formProps,
      model,
      onFinish,
    };
  },
});
</script>
<style lang="less" scoped>
:deep(.ant-form-vertical .ant-col) {
  margin-left: 0 !important;
}
</style>
