<template>
  <div v-bind="$attrs">
    <q-input :label="displayName" v-model="inputValue" label-color="primary"
    :placeholder="placeholder"
    :rules="rulesExp"
    stack-label>
      <template v-slot:append>
        <q-btn round dense flat icon="add" @click="addButtonEvent()" />
      </template>
    </q-input>
  </div>
</template>

<script lang="ts">
import { defineComponent,ref,watchEffect } from 'vue';
import { useFlowEditorStore } from '../../stores/flowEditor';
import { IKintoneEventGroup,kintoneEvent } from 'src/types/KintoneEvents';

export default defineComponent({
  name: 'EventSetter',
  inheritAttrs:false,
  props: {
    displayName:{
      type: String,
      default: '',
    },
    name:{
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    hint:{
      type: String,
      default: '',
    },
    modelValue: {
      type: String,
      default: '',
    },
    connectProps:{
      type:Object,
      default:undefined
    },
    //例：[val=>!!val ||'入力してください']
    rules: {
      type: String,
      default: undefined
    },
    required:{
      type:Boolean,
      default:false
    },
    requiredMessage: {
      type: String,
      default: ''
    }
  },

  setup(props , { emit }) {
    const inputValue = ref(props.modelValue);
    const store = useFlowEditorStore();
    const customExp = props.rules === undefined ? [] : eval(props.rules);
    const errmsg = props.requiredMessage?props.requiredMessage:`${props.displayName}を入力してください。`;
    const requiredExp = props.required ? [((val: any) => !!val || errmsg)] : [];
    const rulesExp = [...requiredExp, ...customExp];
    const addButtonEvent=()=>{
      const eventId =store.currentFlow?.getRoot()?.name;
      if(eventId===undefined){return;}
      let displayName = inputValue.value;
      if(props.connectProps!==undefined && "displayName" in props.connectProps){
        displayName =props.connectProps["displayName"].props.modelValue;
      }
      const customButtonId=`${eventId}.customButtonClick`;
      const findedEvent = store.eventTree.findEventById(customButtonId);
      if(findedEvent && "events" in findedEvent){
        const customEvents = findedEvent as IKintoneEventGroup;
        const addEventId = customButtonId+"." + inputValue.value;
        if(store.eventTree.findEventById(addEventId)){
          return;
        }
        customEvents.events.push({
          eventId: addEventId,
          label: displayName,
          parentId: customButtonId,
          header: 'DELETABLE'
        });
      }
    }
    watchEffect(() => {
      emit('update:modelValue', inputValue.value);
    });

    return {
      inputValue,
      addButtonEvent,
      rulesExp
    };
  },
});
</script>
