<template>
  <!-- <div class="q-pa-md q-gutter-sm"> -->
  <q-tree :nodes="store.eventTree.screens" node-key="eventId" children-key="events" no-connectors
    v-model:expanded="store.expandedScreen" :dense="true" :ref="tree">
    <template v-slot:header-EVENT="prop">
      <div :ref="prop.node.eventId" class="row col items-center no-wrap event-node" @click="onSelected(prop.node)">
        <q-icon v-if="prop.node.eventId" name="play_circle" :color="prop.node.hasFlow ? 'green' : 'grey'" size="16px"
          class="q-mr-sm">
        </q-icon>
        <div class="no-wrap" :class="getSelectedClass(prop.node)">{{ prop.node.label }}</div>
        <q-space></q-space>
        <!-- <q-icon v-if="prop.node.hasFlow" name="delete" color="negative" size="16px" class="q-mr-sm"></q-icon> -->
      </div>
    </template>
    <template v-slot:header-CHANGE="prop">
      <div class="row col items-start no-wrap event-node">
        <div class="no-wrap" :class="getSelectedClass(prop.node)">{{ prop.node.label }}</div>
        <q-space></q-space>
        <q-icon name="add_circle" color="primary" size="16px" class="q-mr-sm"
          @click="addChangeEvent(prop.node)"></q-icon>
      </div>
    </template>
    <template v-slot:header-DELETABLE="prop">
      <div class="row col items-start event-node" @click="onSelected(prop.node)">
          <q-icon v-if="prop.node.eventId" name="play_circle" :color="prop.node.hasFlow ? 'green' : 'grey'" size="16px" class="q-mr-sm" />
          <div class="no-wrap" :class="getSelectedClass(prop.node)">{{ prop.node.label }}</div>
          <q-space></q-space>
          <q-icon  name="delete_forever"  color="negative" size="16px" @click="deleteEvent(prop.node)"></q-icon>
      </div>
    </template>
  </q-tree>
  <show-dialog v-model:visible="showDialog" name="フィールド選択" @close="closeDg">
    <field-select ref="appDg" name="フィールド" type="single" :fieldTypes="fieldTypes" :appId="store.appInfo?.appId"></field-select>
  </show-dialog>
</template>

<script lang="ts">
import { QTree, useQuasar } from 'quasar';
import { ActionFlow, RootAction } from 'src/types/ActionTypes';
import { useFlowEditorStore } from 'stores/flowEditor';
import { defineComponent, ref, watchEffect } from 'vue';
import { IKintoneEvent, IKintoneEventGroup, IKintoneEventNode, kintoneEvent } from '../../types/KintoneEvents';
import FieldSelect from '../FieldSelect.vue';
import ShowDialog from '../ShowDialog.vue';
export default defineComponent({
  name: 'EventTree',
  components: {
    ShowDialog,
    FieldSelect,
  },
  setup(props, context) {
    const $q = useQuasar();
    const appDg = ref();
    const store = useFlowEditorStore();
    const showDialog = ref(false);
    const tree = ref<QTree>();
    const fieldTypes=[
    'RADIO_BUTTON',
    'DROP_DOWN',
    'CHECK_BOX',
    'MULTI_SELECT',
    'USER_SELECT',
    'GROUP_SELECT',
    'ORGANIZATION_SELECT',
    'DATE',
    'DATETIME',
    'TIME',
    'SINGLE_LINE_TEXT',
    'NUMBER'];
    // const eventTree=ref(kintoneEvents);
    // const selectedFlow = store.currentFlow;

    // const expanded=ref();
    const selectedEvent = ref<IKintoneEvent | undefined>(store.selectedEvent);
    const selectedChangeEvent = ref<IKintoneEventGroup | undefined>(undefined);
    const isFieldChange = (node: IKintoneEventNode) => {
      return node.header == 'EVENT' && node.eventId.indexOf('.change.') > -1;
    }

    const getSelectedClass = (node: IKintoneEventNode) => {
      return store.selectedEvent && node.eventId === store.selectedEvent.eventId ? 'selected-node' : '';
    };

    //フィールド値変更イベント追加
    const closeDg = (val: string) => {
      if (val == 'OK') {
        if (!selectedChangeEvent.value) { return; }
        const field = appDg.value.selected[0];
        const eventid = `${selectedChangeEvent.value.eventId}.${field.code}`;
        if (store.eventTree.findEventById(eventid)) {
          return;
        }
        selectedChangeEvent.value?.events.push(new kintoneEvent(
           field.name,
           eventid,
           selectedChangeEvent.value.eventId,
          'DELETABLE'
        ));
        tree.value?.expanded?.push(selectedChangeEvent.value.eventId);
        tree.value?.expandAll();
      }
    };
    const addChangeEvent = (node: IKintoneEventGroup) => {
      if (store.appInfo === undefined) {
        return;
      }
      selectedChangeEvent.value = node;
      showDialog.value = true;
    }

    const deleteEvent = (node: IKintoneEvent) => {
      if (!node.eventId) {
        return;
      }
      store.deleteEvent(node);
      store.selectFlow(undefined)

      $q.notify({
        type: 'positive',
        caption: '通知',
        message: `イベント ${node.label} 削除`
      })
    }

    const onSelected = (node: IKintoneEvent) => {
      if (!node.eventId) {
        return;
      }
      selectedEvent.value = node;
      if (store.appInfo === undefined) {
        return;
      }
      const screen = store.eventTree.findEventById(node.parentId);

      let flow = store.findFlowByEventId(node.eventId);
      let screenName = screen !== null ? screen.label : '';
      let nodeLabel = node.label;
      // if(isFieldChange(node)){
      //   screenName=nodeLabel;
      //   nodeLabel=`${node.label}の値を変更したとき`;
      // }

      if (flow !== undefined && flow !== null) {
        store.selectFlow(flow);
      } else {
        const root = new RootAction(node.eventId, screenName, nodeLabel)
        const flow = new ActionFlow(root);
        store.flows?.push(flow);
        store.selectFlow(flow);
        selectedEvent.value.flowData = flow;
      }
    };
    watchEffect(()=>{
       store.setCurrentEvent(selectedEvent.value);
    });
    return {
      // eventTree,
      // expanded,
      appDg,
      tree,
      showDialog,
      isFieldChange,
      getSelectedClass,
      onSelected,
      selectedEvent,
      addChangeEvent,
      deleteEvent,
      closeDg,
      store,
      fieldTypes
    }
  }
});
</script>
<style lang="scss">
.nowrap {
  flex-wrap: nowarp;
  text-wrap: nowarp;
}

.event-node {
  cursor: pointer;
}

.selected-node {
  color: $primary;
  font-weight: bolder;
}

.event-node:hover {
  background-color: $light-blue-1;
}

.delete-btn {
  margin-right: 5px;
}
</style>
