<template>
  <div style="width: 100%; height: 100%">
    <w-grid
      ref="gridRef"
      :title="$t('re.lib.tab.testcase.title')"
      dense-body
      dense-bottom
      :config-button="true"
      selection="multiple"
      :checkbox-selection="true"
      db-click-operation="edit"
      :tree="false"
      :fetch-data-url="fetchDataUrlComputed"
      :data-url="Environment.apiContextPath('/api/re/testCase')"
      :pageable="true"
      :pagination="{ rowsPerPage: 50 }"
      :sort-by="['-lastModifyDate']"
      :toolbar-configure="{ noIcon: false }"
      :toolbar-actions="getActions()"
      :query-form-cols-num="6"
      :query-form-fields="
        Tools.isNill(owner)
          ? [
              { colSpan: 2, name: 'name', label: $t('name'), type: 'w-text', clearable: true },
              { colSpan: 3, name: 'description', label: $t('description'), type: 'w-text', clearable: true },
            ]
          : []
      "
      :columns="[
        { width: 100, name: 'id', label: $t('id'), showIf: false },
        {
          width: 60,
          name: 'testResult',
          label: $t('re.testcase.grid.entity.testResult'),
          align: 'center',
          format: EngineEnums.TestResult.formater,
        },
        { width: 150, name: 'lastTestDate', label: $t('re.testcase.grid.entity.lastTestDate') },
        { width: 290, name: 'name', label: $t('name') },
        { width: 200, name: 'description', label: $t('description') },
        {
          width: 80,
          name: 'ownerType',
          label: $t('re.testcase.grid.entity.ownerType'),
          sortable: false,
          format: EngineEnums.TestCaseOwnerType.formater,
        },
        {
          width: 190,
          name: 'ownerDescription',
          label: $t('re.testcase.grid.entity.ownerDescription'),
          sortable: false,
          format: (value: any, row: any) => {
            return Tools.initialize(row.ownerName, '') + (Tools.isNill(row.ownerVersion) ? '' : '(V' + row.ownerVersion + ')');
          },
        },
        {
          width: 80,
          name: 'ownerStatus',
          label: $t('re.testcase.grid.entity.ownerStatus'),
          sortable: false,
          align: 'center',
          format: EngineEnums.DeployStatus.formater,
        },
      ]"
      :editor="{
        dialog: {
          width: '600px',
        },
        form: {
          colsNum: 1,
          fields: [
            { name: 'id', label: $t('id'), type: 'w-text', showIf: false },
            { name: 'name', label: $t('name'), type: 'w-text', requiredIf: true },
            { name: 'description', label: $t('description'), type: 'w-text' },
            ...getEditorFields(),
          ],
        },
      }"
      :viewer="{
        panel: {
          columnNum: 1,
          fields: [
            { name: 'id', label: $t('id') },
            { name: 'name', label: $t('name') },
            { name: 'description', label: $t('description') },
            { name: 'ownerId', label: $t('re.testcase.grid.entity.ownerId') },
            { name: 'ownerType', label: $t('re.testcase.grid.entity.ownerType'), format: Formater.none() },
            { name: 'ownerCode', label: $t('re.testcase.grid.entity.ownerCode') },
            { name: 'ownerName', label: $t('re.testcase.grid.entity.ownerName') },
            { name: 'ownerVersion', label: $t('re.testcase.grid.entity.ownerVersion') },
            { name: 'ownerStatus', label: $t('re.testcase.grid.entity.ownerStatus'), format: Formater.none() },
          ],
        },
      }"
      v-bind="attrs"
      @row-click="
        (args) => {
          emit('rowClick', args);
        }
      "
      @before-request-data="
        (args: any) => {
          emit('beforeRequestData', args);
        }
      "
    ></w-grid>
    <UploadTestCaseDialog ref="uploadTestCaseDialogRef"></UploadTestCaseDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, useAttrs, computed } from 'vue';
import { $t, axios, Environment, Tools, Downloader, Formater } from 'platform-core';
import { ValueTypeManager } from '@/views/shared/ValueTypeManager';
import { EngineEnums } from '@/views/shared/enums/EngineEnums';
import UploadTestCaseDialog from './UploadTestCaseDialog.vue';

const attrs = useAttrs();
const props = defineProps({
  owner: { type: Object, default: undefined },
});
const emit = defineEmits<{
  (e: 'rowClick', args): void;
  (e: 'beforeRequestData', args): void;
}>();

const gridRef = ref();
const uploadTestCaseDialogRef = ref();
const valueTypeManager = new ValueTypeManager();

const fetchDataUrlComputed = computed(() => {
  if (Tools.isNill(props.owner)) {
    return Environment.apiContextPath('/api/re/testCase/find');
  } else {
    return Environment.apiContextPath('/api/re/testCase/findByOwnerId?ownerId=' + Tools.initialize(props.owner?.id, ''));
  }
});

const actionMap = {
  deepClone: {
    extend: 'clone',
    name: 'deepClone',
    label: $t('deepClone'),
    icon: 'bi-copy',
    click: (args: any) => {
      axios.post(Environment.apiContextPath('/api/re/testCase/deepClone/' + args.selected.id), {}, { loading: true }).then((response) => {
        gridRef.value.refresh();
      });
    },
  },
  execute: {
    name: 'execute',
    label: $t('execute'),
    icon: 'bi-caret-right',
    enableIf: (args: any) => {
      return args.selected;
    },
    click: (args: any) => {
      const tickeds = args.tickeds;
      if (tickeds && tickeds.length > 0) {
        const ids = Tools.extractProperties(tickeds, 'id');
        if (ids && ids.length > 0) {
          axios.post(Environment.apiContextPath('/api/re/testCase/execute'), ids, { loading: true }).then((response) => {
            gridRef.value.refresh();
          });
        }
      }
    },
  },
  executeAll: {
    name: 'executeAll',
    label: $t('executeAll'),
    icon: 'bi-caret-right-fill',
    click: (args: any) => {
      axios.post(Environment.apiContextPath('/api/re/testCase/executeAll'), {}, { loading: true }).then(() => {
        gridRef.value?.refresh();
      });
    },
  },
  batchTest: {
    name: 'batchTest',
    label: $t('re.testcase.grid.tools.batchTest'),
    icon: 'bi-list-check',
  },
  download: {
    name: 'download',
    label: $t('re.testcase.grid.tools.download'),
    icon: 'bi-box-arrow-in-down',
    click: (args: any) => {
      Downloader.post(Environment.apiContextPath('/api/re/testCase/downloadTemplate/' + props.owner.resource), {}, { loading: true });
    },
  },
  upload: {
    name: 'upload',
    label: $t('re.testcase.grid.tools.upload'),
    icon: 'bi-box-arrow-in-up',
    click: (args: any) => {
      uploadTestCaseDialogRef.value.open();
    },
  },
};

const getActions = () => {
  if (Tools.isNill(props.owner)) {
    return ['query', actionMap['execute'], actionMap['executeAll'], [actionMap['batchTest'], actionMap['upload']], 'separator', 'view', 'separator', 'export'];
  } else {
    return [
      'refresh',
      'separator',
      ['add', 'clone', actionMap['deepClone']],
      'edit',
      'remove',
      'separator',
      actionMap['execute'],
      actionMap['executeAll'],
      'separator',
      [actionMap['batchTest'], actionMap['download'], actionMap['upload']],
      'separator',
      'view',
      'separator',
      'export',
    ];
  }
};

const getEditorFields = () => {
  if (Tools.isNill(props.owner)) {
    return [];
  }
  if (props.owner.type === 'INDICATOR') {
    return [
      { name: 'ownerType', label: $t('ownerType'), type: 'w-text', defaultValue: 'LIB', showIf: false },
      { name: 'owner', label: $t('owner'), type: 'w-text', defaultValue: props.owner.id, showIf: false },
    ];
  } else {
    return [
      { name: 'ownerType', label: $t('ownerType'), type: 'w-text', defaultValue: 'MODEL', showIf: false },
      { name: 'owner', label: $t('owner'), type: 'w-text', defaultValue: props.owner.id, showIf: false },
    ];
  }
};

await EngineEnums.init();
await valueTypeManager.init();
</script>
