<template>
  <div class="container-fluid">
    <Navbar
      :title="$t('lang.WorkflowEdit.workflowManagement')"
      :is-go-back="false"
    />
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div class="form-inline" style="margin-top: 10px">
        <div class="form-group">
          <label for="condition">{{ $t("lang.WorkflowEdit.queryCondition") }}：</label>
          <a-input
            id="condition"
            v-model:value="condition"
            autocomplete="off"
            class="form-control"
            @press-enter="query"
          />
        </div>

        <a-button class="btn btn-default" @click="requeryWorkflows">
          {{ $t("lang.WorkflowEdit.query") }}
        </a-button>

        <a-button class="btn btn-default" @click="addition">
          {{ $t("lang.WorkflowEdit.newlyBuild") }}
        </a-button>

        <a-button class="btn btn-default" @click="exportJsonFile">
          {{ $t("lang.WorkflowEdit.export") }}
        </a-button>

        <a-button class="btn btn-default" @click="importJsonFile">
          {{ $t("lang.WorkflowEdit.import") }}
        </a-button>
      </div>
      <a-button
        class="btn btn-default"
        style="margin: 10px 0 0 0"
        @click="openArchive"
      >
        历史数据归档
      </a-button>
    </div>
    <div class="table-responsive" style="margin-top: 10px">
      <template v-if="hasSelected">
        {{ `Selected ${selectedRowKeys.length} items` }}
      </template>
      <CommonTable
        ref="table"
        :columns="columns"
        :data-source="workflowDatas"
        :total="pagination.total"
        :row-selection="rowSelection"
        @get-pager="getPageParams"
      >
        <template #headerCell="{ column }">
          <template v-if="column.dataIndex == 'check'">
            <input
              v-model="checked"
              autocomplete="off"
              type="checkbox"
              :checked="checked"
              @change="selectAll()"
            />
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'check'">
            <input
              autocomplete="off"
              type="checkbox"
              name="checkboxinput"
              :checked="record.checked"
              @click="record.checked = !record.checked"
            />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-button type="dashed" @click="selectWorkflow(record, true)">
              编辑
            </a-button>
          </template>
          <template v-if="column.dataIndex === 'window'">
            <span>{{ record.windowNo }}.{{ record.windowName }}</span>
          </template>
          <template v-if="column.dataIndex === 'deploymentId'">
            <span>{{
              record.deploymentId != undefined &&
                record.deploymentId.length > 0
                ? "已部署"
                : "未部署"
            }}
            </span>
          </template>
        </template>
      </CommonTable>
    </div>
    <Loading v-if="loading" />
    <a-drawer
      v-model:open="modal"
      :width="640"
      class="custom-class"
      title="工作流定义"
      placement="right"
    >
      <div class="form-group">
        <label>{{ $t("lang.WorkflowEdit.corporateName") }}</label>
        <v-select
          v-model="selectedWorkflow.client"
          :options="clientOptions"
          :label="'name'"
        />
      </div>
      <div class="form-group">
        <label>{{ $t("lang.WorkflowEdit.windowName") }}</label>
        <v-select
          v-model="selectedWorkflow.window"
          :options="windowOptions"
          :label="'value'"
        />
      </div>
      <div class="form-group">
        <label>{{ $t("lang.WorkflowEdit.workflowName") }}</label>
        <a-input
          v-model:value="selectedWorkflow.name"
          autocomplete="off"
          class="form-control"
        />
      </div>
      <div class="form-group">
        <label>{{ $t("lang.WorkflowEdit.workflowFilePath") }}</label>
        <v-select
          v-model="selectedWorkflow.bpmnFileName"
          :options="bpmns"
          :label="'value'"
        />
      </div>
      <div class="form-group">
        <label>{{ $t("lang.WorkflowEdit.workflowType") }}</label><br />
        <a-select
          v-model:value="selectedWorkflow.workflowType" class="form-control"
          style="width: 100%;"
        >
          <a-select-option
            v-for="workflowType in workflowTypes"
            :key="workflowType.keyStr"
            :value="workflowType.keyStr"
          >
            {{ workflowType.value }}
          </a-select-option>
        </a-select>
      </div>
      <div class="form-group">
        <label>{{ $t("lang.WorkflowEdit.deploymentStatus")
        }}{{
          selectedWorkflow.deploymentId != undefined &&
            selectedWorkflow.deploymentId.length > 0
            ? $t("lang.WorkflowEdit.deployed")
            : $t("lang.WorkflowEdit.notDeployed")
        }}</label>
        <a-input
          v-model:value="selectedWorkflow.deploymentId"
          class="form-control"
        />
      </div>
      <div class="form-group">
        <label>{{
          $t("lang.WorkflowEdit.deleteProcessVerificationPassword")
        }}</label>
        <a-input
          v-model:value="selectedWorkflow.deletePassword"
          onfocus="this.type='password'"
          class="form-control"
        />
      </div>
      <template #footer>
        <div class="footerStyle">
          <a-button class="btn btn-default" @click="approvalFlow">
            {{ $t("lang.WorkflowEdit.editor") }}
          </a-button>
          <a-button class="btn btn-default" @click="deleteWorkflow">
            {{ $t("lang.WorkflowEdit.delete") }}
          </a-button>
          <a-button class="btn btn-default" @click="save">
            {{ $t("lang.WorkflowEdit.save") }}
          </a-button>
          <a-button class="btn btn-default" @click="sync">
            {{ $t("lang.WorkflowEdit.synchronization") }}
          </a-button>
          <a-button class="btn btn-default" @click="deleteInstance">
            {{ $t("lang.WorkflowEdit.deleteInstance") }}
          </a-button>
          <a-button class="btn btn-default" @click="processInstanceCount">
            {{ $t("lang.WorkflowEdit.numberOfProcessInstances") }}
          </a-button>

          <a-button
            v-if="
              selectedWorkflow.workflowType == 'Timer' ||
                selectedWorkflow.workflowType == 'OTHER' ||
                selectedWorkflow.workflowType == 'NoticeOnLogin'
            "
            class="btn btn-default"
            @click="manualStartWorkflow"
          >
            {{ $t("lang.WorkflowEdit.manualStartProcess") }}
          </a-button>
        </div>
      </template>
    </a-drawer>

    <Modal v-model:show="modal1" small="true">
      <template #header>
        {{ $t("lang.WorkflowEdit.workflowDefinition") }}
      </template>
      <div>
        <div class="form-group">
          <label>{{ $t("lang.WorkflowEdit.workflowJsonFile") }}</label>
          <pre>{{ selectWorkflowDatas }}</pre>
        </div>
      </div>
    </Modal>
    <Modal
      v-model:show="modal2"
      :show-ok-button="false"
      :show-canel-button="false"
      small="true"
    >
      <template #header>
        {{ $t("lang.WorkflowEdit.workflowDefinition") }}
      </template>
      <div>
        <div class="form-group">
          <label>{{ $t("lang.WorkflowEdit.workflowJsonFile") }}</label>
          <a-textarea v-model:value="jsonFile" class="form-control" rows="20" />
        </div>
      </div>
      <template #footer>
        <div>
          <a-button @click="modelClose">
            {{ $t("lang.WorkflowEdit.cancel") }}
          </a-button>
          <a-button
            type="primary"
            @click="saveWorkflowDto"
          >
            {{ $t("lang.WorkflowEdit.determine") }}
          </a-button>
        </div>
      </template>
    </Modal>
    <a-modal
      v-model:open="archiveVisible"
      title="请按照如下步骤进行历史数据归档"
      width="600px"
      :mask-closable="false"
    >
      <a-steps :current="current">
        <a-step
          v-for="item in steps"
          :key="item.title"
          :title="item.title"
          :description="item.content"
        />
      </a-steps>
      <div class="steps-content">
        <div v-if="steps[current].title === '步骤一'">
          <a-textarea v-model:value="tableSql" :rows="8" />
          <h4 style="margin: 20px 0; color: red">
            注意：一定要复制SQL到数据库中执行，很重要！很重要！很重要！
          </h4>
        </div>
        <div v-if="steps[current].title === '步骤二'">
          <h4
            v-if="!isNext"
            style="padding: 100px 0; text-align: center; color: red"
          >
            注意：改操作执行时间较长，执行时请您耐心等待。
          </h4>
          <h4 v-else style="padding: 100px 0; text-align: center; color: red">
            历史数据归档完成，共计归档{{ archiveTotal }}条数据。
          </h4>
        </div>
        <div v-if="steps[current].title === '步骤三'">
          <a-textarea v-model:value="deleteTableSql" :rows="8" />
          <h4 style="margin: 20px 0; color: red">
            注意：一定要复制SQL到数据库中执行，很重要！很重要！很重要！
          </h4>
        </div>
      </div>
      <div class="steps-action">
        <div>
          <a-button v-if="current > 0" @click="prev"> 上一步 </a-button>
          <span v-else />
        </div>
        <div>
          <a-button
            v-if="current === 0 || current === 2"
            type="dashed"
            style="margin-right: 8px"
            @click="copyText"
          >
            复制
          </a-button>
          <a-button
            v-if="current === 1"
            type="dashed"
            style="margin-right: 8px"
            @click="archiveDatas"
          >
            归档
          </a-button>
          <a-button
            v-if="current === 0"
            type="primary"
            :disabled="!isOk"
            @click="next"
          >
            下一步
          </a-button>
          <a-button
            v-if="current === 1"
            type="primary"
            :disabled="!isNext"
            @click="next"
          >
            下一步
          </a-button>
          <a-button
            v-if="current === 2"
            type="primary"
            :disabled="!isDeleteOk"
            @click="archiveVisible = false"
          >
            完成
          </a-button>
        </div>
      </div>
      <template #footer />
    </a-modal>
  </div>
</template>

<script>
import Common from '../common/Common.js';
import vSelect from 'vue-select';
import WorkflowEditResource from './WorkflowEditResource.js';
import 'vue-select/dist/vue-select.css';
import { Notify, Uuid } from 'pc-component-v3';
import CommonTable from '../common/CommonTable.vue';
import { ajaxApiGet, ajaxApi } from '../api/workflow/workflow';
import { message } from 'ant-design-vue';

export default {
  components: {
    'v-select': vSelect,
    CommonTable,
  },
  data: function () {
    return {
      isSelect: true,
      columns: [
        {
          title: '',
          dataIndex: 'check',
          key: 'check',
          width: 48,
        },
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          width: 75,
          customRender: ({ text, record, index }) => `${index + 1}`,
        },
        {
          title: '公司名称',
          dataIndex: 'clientName',
          key: 'clientName',
        },
        {
          title: '工作流名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '文件路径',
          dataIndex: 'bpmnFileName',
          key: 'bpmnFileName',
        },
        {
          title: '窗口',
          dataIndex: 'window',
          key: 'window',
          width: '250px',
        },
        {
          title: '工作流类型',
          dataIndex: 'workflowTypeName',
          key: 'workflowTypeName',
        },
        {
          title: '部署状态',
          dataIndex: 'deploymentId',
          key: 'deploymentId',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: '100px',
          fixed: 'right',
        },
      ].map(item => ({ ...item, align: 'center' })),
      // dataSource: [
      //   {
      //     key: '1',
      //     corporateName: '测试公司',
      //     workflowName: '资产申购单',
      //     fileUrl: '',
      //     window: '040601.资产申购单',
      //     workflowType: '用户自定义',
      //     deploymentStatus: '已部署',
      //   },
      // ],
      clientOptions: [],
      workflowDatas: [],
      windowOptions: [],
      workflowTypes: [],
      bpmns: [],
      checked: false,
      selectedWorkflow: {
        id: undefined,
        clientId: undefined,
        clientName: undefined,
        client: undefined,
        windowNo: undefined,
        windowName: '',
        window: undefined,
        deploymentId: undefined,
        name: undefined,
        bpmnFileName: undefined,
        description: undefined,
        workflowType: undefined,
        deletePassword: null,
      },
      processReports: [],
      condition: undefined,
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },
      selectWorkflowDatas: undefined,
      jsonFile: undefined,
      loading: false,
      isNext: false,
      modal: false,
      modal1: false,
      modal2: false,
      archiveVisible: false,
      isOk: false,
      isDeleteOk: false,
      current: 0,
      tableSql: '',
      deleteTableSql: '',
      archiveTotal: null,
      steps: [
        {
          title: '步骤一',
          content: '备份历史数据',
        },
        {
          title: '步骤二',
          content: '执行归档',
        },
        {
          title: '步骤三',
          content: '删除历史数据',
        },
      ],
    };
  },

  computed: {},
  watch: {
    'selectedWorkflow.window': {
      handler(newValue, oldVal) {
        if (newValue != oldVal && newValue) {
          this.selectedWorkflow.name = newValue.value;
        }
      },
      deep: true,
    },
  },

  mounted: function () {
    this.queryBpmn();
    //this.queryDeploymentIds();
    this.initSelectedWorkflow();
    this.loadWorkflowTypes();
    this.loadClients();
    this.loadProcessReports();
  },
  methods: {
    openArchive: function () {
      this.current = 0;
      this.getTableSql();
      this.isOk = false;
      this.isNext = false;
      this.isDeleteOk = false;
    },
    next: function () {
      this.current++;
      if (this.current === 2) {
        this.getDeleteTableSql();
      }
    },
    prev: function () {
      this.current--;
    },
    rowSelection: function () {
      const onChange = (selectedRowKeys, selectedRows) => {
        //第一个参数控制选不选中，第二个参数是选中列表的数据的集合
        console.log(selectedRows);
      };
      const getCheckboxProps = record => ({
        disabled: record.releaseState === 'ONLINE', //控制禁用那个按钮
        releaseState: record.releaseState,
      });
      return onChange, getCheckboxProps;
    },

    /**
     * 导入json文件
     * @author GuoZhiBo 20210318
     */
    saveWorkflowDto: function () {
      var _self = this;
      var jsonFile = JSON.parse(_self.jsonFile);
      WorkflowEditResource.saveListWorkflowDto(jsonFile).then(
        successData => {
          if (successData) {
            Notify.success('导入成功', '导入成功', 1500);
            _self.refreshWorkflows();
          }
          _self.modal2 = false;
          _self.jsonFile = undefined;
        },
        errorData => {
          Common.processException(errorData);
          _self.modal2 = false;
        },
      );
    },
    /**
     * 关闭模态框
     * @author GuoZhiBo 20210318
     */
    modelClose: function () {
      var _self = this;
      _self.modal2 = false;
    },
    /**
     * 全选和反选
     * @author GuoZhiBo 20210318
     */
    selectAll: function () {
      var _self = this;
      if (_self.checked) {
        for (let i = 0; i < _self.workflowDatas.length; i++) {
          _self.workflowDatas[i].checked = true;
        }
      } else {
        for (let i = 0; i < _self.workflowDatas.length; i++) {
          _self.workflowDatas[i].checked = false;
        }
      }
    },
    setSelectedWorkflow: function (data) {
      data.client = {
        id: data.clientId,
        name: data.clientName,
      };
      data.window = {
        id: data.windowNo,
        value: data.windowName,
      };
      this.selectedWorkflow = data;
    },

    initSelectedWorkflow: function () {
      var _self = this;
      this.selectedWorkflow = {
        id: undefined,
        clientId: undefined,
        clientName: undefined,
        client: undefined,
        windowNo: undefined,
        windowName: undefined,
        window: undefined,
        deploymentId: undefined,
        name: undefined,
        bpmnFileName: undefined,
        description: undefined,
        workflowType: undefined,
        deletePassword: null,
      };
    },

    /**
     * 查询所有的可访问的单位
     */
    loadClients: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('ClientResource/listSubClient'),
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.clientOptions.splice(0, _self.clientOptions.length);

          // 清空数据
          if (data == undefined || data.length == 0) {
            return;
          }

          for (var i = 0, len = data.length; i < len; i++) {
            _self.clientOptions.push(data[i]);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 编辑器
     */
    approvalFlow: function () {
      var _self = this;

      var url =
        '/workflow.html#/approver?windowNo=' +
        _self.selectedWorkflow.window.keyStr +
        '&workflowId=' +
        _self.selectedWorkflow.id;

      window.open(url);
    },

    /**
     * [loadWindows 获取窗口]
     * @return {[type]} [description]
     */
    loadWindows: function () {
      var _self = this;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('CurdWindowResource/getWindowKeyValues'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          _self.windowOptions.splice(0, _self.windowOptions.length);
          // 清空数据
          if (data == undefined || data.length == 0) {
            return;
          }

          for (var i = 0, len = data.length; i < len; i++) {
            _self.windowOptions.push(data[i]);
          }

          _self.refreshWorkflows();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
     * 查询所有流程文件
     * @author GuoZhiBo 20200507
     */
    queryBpmn: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('WorkflowResource/queryBpmn'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.bpmns = data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 加载流程报表
     */
    loadProcessReports: function () {
      var _self = this;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL(
          'ProcessReportResource/getProcessReportKeyValues',
        ),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          _self.processReports.splice(0, _self.processReports.length);
          for (var i = 0, len = data.length; i < len; i++) {
            _self.processReports.push(data[i]);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
     * [获取工作流类型]
     * @return {[type]} [description]
     */
    loadWorkflowTypes: function () {
      var _self = this;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('workflowEditResource/getWorkflowTypes'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          _self.workflowTypes.splice(0, _self.workflowTypes.length);
          if (data == undefined || data.length == 0) {
            return;
          }

          for (var i = 0, len = data.length; i < len; i++) {
            _self.workflowTypes.push(data[i]);
          }

          _self.loadWindows();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 重新查询工作流
     */
    requeryWorkflows: function () {
      this.initSelectedWorkflow();
      this.pagination.current_page = 1;
      this.pagination.last_page = 0;
      this.$refs.table.backFirstPage();
    },

    // 从子组件获取的分页参数
    getPageParams: function (start, length) {
      this.pagination.current_page = start;
      this.pagination.per_page = length;
      this.refreshWorkflows();
    },

    /**
     * [getWorkflows 获取(刷新)工作流]
     * @return {[type]} [description]
     */
    refreshWorkflows: function () {
      var _self = this;
      _self.loading = true;
      var workflowDto = {
        range: {
          start:
            (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        condition: _self.condition,
      };
      $.ajax({
        url: Common.getApiURL('workflowEditResource/getWorkflowDtos'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(workflowDto),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          _self.pagination.total = data.totalSize;
          // 清空数据
          _self.workflowDatas.splice(0, _self.workflowDatas.length);
          if (data == undefined || data.dataList.length == 0) {
            return;
          }

          for (var i = 0, len = data.dataList.length; i < len; i++) {
            data.dataList[i].selected = false;
            data.dataList[i].checked = false;
            _self.workflowDatas.push(data.dataList[i]);
            if (
              _self.selectedWorkflow != null &&
              _self.selectedWorkflow.id == data.dataList[i].id
            ) {
              _self.selectWorkflow(data.dataList[i], false);
            }
          }
          _self.pagination.last_page = Math.ceil(
            data.totalSize / data.range.length,
          );
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * [addition 添加事件]
     * @return {[type]} [description]
     */
    addition: function () {
      var _self = this;
      _self.modal = true;
      _self.initSelectedWorkflow();
    },

    /**
     * 导出选中的流程
     * @author GuoZhiBo 20210318
     */
    exportJsonFile: function () {
      var _self = this;
      _self.modal1 = true;
      _self.selectWorkflowDatas = [];
      for (var i = 0; i < _self.workflowDatas.length; i++) {
        if (_self.workflowDatas[i].checked == true) {
          let item = _self.workflowDatas[i];
          item.id = null;
          item.clientId = null;
          item.clientName = null;
          _self.selectWorkflowDatas.push(item);
        }
      }
    },
    /**
     * 导入JSON文件
     */
    importJsonFile: function () {
      var _self = this;
      _self.modal2 = true;
    },

    /**
     * [deleteWorkflow 删除事件]
     * @return {[type]} [description]
     */
    deleteWorkflow: function () {
      var _self = this;
      if (_self.selectedWorkflow == undefined) {
        Notify.error('提示', '请选择数据', false);
        return;
      }
      if (_self.selectedWorkflow.id == 0) {
        _self.modal = false;
      } else {
        _self.loading = true;

        $.ajax({
          url: Common.getApiURL('workflowEditResource/deleteWorkflowDto'),
          type: 'post',
          dataType: 'json',
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          contentType: 'application/json',
          data: JSON.stringify(_self.selectedWorkflow),
          success: function (data) {
            _self.loading = false;
            _self.modal = false;
            Notify.success('删除成功', '数据删除成功', 1500);
            _self.refreshWorkflows();
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            _self.loading = false;
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
          },
        });
      }
    },

    /*
        按条件查询
        */
    query: function () {
      var _self = this;
      _self.$refs.table.backFirstPage();
    },

    /**
     * [save 保存]
     * @return {[type]} [description]
     */
    save: function () {
      var _self = this;
      if (_self.selectedWorkflow == undefined) {
        Notify.error('提示', '请选择数据', false);
        return;
      }

      _self.windowChange(_self.selectedWorkflow.window);
      _self.clientChange(_self.selectedWorkflow.client);
      _self.bpmnChange(_self.selectedWorkflow.bpmnFileName);
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('workflowEditResource/saveWorkflowDto'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.selectedWorkflow),
        success: function (data) {
          _self.loading = false;
          _self.setSelectedWorkflow(data);
          Notify.success('保存成功', '数据保存成功', 1500);
          _self.refreshWorkflows();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * [sync 同步工作流信息]
     * @return {[type]} [description]
     */
    sync: function () {
      var _self = this;
      if (_self.selectedWorkflow == undefined) {
        Notify.error('提示', '请选择数据', false);
        return;
      }
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('workflowEditResource/syncWorkflowDto'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.selectedWorkflow),
        success: function (data) {
          _self.loading = false;
          _self.setSelectedWorkflow(data);
          Notify.success('同步成功', '数据同步成功', 1500);
          _self.refreshWorkflows();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
     * [deleteInstance 删除实例]
     * @return {[type]} [description]
     */
    deleteInstance: function () {
      var _self = this;
      if (_self.selectedWorkflow == undefined) {
        Notify.error('提示', '请选择数据', false);
        return;
      }
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('workflowEditResource/deleteWorkflowResource'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.selectedWorkflow),
        success: function (data) {
          _self.loading = false;
          Notify.success('删除实例成功', '数据删除成功', 1500);
          _self.refreshWorkflows();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * [processInstanceCount 流程实例数量]
     * @return {[type]} [description]
     */
    processInstanceCount: function () {
      var _self = this;
      if (_self.selectedWorkflow == undefined) {
        Notify.error('提示', '请选择数据', false);
        return;
      }
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('workflowEditResource/getProcessInstanceCount'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.selectedWorkflow),
        success: function (data) {
          _self.loading = false;
          Notify.success('流程实例数量：' + data, '', 1500);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    manualStartWorkflow: function () {
      var _self = this;
      if (_self.selectedWorkflow == undefined) {
        Notify.error('提示', '请选择数据', false);
        return;
      }
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('workflowEditResource/start'),
        type: 'post',
        dataType: 'text',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.selectedWorkflow),
        success: function (data) {
          _self.loading = false;
          Notify.success('提示', '手工启动流程成功', 1500);
          _self.refreshWorkflows();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    getTypeDisplayValue: function (workflow) {
      var _self = this;
      var type = workflow.workflowType;
      for (var i = 0, len = _self.workflowTypes.length; i < len; i++) {
        if (_self.workflowTypes[i].keyStr == type) {
          return _self.workflowTypes[i].value;
        }
      }
      return '';
    },

    /**
     * 编辑工作流
     * @param {Object} data
     */
    selectWorkflow: function (data, showModal) {
      var _self = this;

      if (showModal) {
        _self.modal = true;
      }

      if (data.clientId != undefined) {
        for (let i = 0, len = _self.clientOptions.length; i < len; i++) {
          if (_self.clientOptions[i].id == data.clientId) {
            data.client = _self.clientOptions[i];
            data.clientName = _self.clientOptions[i].name;
            break;
          }
        }
      } else {
        data.client = undefined;
        data.clientName = undefined;
      }

      if (data.windowNo != undefined) {
        for (let i = 0, len = _self.windowOptions.length; i < len; i++) {
          if (_self.windowOptions[i].keyStr == data.windowNo) {
            data.window = _self.windowOptions[i];
            data.windowName = _self.windowOptions[i].value;
            break;
          }
        }
      } else {
        data.window = undefined;
        data.windowName = undefined;
      }
      this.selectedWorkflow = data;
    },

    /**
     * 窗口选择发生改变
     */
    windowChange: function (val) {
      if (this.selectedWorkflow != undefined) {
        if (val != undefined) {
          this.selectedWorkflow.windowNo = val.keyStr;
          this.selectedWorkflow.windowName = val.value;
          this.selectedWorkflow.window = val;
          if (
            this.selectedWorkflow.name == null ||
            this.selectedWorkflow.name.length == 0
          ) {
            this.selectedWorkflow.name = val.value;
          }
        } else {
          this.selectedWorkflow.windowNo = undefined;
          this.selectedWorkflow.windowName = undefined;
          this.selectedWorkflow.window = undefined;
        }
      }
    },

    /**
     * 单位选择发生改变
     */
    clientChange: function (val) {
      if (this.selectedWorkflow != undefined) {
        if (val != undefined) {
          this.selectedWorkflow.clientId = val.id;
          this.selectedWorkflow.clientName = val.name;
          this.selectedWorkflow.client = val;
        } else {
          this.selectedWorkflow.clientId = undefined;
          this.selectedWorkflow.clientName = undefined;
          this.selectedWorkflow.client = undefined;
        }
      }
    },
    bpmnChange: function (val) {
      if (this.selectedWorkflow != undefined) {
        if (val != undefined) {
          this.selectedWorkflow.bpmnFileName = val.value;
        } else {
          this.selectedWorkflow.bpmnFileName = undefined;
        }
      }
    },
    deploymentChange: function (val) {
      if (this.selectedWorkflow != undefined) {
        if (val != undefined) {
          this.selectedWorkflow.deploymentId = val.deploymentId;
        } else {
          this.selectedWorkflow.deploymentId = undefined;
        }
      }
    },
    // 获取备份历史流程Sql
    getTableSql: function () {
      const _self = this;
      const url = 'api/MongoDBResource/getBackUpsTableSql';
      ajaxApiGet(url).then(
        success => {
          _self.tableSql = success;
          this.archiveVisible = true;
        },

        error => {
          if (error.status === 404) {
            _self.archiveVisible = false;
            Notify.error(
              '历史数据归档错误',
              '服务器未配置历史流程归档服务，请配置。',
              false,
            );
          } else {
            Common.processException(error);
          }
        },
      );
    },
    // 获取删除已归档历史表数据sql和清空待删除表sql
    getDeleteTableSql: function () {
      const _self = this;
      const url = 'api/MongoDBResource/getDeleteTableSql';
      ajaxApiGet(url).then(
        success => {
          _self.deleteTableSql = success;
        },
        error => {
          Common.processException(error);
        },
      );
    },

    // 执行归档
    archiveDatas: function () {
      const _self = this;
      const url = 'api/MongoDBResource/archiveHistoryData';
      _self.loading = true;
      ajaxApi(url).then(
        success => {
          _self.isNext = true;
          _self.archiveTotal = success;
          Notify.success('成功', '归档执行成功。', false);
          _self.loading = false;
        },
        error => {
          _self.loading = false;
          Common.processException(error);
        },
      );
    },

    // 复制文本(兼容http和https)
    copyText() {
      const _self = this;
      let text;
      if (_self.current === 0) {
        text = _self.tableSql;
      } else if (_self.current === 2) {
        text = _self.deleteTableSql;
      }
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard
          .writeText(text)
          .then(() => {
            if (_self.current === 0) {
              _self.isOk = true;
            } else if (_self.current === 2) {
              _self.isDeleteOk = true;
            }
            message.success('复制成功');
          })
          .catch(err => {
            console.error(err);
          });
      } else {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((resolve, reject) => {
          document.execCommand('copy')
            ? resolve()
            : reject(new Error('出错了'));
          textArea.remove();
        }).then(
          () => {
            if (_self.current === 0) {
              _self.isOk = true;
            } else if (_self.current === 2) {
              _self.isDeleteOk = true;
            }
            message.success('复制成功');
          },
          () => {
            console.log('复制失败');
          },
        );
      }
    },
  },
};
</script>

<style scoped>
.row {
  margin: 10px 0px;
}
.form-inline > .btn {
  margin-left: 8px;
}
.footerStyle {
  float: right;
}
.footerStyle > .btn {
  margin-right: 2px !important;
}
.steps-content,
.steps-action {
  margin-top: 10px;
}
.steps-action {
  display: flex;
  justify-content: space-between;
}
</style>