<template>
  <h-form
    ref="formRef"
    :model="formState"
    :layout="hFormGlobalConfig.layout"
    :labelCol="hFormGlobalConfig.labelCol"
    class="base-form"
  >
    <h-row :gutter="24">
      <h-col :span="12">
        <h-form-item :label="t('code.codeSegment.completeCodeSegment.length')" name="length">
          <h-input
            :disabled="true"
            autocomplete="off"
            :placeholder="t('code.codeSegment.completeCodeSegment.inputPlacehoder')"
            v-model:value="formState.length"
          ></h-input>
        </h-form-item>
      </h-col>
      <h-col :span="12">
        <h-form-item
          :label="t('code.codeSegment.completeCodeSegment.extendedLength')"
          name="extendedLength"
          :rules="[
            {
              message: t('code.codeSegment.completeCodeSegment.extendNumRule'),
              pattern: /^([0-9]|10)$/,
              trigger: 'change',
            },
            {
              message: t('code.codeSegment.completeCodeSegment.extendLenthRule'),
              asyncValidator: extendValidatorEvent,
              trigger: 'change',
              required: true,
            },
          ]"
        >
          <h-input
            :placeholder="t('code.codeSegment.completeCodeSegment.inputPlacehoder')"
            autocomplete="off"
            v-model:value="formState.extendedLength"
            @change="extendChangeEvent"
          ></h-input>
        </h-form-item>
      </h-col>
      <h-col :span="12">
        <h-form-item
          :label="t('code.codeSegment.completeCodeSegment.complementCharacter')"
          name="complementCharacter"
          :rules="[
            {
              message: t('code.codeSegment.completeCodeSegment.complementCharacterRule'),
              asyncValidator: complementValidatorEvent,
              trigger: 'change',
              required: true,
            },
          ]"
        >
          <h-input
            autocomplete="off"
            :placeholder="t('code.codeSegment.completeCodeSegment.inputPlacehoder')"
            v-model:value="formState.complementCharacter"
          ></h-input>
        </h-form-item>
      </h-col>
      <h-col :span="12">
        <h-form-item
          :label="t('code.codeSegment.completeCodeSegment.triggerCode')"
          name="triggerCode"
          :rules="[
            {
              message: t('code.codeSegment.completeCodeSegment.triggerCodeRule'),
              asyncValidator: triggerValidatorEvent,
              trigger: 'change',
              required: true,
            },
          ]"
        >
          <h-input
            :placeholder="t('code.codeSegment.completeCodeSegment.triggerCodePlaceHolder')"
            autocomplete="off"
            v-model:value="formState.triggerCode"
          ></h-input>
        </h-form-item>
      </h-col>
      <h-col :span="24">
        <h-form-item
          :label="t('code.codeSegment.completeCodeSegment.describes')"
          :rules="[
            {
              pattern: /^[\s\S]{0,100}$/,
              message: t('code.codeSegment.segmentTable.completeRule'),
              trigger: 'blur',
            },
          ]"
          name="describes"
        >
          <h-text-area
            :placeholder="t('code.codeSegment.completeCodeSegment.inputPlacehoder')"
            v-model:value="formState.describes"
          ></h-text-area>
        </h-form-item>
      </h-col>
      <h-col :span="24">
        <h-form-item :hidden="true" name="codeComplementId">
          <h-input
            :placeholder="t('code.codeSegment.completeCodeSegment.inputPlacehoder')"
            v-model="formState.codeComplementId"
          ></h-input>
        </h-form-item>
      </h-col>
    </h-row>
    <!-- <h-row>
      <h-col :span="24" style="text-align: right">
        <h-button style="margin: 0 8px" @click="cancelEvent">
          {{ t('code.common.cancel') }}
        </h-button>
        <h-button type="primary" html-type="submit">{{ t('code.common.ok') }}</h-button>
      </h-col>
    </h-row> -->
  </h-form>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref } from 'vue';
import {
  HModal,
  Form as HForm,
  FormItem as HFormItem,
  Row as HRow,
  Col as HCol,
  Input as HInput,
  TextArea as HTextArea,
  Button as HButton,
  message,
} from '@crami/ui';
import { getInfo, ICP_CONFIG, bus } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
import bus from '@/utils/bus'; */
import { useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';
import { hFormGlobalConfig } from '@/settings/config';

/**控件对外数据*/
const formProps = {
  options: {
    type: Object,
  },
  componentProps: {
    type: Object,
  },
};
export default defineComponent({
  name: 'CompleteCodeSegment',
  props: formProps,
  components: {
    HForm,
    HRow,
    HCol,
    HFormItem,
    HInput,
    HTextArea,
    HButton,
  },
  setup: (props: any) => {
    const { t } = useI18n();
    const stateData = props.componentProps.stateData || '^[0-9]{0,100}$';
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const formState = reactive({
      length: 0,
      extendedLength: 0,
      complementCharacter: 0,
      triggerCode: '',
      describes: '',
      codeComplementId: '',
      lengthFineRules: '',
    });
    const formRef = ref();
    Object.assign(formState, stateData);

    const onFinish = () => {
      formRef.value
        .validate()
        .then(res => {
          submitApi(res);
        })
        .catch(err => {
          console.info('---validate', err);
        });
    };

    const submitApi = async (res: any) => {
      const params = {
        codeSegmentId: props.componentProps?.params.objectID,
        codeComplementId: res.codeComplementId,
        extendedLength: res.extendedLength,
        complementCharacter: res.complementCharacter,
        triggerCode: res.triggerCode,
        describes: res.describes,
        newObject: true,
        connect: commonParams.value?.connect,
        lang: commonParams.value?.lang,
        companyId: commonParams.value?.companyId,
        userId: commonParams.value?.user_id,
        lengthFineRules: stateData.lengthFineRules,
        currentLength: res.length,
        timeZone: commonParams.value?.TIME_ZONE,
      };
      const data = await useHttp({
        url: '/api/codemanagement/codeSegment/saveComplement',
        method: 'post',
        params,
      });
      if (data.code === 200) {
        HModal.destroyAll();
        bus.emit('endCodeEvent');
      } else {
        message.error(data.msg);
      }
    };

    const cancelEvent = () => {
      HModal.destroyAll();
    };

    const extendValidatorEvent = (rule, value, callback) => {
      return new Promise((res, reject) => {
        const regular = /^[+]{0,1}(\d+)$/;
        if (!regular.test(value)) {
          rule.message = t('code.codeSegment.completeCodeSegment.extendNumMsg');
          callback(false);
          reject();
        } else if (value <= formState.length) {
          callback(false);
          reject();
        } else {
          res(true);
        }
      });
    };

    const complementValidatorEvent = (rule, value, callback) => {
      return new Promise((res, reject) => {
        if (formState.extendedLength > 10) {
          rule.message = t('code.codeSegment.completeCodeSegment.complementGreaterRule');
          callback(false);
          reject();
          return;
        }
        const item = formState.extendedLength - formState.length;
        if (item <= 0) {
          rule.message = t('code.codeSegment.completeCodeSegment.complementLenthRule');
          callback(false);
          reject();
          return;
        }
        const lengthRule = formState.lengthFineRules || '';
        var a = lengthRule.indexOf('[');
        var b = lengthRule.indexOf(']', a);
        var d = lengthRule.slice(a + 1, b);
        const regular = new RegExp(`^[${d}]{0,100}$`);
        if (!regular.test(value)) {
          rule.message = t('code.codeSegment.completeCodeSegment.complementFineRule');
          callback(false);
          reject();
          return;
        }
        if (value.length !== item) {
          rule.message = t('code.codeSegment.completeCodeSegment.complementDigitRule', {
            item: item,
          });
          callback(false);
          reject();
        } else {
          res(true);
        }
      });
    };

    const triggerValidatorEvent = (rule, value, callback) => {
      return new Promise((res, reject) => {
        const reg = new RegExp(stateData.lengthFineRules);
        if (!reg.test(value)) {
          rule.message = t('code.codeSegment.completeCodeSegment.triggerRule');
          callback(false);
          reject();
        } else {
          res(true);
        }
      });
    };

    const extendChangeEvent = () => {
      formRef.value.validateFields('complementCharacter');
    };

    return {
      t,
      formRef,
      FormData,
      formProps,
      formState,
      onFinish,
      extendValidatorEvent,
      complementValidatorEvent,
      triggerValidatorEvent,
      cancelEvent,
      extendChangeEvent,
      hFormGlobalConfig,
    };
  },
});
</script>
