<template>
  <h1> {{ $t("lang.ActivitiAdmin.workflowEditing") }}</h1>

  <a-space wrap style="margin-bottom: 16px">
    <a-button class="editable-add-btn" :loading="loading" @click="handleAdd"> {{ $t("lang.ActivitiAdmin.newlyAdded") }}</a-button>

    <a-button class="editable-add-btn" :loading="loading" @click="handleRequery"> {{ $t("lang.ActivitiAdmin.refresh") }}</a-button>

    <a-button type="default" :disabled="!hasSelected" :loading="loading" @click="downloadBpmns">
      {{ $t("lang.ActivitiAdmin.download") }}{{ `(${selectedRowKeys.length})` }}
    </a-button>

    <a-button type="primary" danger :disabled="!hasSelected" :loading="loading" @click="deleteBpmnModalVisible = true">
      {{ $t("lang.ActivitiAdmin.delete") }}{{ `(${selectedRowKeys.length})` }}
    </a-button>

    <a-upload
      v-model:file-list="fileList"
      name="files"
      :headers="headers"
      action="/api/modelResource/createModelByFile"
      @change="handleChange"
    >
      <a-button>
        <upload-outlined />
        {{ $t("lang.ActivitiAdmin.upload") }}
      </a-button>
    </a-upload>
  </a-space>
  

  <a-table
    :columns="columns"
    :row-key="(record) => record.id"
    :data-source="dataSource"
    :pagination="pagination"
    :loading="loading"
    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'operation'">
        <a @click="editBpmn(record)"> {{ $t("lang.ActivitiAdmin.edit") }}</a>

        <a v-if="record.deploymentId == null" style="margin-left: 1rem;" @click="deployBpmn(record)">{{ $t("lang.ActivitiAdmin.deploy") }}</a>
        <a v-else style="margin-left: 1rem;" @click="deleteDeployBpmn(record)">{{ $t("lang.ActivitiAdmin.deleteDeployment") }}</a>
      </template>
    </template>
    <template
      #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
    >
      <div style="padding: 8px">
        <a-input
          ref="searchInput"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block"
          @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          @press-enter="handleSearch(selectedKeys, confirm, column.dataIndex)"
        />
        <a-button
          type="primary"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          <template #icon><SearchOutlined /></template>
          Search
        </a-button>
        <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
          Reset
        </a-button>
      </div>
    </template>
  </a-table>

  <a-modal v-model:open="deleteBpmnModalVisible" title="请确认删除工作流" @ok="deleteBpmns">
    您确定要删除选中的{{ `  ${selectedRowKeys.length}  ` }}个流程定义吗？
  </a-modal>
</template>
<script>
import { usePagination } from 'vue-request';
import { ref, reactive, toRefs, computed, defineComponent } from 'vue';
import ModelResources from '../api/base/ModelResource.js';
import Common from '../common/Common.js';
import { SearchOutlined , UploadOutlined} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default defineComponent({
  components: {
    SearchOutlined,UploadOutlined,
  },

  setup() {
    const deleteBpmnModalVisible = ref(false);

    const queryData = params => {
      let firstResult = (params.current - 1) * params.pageSize;
      let maxResults = params.pageSize;
      let modelName = null, deploymentId = null;
      if(state.searchedColumn === 'name'){
        modelName = state.searchText;
      }
      if(state.searchedColumn === 'deploymentId'){
        deploymentId = state.searchText;
      }

      return ModelResources.listModel(firstResult, maxResults, modelName, deploymentId);
    };

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        customFilterDropdown: true,
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: 'Key',
        dataIndex: 'key',
      },
      {
        title: 'Category',
        dataIndex: 'category',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '更新时间',
        dataIndex: 'lastUpdateTime',
      },
      {
        title: '部署Id',
        dataIndex: 'deploymentId',
        key: 'deploymentId',
        customFilterDropdown: true,
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
        },
      },
      {
        title: '租户Id',
        dataIndex: 'tenantId',
      },{
        title: '操作',
        key: 'operation',
        fixed: 'right',
        width: 100,
      },
    ];

    const state = reactive({
      searchText: '',
      searchedColumn: '',
      selectedRowKeys: [],
    });

    const hasSelected = computed(() => state.selectedRowKeys.length > 0);

    const onSelectChange = selectedRowKeys => {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      state.selectedRowKeys = selectedRowKeys;
    };

    const searchInput = ref();
    const {
      data: dataSource,
      run,
      loading,
      current,
      pageSize,
      total,
    } = usePagination(queryData, {
      formatResult: res => res.datas,
      pagination: {
        currentKey: 'current',
        pageSizeKey: 'pageSize',
        totalKey: 'total',
      },
    });

    const pagination = computed(() => ({
      total: total,
      current: current.value,
      pageSize: pageSize.value,
    }));

    const handleTableChange = (pag, filters, sorter) => {
      run({
        pageSize: pag.pageSize,
        current: pag.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      });
    };

    const handleRequery = () => {
      run({
        pageSize: pageSize.value,
        current: 1,
      });
      fileList.value = [];
      state.selectedRowKeys = [];
    };

    const handleAdd = () =>{
      ModelResources.create().then(successData => {
        handleRequery();
      }, errorData => {
        Common.processException(errorData);
      });
    };

    const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      state.searchText = selectedKeys[0];
      state.searchedColumn = dataIndex;
      handleRequery();
    };

    const handleReset = clearFilters => {
      clearFilters({
        confirm: true,
      });
      state.searchText = '';
      state.searchedColumn = null;
      handleRequery();
    };

    const editBpmn = record => {
      let url = '/wf-editor/modeler.html?modelId=' + record.id;
      window.open(url);
    };

    const deployBpmn = record => {
      ModelResources.deploy(record.id).then(successData => {
        if(successData.errorCode === 0){
          handleRequery();
          message.success('流程部署成功，部署id=' + successData.data);
        }else{
          message.error(successData.errorMessage);
        }
      }, errorData => {
        Common.processException(errorData);
      });
    };

    const deleteBpmns = () => {
      ModelResources.deleteModels(state.selectedRowKeys).then(successData => {
        if(successData.errorCode === 0){
          successData.datas.forEach(element => {
            if(element.errorCode !== 0){
              message.error(element.errorMessage);
            }
          });
        }else{
          message.error(successData.errorMessage);
        }
        deleteBpmnModalVisible.value = false;
        handleRequery();
      },errorData => {
        Common.processException(errorData);
      });
    };

    const downloadBpmns = () => {
      if(state.selectedRowKeys.length == 0){
        return;
      }
      state.selectedRowKeys.forEach(item => {
        let url = '/api/modelResource/export/' + item;
        window.open(url);
      });
    };

    const deleteDeployBpmn = record => {
      ModelResources.undeploy(record.id).then(successData => {
        if(successData.errorCode === 0){
          handleRequery();
          message.success('删除流程部署成功。');
        }else{
          message.error(successData.errorMessage);
        }
      }, errorData => {
        Common.processException(errorData);
      });
    };

    const handleChange = info => {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }

      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功。`);
        handleRequery();
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败。 ${info.file.response}`);
      }
    };

    const fileList = ref([]);

    const headers = {
      'token': localStorage.getItem('#token'),
    };
    
    return {
      searchInput,
      dataSource,
      pagination,
      loading,
      columns,
      editBpmn,
      ...toRefs(state),
      handleTableChange,
      handleRequery,
      handleAdd,
      handleSearch,
      handleReset,
      handleChange, 
      fileList,
      deployBpmn,
      deleteDeployBpmn,
      deleteBpmns,
      hasSelected,
      onSelectChange,
      deleteBpmnModalVisible,
      downloadBpmns,
      headers,
    };
  },
});
</script>