<template>
  <div class="pr-1" style="height: 100%">
    <w-grid
      ref="treeGridRef"
      :title="$t('re.lib.grid.title')"
      dense-body
      db-click-operation="edit"
      :config-button="true"
      :checkbox-selection="false"
      :tree="true"
      :tree-icon="
        (row: any) => {
          if (row.type === 'FOLDER') {
            return { name: 'folder', color: 'amber' };
          } else {
            return { name: 'bi-card-list' };
          }
        }
      "
      :data-url="Environment.apiContextPath('/api/re/lib')"
      :sort-by="['type', 'namec', '-version']"
      :pageable="false"
      :toolbar-configure="{ noIcon: false }"
      :toolbar-actions="[
        'refresh',
        'separator',
        'expand',
        [
          {
            name: 'addGroup',
            label: $t('re.lib.grid.toolbar.addGroup'),
            icon: 'add',
            click: undefined,
          },
          {
            extend: 'addTop',
            name: 'addTop',
            label: $t('re.lib.grid.toolbar.addTop'),
            afterClick: (args: any) => {
              args.grid.getEditorForm().setFieldValue('type', 'FOLDER');
            },
          },
          {
            extend: 'addChild',
            name: 'addChild',
            label: $t('re.lib.grid.toolbar.addChild'),
            enableIf: (args: any) => {
              return args.selected && args.selected.type === 'FOLDER';
            },
            afterClick: (args: any) => {
              args.grid.getEditorForm().setFieldValue('type', 'FOLDER');
            },
          },
          'separator',
          {
            name: 'addLib',
            extend: 'addChild',
            label: $t('re.lib.grid.toolbar.addLib'),
            icon: 'bi-card-list',
            enableIf: (args: any) => {
              return args.selected && args.selected.type === 'FOLDER';
            },
            afterClick: (args: any) => {
              args.grid.getEditorForm().setFieldValue('type', 'INDICATOR');
            },
          },
          'separator',
          'clone',
          {
            extend: 'deepClone',
            name: 'deepClone',
            label: $t('re.lib.grid.toolbar.deepClone'),
            icon: 'bi-copy',
            enableIf: (args: any) => {
              return args.selected && args.selected.type !== 'FOLDER';
            },
            click: (args: any) => {
              DialogManager.confirm($t('re.lib.grid.toolbar.deepClone.tip'), () => {
                axios.post(Environment.apiContextPath('/api/re/lib/deepClone/' + args.selected.id)).then(() => {
                  treeGridRef.refresh();
                });
              });
            },
          },
          {
            extend: 'clone',
            name: 'deepCloneNew',
            label: $t('re.lib.grid.toolbar.deepCloneNew'),
            icon: 'bi-copy',
            enableIf: (args: any) => {
              return args.selected && args.selected.type !== 'FOLDER';
            },
            click: (args: any) => {
              DialogManager.confirm($t('re.lib.grid.toolbar.deepCloneNew.tip'), () => {
                axios.post(Environment.apiContextPath('/api/re/lib/deepCloneNew/' + args.selected.id)).then(() => {
                  treeGridRef.refresh();
                });
              });
            },
          },
        ],
        'separator',
        'edit',
        'remove',
        'separator',
        {
          name: 'generateGroovySourceCode',
          label: $t('re.lib.grid.toolbar.generateGroovySourceCode'),
          icon: 'bi-code',
          enableIf: (args: any) => {
            return args.selected && args.selected.type === 'INDICATOR';
          },
          click: (args: any) => {
            sourceCodeDialogRef.open();
          },
        },
        'separator',
        {
          name: 'deploy',
          label: $t('re.lib.grid.toolbar.deploy'),
          icon: 'bi-balloon',
          enableIf: (args: any) => {
            return args.selected && args.selected.type !== 'FOLDER' && args.selected.status === 'SKETCH';
          },
          click: (args: any) => {
            DialogManager.confirm($t('re.lib.grid.toolbar.deploy.tip'), () => {
              axios.post(Environment.apiContextPath('/api/re/lib/deploy/' + args.selected.id)).then((response) => {
                treeGridRef.refresh();
              });
            });
          },
        },
        'separator',
        [
          {
            name: 'importGroup',
            label: $t('re.lib.grid.toolbar.importGroup'),
            icon: 'file_upload',
            click: undefined,
          },
          {
            name: 'import',
            label: $t('re.lib.grid.toolbar.import'),
            icon: 'file_upload',
            click: (args: any) => {
              importDialogRef.open();
            },
          },
          {
            name: 'importSample',
            label: $t('re.lib.grid.toolbar.importSample'),
            icon: 'bi-database-up',
            click: (args: any) => {
              importSampleDialogRef.open();
            },
          },
        ],
        'separator',
        'view',
        {
          name: 'viewBloodRelationship',
          label: $t('re.resources.grid.toolbar.viewBloodRelationship'),
          icon: 'hub',
          enableIf: (args: any) => {
            return args.selected && args.selected.type !== 'FOLDER';
          },
          click: (args: any) => {
            bloodRelationshipDialogRef.open();
          },
        },
        'separator',
        {
          extend: 'export',
          enableIf: (args: any) => {
            return args.selected;
          },
          click: (args: any) => {
            Downloader.get(Environment.apiContextPath('/api/re/lib/export/' + args.selected.id), { loading: true });
          },
        },
      ]"
      :columns="[
        {
          width: '100%',
          name: 'namec',
          label: $t('name'),
          format: (value: any, row: any) => {
            return row.name;
          },
        },
        { width: 135, name: 'code', label: $t('code') },
        {
          width: 60,
          name: 'type',
          label: $t('type'),
          format: (value: any) => {
            if (value !== 'FOLDER') {
              return EngineEnums.LibType.formater(value);
            }
          },
        },
        { width: 60, name: 'version', label: $t('version'), align: 'right' },
        {
          width: 60,
          name: 'status',
          label: $t('status'),
          align: 'center',
          format: EngineEnums.DeployStatus.formater,
        },
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'parent', label: $t('parent'), type: 'w-text', showIf: false },
            { name: 'type', label: $t('type'), type: 'w-text', showIf: false },
            { name: 'code', label: $t('code'), type: 'w-text', showIf: false },
            { name: 'name', label: $t('name'), type: 'w-text', requiredIf: true },
            { name: 'description', label: $t('description'), type: 'w-text' },
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'type', label: $t('type'), format: Formater.none() },
            { name: 'parent', label: $t('parent') },
            { name: 'id', label: $t('id') },
            { name: 'code', label: $t('code') },
            { name: 'name', label: $t('name') },
            { name: 'description', label: $t('description') },
            ...CorporationAuditorEntityManager.getViewerFields(),
          ],
        },
      }"
      @row-click="
        (args: any) => {
          currentSelectedLibRef = args.row;
          emit('rowClick', args);
        }
      "
    ></w-grid>
    <ImportDialog
      ref="importDialogRef"
      @after-imported="
        () => {
          treeGridRef.refresh();
        }
      "
    ></ImportDialog>
    <ImportSampleDialog ref="importSampleDialogRef"></ImportSampleDialog>
    <BloodRelationshipDialog ref="bloodRelationshipDialogRef"></BloodRelationshipDialog>
    <SourceCodeDialog
      ref="sourceCodeDialogRef"
      :source-code-url="Environment.apiContextPath('/api/re/executable/generateGroovySourceCode/' + currentSelectedLibRef.id)"
      :validate-url="Environment.apiContextPath('/api/re/executable/validateGroovySourceCode')"
    ></SourceCodeDialog>
  </div>
</template>
<script setup lang="ts">
import 'tailwindcss/utilities.css';
import { ref } from 'vue';
import { axios, Environment, Formater, EnumTools, DialogManager, Downloader, CorporationAuditorEntityManager } from 'platform-core';
import ImportDialog from './ImportDialog.vue';
import ImportSampleDialog from './ImportSampleDialog.vue';
import SourceCodeDialog from '@/views/shared/SourceCodeDialog.vue';
import BloodRelationshipDialog from '@/views/shared/BloodRelationshipDialog.vue';
import { EngineEnums } from '@/views/shared/enums/EngineEnums';

const emit = defineEmits<{
  (e: 'rowClick', evt: Event): void;
}>();

const treeGridRef = ref();
const sourceCodeDialogRef = ref();
const importDialogRef = ref();
const importSampleDialogRef = ref();
const bloodRelationshipDialogRef = ref();
const currentSelectedLibRef = ref({});

await EngineEnums.init();
</script>
