<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';

import type { LicenseApi } from '#/api/license/license';

import { ref } from 'vue';

import { MinusCircleOutlined, PlusOutlined } from '@vben/icons';

import { Textarea } from 'ant-design-vue';

import { $t } from '#/locales';

const props = withDefaults(
  defineProps<{
    availableOptions: Function;
    neCodeList?: LicenseApi.NeCode[];
  }>(),
  {
    neCodeList: () => [{ neList: [], activationCode: '', id: 1, fileUrl: '' }],
  },
);

const emit = defineEmits(['addNeCode', 'removeNeCode']);

const formRef = ref<FormInstance>();
const removeNeCode = (item: LicenseApi.NeCode) => {
  emit('removeNeCode', item);
};
const addNeCode = () => {
  emit('addNeCode');
};

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};

const validate = () => formRef.value?.validate();

defineExpose({
  validate,
});
</script>
<template>
  <a-form ref="formRef" name="dynamic_form_nest_item" :model="props">
    <div
      v-for="(neCode, index) in props.neCodeList"
      :key="neCode.id"
      class="flex w-full gap-1"
    >
      <a-form-item
        :name="['neCodeList', index, 'neList']"
        :rules="{
          required: true,
          message: $t('license.selectNe'),
        }"
      >
        <a-select
          v-model:value="neCode.neList"
          mode="multiple"
          allow-clear
          show-search
          style="width: 100px"
          :options="props.availableOptions(index)"
          :filter-option="filterOption"
          :placeholder="$t('license.selectNe')"
        />
      </a-form-item>
      <a-form-item
        :name="['neCodeList', index, 'activationCode']"
        :rules="{
          required: true,
          message: $t('license.enterCode'),
        }"
        class="flex-1"
      >
        <Textarea
          :placeholder="$t('license.enterCode')"
          allow-clear
          v-model:value="neCode.activationCode"
          :rows="1"
        />
      </a-form-item>
      <a-form-item v-if="props.neCodeList.length > 1">
        <MinusCircleOutlined
          @click="removeNeCode(neCode)"
          class="mt-1 cursor-pointer"
        />
      </a-form-item>
    </div>
    <a-form-item>
      <a-button type="dashed" block @click="addNeCode">
        <PlusOutlined class="mb-1" />
        {{ $t('license.addNe') }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
