import UserTasksUploadComponent from '@components/user-tasks/upload/index.vue';
import { Component, Vue } from 'vue-property-decorator';
import { convertDateFromBackendFormat } from '@utils/format-date';
import { WorkflowServiceApi, UserTaskListItem } from '@openapi/wf';

const wfApi = new WorkflowServiceApi();

@Component({
  components: { UserTasksUploadComponent },
})
export default class UserTasks extends Vue {
  list: UserTaskListItem[] = [];

  private model = {
    loading: false,
    pagination: {
      page: this.$route.query.page ? Number(this.$route.query.page) : 1,
      rowsNumber: 0,
      rowsPerPage: 10,
    },
    visibleColumns: ['userTask.title', 'process.title', 'userTask.createDate'],
  };

  private get columns(): any[] {
    return [
      {
        field: 'id',
        label: this.$t('userTask.id'),
        name: 'id',
      },
      {
        align: 'left',
        field: (val: any) => val,
        format: (val: any) => this.$t(val.userTask.title),
        handler: (val: any) => {
          this.$router.push({
            name: 'stepper',
            params: {
              traceId: val.process.traceId,
            },
            query: {
              taskId: val.userTask.taskId,
            },
          });
        },
        icon: 'work_outline',
        label: this.$t('userTask.title'),
        name: 'userTask.title',
        required: true,
      },
      {
        align: 'left',
        field: (val: any) => val,
        format: (val: any) => this.$t(val.process.title),
        icon: 'work_outline',
        label: this.$t('userTask.process'),
        name: 'process.title',
      },
      {
        align: 'right',
        field: (val: any) => val.userTask.createDate,
        format: (val: any) => convertDateFromBackendFormat(val),
        label: this.$t('userTask.dateCreated'),
        name: 'userTask.createDate',
      },
    ];
  }

  private created(): void {
    this.init();
  }

  private async init(val: any = null): Promise<void> {
    if (val?.pagination) {
      this.model.pagination.page = val.pagination.page;
      this.model.pagination.rowsPerPage = val.pagination.rowsPerPage;
    }

    this.model.loading = true;

    return wfApi
      .taskList(
        undefined,
        (this.model.pagination.page - 1).toString(),
        this.model.pagination.rowsPerPage.toString()
      )
      .then(({ data }) => {
        this.model.pagination.rowsNumber = data.totalCount || 0;
        this.list = data.tasks || [];
      })
      .finally(() => {
        this.model.loading = false;
      });
  }
}
