<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicForm @register="registerForm" ref="formRef" :validateTrigger="['blur', 'change']" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { buildUUID } from '/@/utils/uuid';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const formRef = ref();

  const itemTypeNameOptions: LabelValueOptions = [
    {
      label: t('自定义'),
      value: '0',
    },
    {
      label: t('日期'),
      value: '1',
    },
    {
      label: t('流水号'),
      value: '2',
    },
    {
      label: t('部门'),
      value: '3',
    },
    {
      label: t('用户'),
      value: '4',
    },
  ];

  const formatStrOptionsData = {
    '1': [
      { label: 'MMdd', value: '1' },
      { label: 'ddMM', value: '2' },
      { label: 'MMyy', value: '3' },
      { label: 'yyMM', value: '4' },
      { label: 'yyyy', value: '5' },
      { label: 'yy', value: '6' },
      { label: 'yyyyMM', value: '7' },
      { label: 'yyMMdd', value: '8' },
      { label: 'yyyyMMdd', value: '9' },
    ],
    '2': [
      { label: '000', value: '1' },
      { label: '0000', value: '2' },
      { label: '00000', value: '3' },
      { label: '000000', value: '4' },
    ],
    '3': [
      { label: t('部门编号'), value: 'code' },
      { label: t('部门名称'), value: 'name' },
    ],
    '4': [
      { label: t('用户编号'), value: 'code' },
      { label: t('用户名称'), value: 'name' },
    ],
  };

  let itemTypeName = ref('');
  let formatStr = ref('');
  let formatStrOptions: Array<object>;
  const ruleFormSchema: FormSchema[] = [
    {
      field: 'itemType',
      label: t('前缀'),
      component: 'Select',
      required: true,
      colProps: { span: 24 },
      componentProps: ({ formModel, formActionType }) => {
        return {
          options: itemTypeNameOptions,
          allowClear: false,
          onChange: (e: any, option) => {
            itemTypeName.value = option?.label;
            const { updateSchema } = formActionType;
            formModel.formatStr = undefined;
            if (e === '0') {
              updateSchema({
                field: 'formatStr',
                component: 'Input',
                componentProps: () => {
                  return {
                    allowClear: false,
                    onChange: (e: any) => {
                      formatStr.value = e.target.value;
                    },
                  };
                },
              });
            } else {
              formatStrOptions = e ? formatStrOptionsData[e] : [];
              updateSchema({
                field: 'formatStr',
                component: 'Select',
                componentProps: () => {
                  return {
                    allowClear: false,
                    options: formatStrOptions,
                    onChange: (_, option) => {
                      formatStr.value = e === '3' || e === '4' ? option?.value : option?.label;
                    },
                  };
                },
              });
            }
            if (e !== '2') {
              updateSchema({
                field: 'stepValue',
                defaultValue: '',
              });
              updateSchema({
                field: 'initValue',
                defaultValue: '',
              });
              nextTick(() => {
                formRef.value.clearValidate(['stepValue', 'initValue']);
              });
            }
          },
        };
      },
    },
    {
      field: 'formatStr',
      label: t('格式'),
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'stepValue',
      label: t('步长'),
      component: 'InputNumber',
      componentProps: {
        min: 1,
        precision: 0,
        style: { width: '100%' },
        allowClear: false,
      },
      colProps: { span: 24 },
      dynamicDisabled: ({ values }) => {
        return values.itemType !== '2';
      },
      dynamicRules: ({ values }) => {
        return values.itemType === '2' ? [{ required: true, message: t('请输入步长') }] : [];
      },
    },
    {
      field: 'initValue',
      label: t('初始'),
      component: 'Input',
      colProps: { span: 24 },
      componentProps: {
        allowClear: false,
        onChange: (e: any) => {
          e.target.value = e.target.value.replace(/[^\d]/g, '');
        },
      },
      dynamicDisabled: ({ values }) => {
        return values.itemType !== '2';
      },
      dynamicRules: ({ values }) => {
        return values.itemType === '2' ? [{ required: true, message: t('请输入初始') }] : [];
      },
    },
    {
      field: 'description',
      label: t('说明'),
      component: 'Input',
      colProps: { span: 24 },
      componentProps: {
        allowClear: false,
      },
    },
  ];

  const isUpdate = ref(true);
  const rowId = ref('');
  const { notification } = useMessage();

  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    schemas: ruleFormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.key;
      itemTypeName.value = data.record.itemTypeName;
      const val = data.record.itemType;
      formatStr.value = data.record.formatStr;
      if (val !== '0') {
        formatStrOptions = val ? formatStrOptionsData[val] : [];
        updateSchema({
          field: 'formatStr',
          component: 'Select',
          componentProps: () => {
            return {
              options: formatStrOptions,
              onChange: (_, option) => {
                formatStr.value = val === '3' || val === '4' ? option?.value : option?.label;
              },
            };
          },
        });
      } else {
        updateSchema({
          field: 'formatStr',
          component: 'Input',
        });
      }

      setFieldsValue({
        ...data.record,
      });
    } else {
      updateSchema({
        field: 'formatStr',
        component: 'Input',
      });
      rowId.value = buildUUID();
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增') : t('编辑')));

  async function handleSubmit() {
    try {
      const values = await validate();
      if (values.itemType === '2' && !!values.initValue?.toString().length) {
        if (formatStr.value?.length !== values.initValue?.toString().length) {
          notification.warning({
            message: t('提示'),
            description: t(
              '初始值的长度需跟格式保持一致，例如：格式为000，初始值就为001，不能超过长度',
            ),
          });
          return;
        } else if (formatStr.value === values.initValue?.toString()) {
          notification.warning({
            message: t('提示'),
            description: t('初始值不能从零开始'),
          });
          return;
        }
      }
      if (values.itemType === '0') {
        formatStr.value = values.formatStr;
      }
      setModalProps({ confirmLoading: true });
      closeModal();
      emit('success', {
        isUpdate: unref(isUpdate),
        record: {
          ...values,
          itemTypeName: unref(itemTypeName),
          formatStr: unref(formatStr),
          key: rowId.value,
        },
      });
      updateSchema({
        field: 'formatStr',
        component: 'Input',
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
