<template>
  <div class="pr-1" style="height: 100%">
    <w-grid
      ref="treeGridRef"
      :title="$t('re.lib.grid.title')"
      :draggable="true"
      dense-body
      hide-bottom
      db-click-operation="edit"
      :config-button="true"
      selection="multiple"
      :checkbox-selection="false"
      :tree="true"
      :tree-icon="
        (row) => {
          if (row.type === 'FOLDER') {
            return { name: 'folder', color: 'amber' };
          } else {
            return { name: 'bi-card-list' };
          }
        }
      "
      ticked-field="selected"
      :data-url="Environment.apiContextPath('/api/re/lib')"
      :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: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'FOLDER');
            },
          },
          {
            extend: 'addChild',
            name: 'addChild',
            label: $t('re.lib.grid.toolbar.addChild'),
            enableIf: (arg) => {
              return arg.selected && arg.selected.type === 'FOLDER';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'FOLDER');
            },
          },
          'separator',
          {
            name: 'addLib',
            extend: 'addChild',
            label: $t('re.lib.grid.toolbar.addLib'),
            icon: 'playlist_add',
            enableIf: (arg) => {
              return arg.selected && arg.selected.type === 'FOLDER';
            },
            afterClick: (arg) => {
              arg.grid.getEditorForm().setFieldValue('type', 'INDICATOR');
            },
          },
        ],
        [
          {
            name: 'cloneGroup',
            label: $t('re.lib.grid.toolbar.cloneGroup'),
            icon: 'content_copy',
            click: undefined,
            enableIf: (arg) => {
              return arg.selected;
            },
          },
          'clone',
          {
            extend: 'deepClone',
            name: 'deepClone',
            label: $t('re.lib.grid.toolbar.deepClone'),
            icon: 'bi-copy',
            enableIf: (arg) => {
              return arg.selected && arg.selected.type !== 'FOLDER';
            },
            click: (arg) => {
              DialogManager.confirm($t('re.lib.grid.toolbar.deepClone.tip'), () => {
                axios.post(Environment.apiContextPath('/api/re/lib/deepClone/' + arg.selected.id)).then(() => {
                  treeGridRef.refresh();
                });
              });
            },
          },
          {
            extend: 'clone',
            name: 'deepCloneNew',
            label: $t('re.lib.grid.toolbar.deepCloneNew'),
            icon: 'bi-copy',
            enableIf: (arg) => {
              return arg.selected && arg.selected.type !== 'FOLDER';
            },
            click: (arg) => {
              DialogManager.confirm($t('re.lib.grid.toolbar.deepCloneNew.tip'), () => {
                axios.post(Environment.apiContextPath('/api/re/lib/deepCloneNew/' + arg.selected.id)).then(() => {
                  treeGridRef.refresh();
                });
              });
            },
          },
        ],

        'separator',
        'edit',
        'remove',
        'separator',
        {
          name: 'generateGroovy',
          label: $t('re.lib.grid.toolbar.generateGroovy'),
          icon: 'bi-code',
          enableIf: (arg) => {
            return arg.selected && arg.selected.type === 'INDICATOR';
          },
          click: (arg) => {
            axios.post(Environment.apiContextPath('/api/re/resource/generateGroovySourceCode/' + arg.selected.id), {}, { loading: true }).then((response) => {
              sourceCodeDialogRef.open(response.data.source);
            });
          },
        },
        'separator',
        {
          name: 'deploy',
          label: $t('re.lib.grid.toolbar.deploy'),
          icon: 'bi-balloon',
          enableIf: (arg) => {
            return arg.selected && arg.selected.type !== 'FOLDER' && arg.selected.status === 'SKETCH';
          },
          click: (arg) => {
            DialogManager.confirm($t('re.lib.grid.toolbar.deploy.tip'), () => {
              axios.post(Environment.apiContextPath('/api/re/lib/deploy/' + arg.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: () => {
              importDialogRef.open();
            },
          },
          {
            name: 'importSample',
            label: $t('re.lib.grid.toolbar.importSample'),
            icon: 'bi-database-up',
            click: () => {
              importSampleDialogRef.open();
            },
          },
        ],
        'separator',
        'view',
        'separator',
        {
          extend: 'export',
          enableIf: (arg) => {
            return arg.selected;
          },
          click: (arg) => {
            Downloader.get(Environment.apiContextPath('/api/re/lib/export/' + arg.selected.id));
          },
        },
      ]"
      :columns="[
        {
          width: '100%',
          name: 'name',
          label: $t('name'),
          sortable: false,
        },
        {
          width: 80,
          name: 'type',
          label: $t('type'),
          sortable: false,
          format: (value) => {
            if (value !== 'FOLDER') {
              return Formater.enum(Enums.LibType)(value);
            }
          },
        },
        { width: 60, name: 'version', label: $t('version') },
        {
          width: 60,
          name: 'status',
          label: $t('status'),
          align: 'center',
          sortable: false,
          format: (value, row) => {
            return {
              componentType: ResourceDeployStatusTag,
              attrs: { status: value },
            };
          },
        },
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'parent', label: $t('parent'), type: 'w-text', hidden: true },
            { name: 'type', label: $t('type'), type: 'w-text', hidden: true },
            {
              name: 'code',
              label: $t('code'),
              type: 'w-text',
              showIf: (arg) => {
                const type = arg.form.getFieldValue('type');
                return type !== 'FOLDER';
              },
            },
            { name: 'name', label: $t('name'), type: 'w-text', required: true },
            { name: 'description', label: $t('description'), type: 'w-text' },
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'order', label: $t('order') },
            { name: 'id', label: $t('id') },
            { name: 'parent', label: $t('parent') },
            { name: 'type', label: $t('type') },
            { name: 'code', label: $t('code') },
            { name: 'name', label: $t('name') },
            { name: 'description', label: $t('description') },

            { name: 'dataComeFrom', label: $t('dataComeFrom') },
            { name: 'creator', label: $t('creator') },
            { name: 'createDate', label: $t('createDate') },
            { name: 'lastModifier', label: $t('lastModifier') },
            { name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.none() },
          ],
        },
      }"
      v-bind="attrs"
    ></w-grid>
    <ImportDialog
      ref="importDialogRef"
      @after-imported="
        () => {
          treeGridRef.refresh();
        }
      "
    ></ImportDialog>
    <ImportSampleDialog ref="importSampleDialogRef"></ImportSampleDialog>
    <SourceCodeDialog ref="sourceCodeDialogRef"></SourceCodeDialog>
  </div>
</template>
<script setup lang="ts">
import { ref, useAttrs } from 'vue';
import { axios, Environment, Formater, EnumTools, DialogManager, Downloader } from 'platform-core';
import ImportDialog from './ImportDialog.vue';
import ImportSampleDialog from './ImportSampleDialog.vue';
import ResourceDeployStatusTag from '@/views/shared/ResourceDeployStatusTag.vue';
import SourceCodeDialog from '@/views/shared/SourceCodeDialog.vue';

const attrs = useAttrs();

const treeGridRef = ref();
const sourceCodeDialogRef = ref();
const importDialogRef = ref();
const importSampleDialogRef = ref();

const Enums = await EnumTools.fetch(['io.sc.engine.rule.core.enums.LibType', 'io.sc.engine.rule.core.enums.DeployStatus']);
let ValueTypeMap = {};
const ValueTypeList = [];
const response = await axios.get(Environment.apiContextPath('/api/re/dictionary/getAllDictionaryMap'));
if (response && response.data) {
  ValueTypeMap = {};
  ValueTypeList.splice(0, ValueTypeList.length);
  for (const item of response.data) {
    ValueTypeMap[item.key] = item.value;
    ValueTypeList.push({ value: item.key, label: item.value });
  }
}
</script>
