<template>
  <div v-bind="$attrs">
    <q-field v-model="tree" :label="displayName" labelColor="primary" stack-label >
      <template v-slot:control >
        <q-card flat class="full-width">
          <q-card-actions vertical>
            <q-btn color="grey-3" text-color="black" @click="showDg()">クリックで設定：{{ isSetted?'設定済み':'未設定' }}</q-btn>
          </q-card-actions>
          <q-card-section class="text-caption" >
            <div v-if="!isSetted">{{ placeholder }}</div>
            <div v-else>{{ conditionString }}</div>
          </q-card-section>
        </q-card>
      </template>
    </q-field>
    <condition-editor v-model:show="show" v-model:conditionTree="tree" @closed="onClosed"></condition-editor>
  </div>
</template>

  <script lang="ts">
  import { defineComponent, ref ,watchEffect,computed,reactive} from 'vue';
  import { ConditionTree,GroupNode,ConditionNode,LogicalOperator,Operator } from 'app/src/types/Conditions';
  import ConditionEditor from '../ConditionEditor/ConditionEditor.vue'
  export default defineComponent({
    name: 'FieldInput',
    inheritAttrs:false,
    components: {
      ConditionEditor
    },
    props: {
      displayName:{
        type: String,
        default: '',
      },
      name:{
        type: String,
        default: '',
      },
      placeholder: {
        type: String,
        default: '',
      },
      hint:{
        type: String,
        default: '',
      },
      modelValue: {
        type: String,
        default: null
      },
    },

    setup(props, { emit }) {
      const appDg = ref();
      const show = ref(false);
      const tree = reactive(new ConditionTree());
      if(props.modelValue && props.modelValue!==''){
        tree.fromJson(props.modelValue);
      }else{
        const newNode = new ConditionNode({},Operator.Equal,'',tree.root);
        tree.addNode(tree.root,newNode);
      }

      const isSetted=ref(props.modelValue && props.modelValue!=='');

      const conditionString = computed(()=>{
          return tree.buildConditionString(tree.root);
      });

      const showDg = () => {
        show.value = true;
      };

      const onClosed = (val:string) => {
        if (val == 'OK') {
          const conditionJson = tree.toJson();
          isSetted.value=true;
          emit('update:modelValue', conditionJson);
        }
      };

      watchEffect(() => {
        const conditionJson = tree.toJson();
        emit('update:modelValue', conditionJson);
      });

      return {
        appDg,
        isSetted,
        show,
        showDg,
        onClosed,
        tree,
        conditionString
      };
    }
  });
  </script>
