<template>
  <div class="q-pa-md">
    <q-table flat bordered row-key="id" :selection="type" :selected="modelValue" :filter="filter"
      @update:selected="$emit('update:modelValue', $event)" :columns="columns" :rows="rows" />
  </div>
</template>
<script lang="ts">
import { PropType, reactive } from 'vue';
import { IActionVariable } from '../types/ActionTypes';
import { v4 as uuidv4 } from 'uuid';

export default {
  name: 'VariableList',
  props: {
    name: String,
    type: String,
    vars: {
      type: Array as PropType<IActionVariable[]>,
      reqired: true,
      default: () => []
    },
    modelValue: Array,
    filter: String
  },
  emits: [
    'update:modelValue'
  ],
  setup(props) {
    const variableName = (field) => {
      const name = field.name;
      return name.name;
    }
    const columns = [
      { name: 'actionName', label: 'アクション名', align: 'left', field: 'actionName', sortable: true },
      { name: 'displayName', label: '変数表示名', align: 'left', field: 'displayName', sortable: true },
      { name: 'name', label: '変数名', align: 'left', field: variableName, required: true, sortable: true }
    ];

    const rows = props.vars.flatMap((v) => {
      if (v.name.vars && v.name.vars.length > 0) {
        return v.name.vars
          .filter(o => o.vName && o.logicalOperator && o.field)
          .map(o => ({
            id: uuidv4(),
            objectType: 'variable',
            name: { name: `${v.name.name}.${o.vName}` },
            actionName: v.name.actionName,
            displayName: v.name.displayName
          }));
      } else {
        return [{ objectType: 'variable', ...v }];
      }
    });

    return {
      columns,
      rows: reactive(rows)
    }
  }
}
</script>
