<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 { BForm as HBForm } from '@crami/bui';
import { HModal, message } from '@crami/ui';
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

/**控件对外数据*/
const formProps = {
  options: {
    type: Object,
  },
  data: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'EditCodeValue',
  props: formProps,
  components: {
    HBForm,
  },
  setup: (props: any, { emit }) => {
    const { t } = useI18n();
    const codeTitle =
      props?.componentProps?.params?.ruleTitle || t('code.codeValue.createOrEdit.codeTitle');
    const ruleErrorTip =
      props?.componentProps?.params?.ruleErrorTip || props?.componentProps?.params?.ruleTitle || '';
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const pItem = {
      pname: props.componentProps?.params.objectID.PNAME,
      pid: props.componentProps?.params.objectID.PID,
    };
    const [formRef, formProps, formMethods] = useForm(
      {
        isAutoSave: 'false',
        immediate: true,
        configApi: {
          // 测试使用admin接口，后续使用下面的
          url: commonApi().studioCache.getMetaInfo.url,
          params: {
            ...commonApi().studioCache.getMetaInfo.params,
            type: 'form',
            productLine:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.project
                : '',
            mode: 'edit',
            name:
              props.componentProps && props.componentProps.params != undefined
                ? props.componentProps.params.modelName
                : '',
          },
          method: 'post',
        },
        dataSourceApi: {
          url: commonApi().system.getObjectDataTestList.url,
          method: commonApi().system.getObjectDataTestList.method,
          params: {
            ...commonApi().system.getObjectDataTestList.params,
            objectID: props.componentProps?.params?.objectID?.EID || '',
            userId: commonParams.value.user_id,
          },
        },
        // 设置form的各种配置信息
        beforeSetData: (type, prop) => {
          if (type === 'data') {
            model['CODE_VALUE'] = prop.CODE_VALUE;
            model['DESCRIBES'] = prop.DESCRIBES;
          }
          if (type === 'config') {
            const _props: any = {
              // column: 2, // 一行展示几个
              isQuery: false,
              labelCol: { span: 10 },
              uniqueParams: uniqueParams(),
              submitter: {
                showActionButtonGroup: false,
                isQuery: false,
              },
            };
            formMethods.setProps(_props, prop);
            formMethods.updateSchema(
              [
                {
                  dataIndex: 'CODE_VALUE',
                  title: codeTitle,
                  disabled: props.componentProps?.params?.enableEdit,
                  fieldProps: {},
                  locale: '',
                  formItemProps: {
                    title: codeTitle,
                    labelWidth: '100%',
                    rules: [
                      {
                        locale: '',
                        message: ruleErrorTip,
                        pattern: props?.componentProps?.params?.rule,
                        trigger: 'change',
                        required: true,
                      },
                    ],
                  },
                },
                {
                  dataIndex: 'DESCRIBES',
                  fieldProps: {},
                  formItemProps: {},
                },
              ],
              prop,
            );
          }

          return prop;
        },
      },
      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: false, //唯一性校验
        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 params = {
        codeSegmentId: props.componentProps?.params.codeSegmentId,
        pid: pItem.pid,
        parentName: pItem.pname,
        codeValueId: props.componentProps?.params.objectID.EID,
        codeValue: res.CODE_VALUE,
        describes: res.DESCRIBES,
        connect: commonParams.value?.connect,
        lang: commonParams.value?.lang,
        companyId: commonParams.value?.companyId,
        userId: commonParams.value.user_id,
        timeZone: commonParams.value?.TIME_ZONE,
      };
      const data = await useHttp({
        url: '/api/codemanagement/codeValue/addCodeValue',
        method: 'post',
        params,
      });
      if (data.code === 200) {
        HModal.destroyAll();
        bus.emit('endCodeEvent');
        message.success(data.msg);
      } 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>
