<script setup lang="ts">
import type { PropType } from 'vue';

import { reactive, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVModel } from '@vueuse/core';
import { Input } from 'ant-design-vue';

import { Icon } from '#/components/icon';

import InputCode from './input-code/input-code-modal-ignore.vue';

const props = defineProps({
  value: {
    type: [String, Object, Array] as PropType<
      any[] | Record<string, any> | string
    >,
    default: undefined,
  },
});
const emit = defineEmits(['update:value']);
const modelValue = useVModel(props, 'value', emit, {
  defaultValue: props.value,
  passive: true,
});

const state = reactive({
  value: '',
});

const [InputCodeModal, inputCodeApi] = useVbenModal({
  connectedComponent: InputCode,
});

watch(
  () => props.value,
  () => {
    if (props.value) {
      state.value = '已配置';
    }
  },
  { deep: true },
);

const handleSuccess = (scriptCode: any) => {
  if (modelValue.value !== scriptCode) {
    emit('update:value', scriptCode);
  }
};

const handleInput = () => {
  inputCodeApi.setData({
    baseData: {
      scriptCode: modelValue.value,
      name: '验证规则',
      // language: 'javascript',
    },
  });
  inputCodeApi.open();
};
</script>

<template>
  <div class="w-full">
    <InputCodeModal :close-on-click-modal="false" @success="handleSuccess" />
    <Input v-model:value="state.value" class="w-full">
      <template #addonAfter>
        <Icon icon="proicons:nodejs" @click="handleInput" />
      </template>
    </Input>
  </div>
</template>
