<template>
  <el-container
    class="fullheight"
    style="border: 1px solid #eee; position: relative"
  >
    <ht-aside-tree
      cat-id="6"
      @node-click="handleNodeClick"
      @delete="
        selectTypeIds = ''
        $refs.htTable.load()
      "
      @check="check"
    />

    <el-container>
      <el-main>
        <ht-table
          @load="loadData"
          @row-click="rowClick"
          :data="data"
          :pageResult="pageResult"
          :selection="true"
          quick-search-props="name,defKey,desc"
          ref="htTable"
          :show-export="false"
          :defaultSorter="[{property: 'createTime', direction: 'DESC'}]"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <!-- <el-button-group> -->
            <el-button
              size="small"
              @click="handleCommand({command: 'add'})"
              icon="el-icon-plus"
              type="primary"
              >新增</el-button
            >
            <el-button
              size="small"
              @click="
                importDialogVisible = true
                flowTypeSelectorCatId = ''
                flowTypeSelectorCatName = ''
              "
              icon="el-icon-download"
              >导入</el-button
            >
            <el-button
              size="small"
              @click="handExport"
              icon="el-icon-upload2"
              :disabled="isDisabled"
              >导出</el-button
            >
            <el-button
              @click="openTypeSetDialog()"
              :disabled="isDisabled"
              icon="icon-shezhifenlei"
              >设置分类</el-button
            >
            <el-button
              @click="batchGoLive()"
              :disabled="isDisabled"
              icon="el-icon-document-checked"
              >批量上线</el-button
            >
            <el-button
              @click="batchGoTest()"
              :disabled="isDisabled"
              icon="el-icon-document-delete"
              >批量测试</el-button
            >
            <el-button
              style="margin-left: 10px"
              icon="icon-application-delete"
              @click="batchDelete()"
              :disabled="isDisabled"
              >删除</el-button
            >
          <!--  <el-button size="small" @click="batchAddNode()" icon="el-icon-plus"
              >批量新增节点</el-button
            >
            <el-button type="danger" @click="batchDeleteNode()"
              >批量删除节点</el-button
            >-->
            <!-- </el-button-group> -->
          </template>

          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              prop="name"
              label="名称"
              :hiden="true"
              width="200"
              :show-overflow-tooltip="true"
              :sortable="true"
            >
              <template v-slot="{row}">
                <span v-if="!row.authorizeRight.m_edit">{{ row.name }}</span>
                <el-link
                  type="primary"
                  v-if="row.authorizeRight.m_edit"
                  @click="handleCommand({row: row, command: 'edit'})"
                  title="编辑流程"
                  >{{ row.name }}</el-link
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="defKey"
              label="流程key"
              width="100"
              :show-overflow-tooltip="true"
            />
            <ht-table-column
              prop="desc"
              label="流程描述"
              :show-overflow-tooltip="true"
              :sortable="true"
            />
            <ht-table-column
              prop="typeName"
              label="流程分类"
              hidden
              :show-overflow-tooltip="true"
              width="110"
              :sortable="true"
            />
            <ht-table-column
              prop="status"
              label="状态"
              width="100"
              :render-header="renderHeaderMethod"
              :filters="statusArray"
            >
              <template v-slot="{row}">
                <el-tag
                  v-show="row.status == s.value"
                  :type="s.type"
                  v-for="s in statusArray"
                  :key="s.value"
                  >{{ s.text }}</el-tag
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="testStatus"
              label="生产状态"
              width="110"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '测试', value: 'test'},
                {text: '正式', value: 'run'},
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="info" v-if="row.testStatus == 'test'"
                  >测试</el-tag
                >
                <el-tag type="danger" v-if="row.testStatus == 'run'"
                  >正式</el-tag
                >
              </template>
            </ht-table-column>
            <!-- <ht-table-column
              prop="designPattern"
              label="设计模式"
              width="100"
              :render-header="renderHeaderMethod"
              :filters="[
               // {text: '简易模式', value: 'simple'},
                {text: '正常模式', value: 'normal'},
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="info" v-if="row.designPattern == 'simple'"
                  >简易模式</el-tag
                >
                <el-tag type="danger" v-else>正常模式</el-tag>
              </template>
            </ht-table-column> -->
            <ht-table-column label="版本" width="200">
              <template v-slot="{row}">
                <el-tag
                  v-if="row.authorizeRight.m_edit"
                  type="info"
                  style="margin-left:10px;cursor:pointer"
                  class="version-tag"
                  title="查看表单主版本"
                  @click="handleCommand({row: row, command: 'mainEdit'})"
                >主版本:{{ row.mainVersion }}
                </el-tag>
                <el-tag
                  v-else
                  type="info"
                  style="margin-left:10px;color: dimgrey;"
                  class="version-tag"
                >主版本:{{ row.mainVersion }}
                </el-tag>
                <el-tag
                    style="margin-left:10px;cursor:pointer"
                    title="查看表单的所有版本"
                    class="version-tag"
                    @click="openDefVersion(row)"
                    type="info"
                >版本数量({{ row.versionCount }})</el-tag
                >
              </template>
            </ht-table-column>
            <ht-table-column width="200" label="操作" align="left">
              <template v-slot="{row}">
                <template v-if="row.status != 'draft'">
                  <el-button
                    type="text"
                    @click="
                      row.authorizeRight.m_start
                        ? handleCommand({row: row, command: 'startFlow'})
                        : handleCommand({row: row, command: 'bindRelation'})
                    "
                    >{{
                      row.authorizeRight.m_start ? '启动' : '绑定关系'
                    }}</el-button
                  >
                  <el-button v-if="row.testStatus != 'test'"
                    type="text"
                    @click="handleCommand({row: row, command: 'goTest'})"
                    >测试</el-button
                  >
                  <el-button
                    type="text" v-if="row.testStatus == 'test'"
                    @click="handleCommand({row: row, command: 'goLive'})"
                    >上线</el-button
                  >
                  <el-dropdown
                    size="mini"
                    class="more-operate-btn__dropdown"
                    @command="handleCommand"
                  >
                    <span class="more-operate-btn"
                      >更多操作<i class="el-icon-caret-bottom"></i>
                    </span>

                    <el-dropdown-menu
                      slot="dropdown"
                      class="operate-dropdown__button"
                    >
                      <el-dropdown-item
                        v-if="
                          row.authorizeRight.m_clean && row.testStatus == 'test'
                        "
                        :command="{row: row, command: 'cleanData'}"
                        >清除数据</el-dropdown-item
                      >
                      <el-dropdown-item 
                        type="text"
                        :command="{row: row, command: 'copy'}"
                        >复制</el-dropdown-item
                      >
                      <el-dropdown-item
                        v-if="row.authorizeRight.m_start"
                        :command="{row: row, command: 'bindRelation'}"
                        >绑定关系</el-dropdown-item
                      >
                      <el-dropdown-item
                        v-if="row.status == 'deploy'"
                        :command="{row: row, command: 'processSimulation'}"
                        size="mini"
                        >流程仿真配置</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="{row: row, command: 'auth'}"
                        size="mini"
                        >授权管理</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="{row: row, command: 'pcModulePublish'}"
                        size="mini"
                        >发布到PC应用模块</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="{row: row, command: 'mobileModulePublish'}"
                        size="mini"
                        v-if="row.supportMobile === 1"
                        >发布到移动端</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="{row: row, command: 'sysModulePublish'}"
                        size="mini"
                        >发布流程模块</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="{row: row, command: 'tagsSetting'}"
                        size="mini"
                        >设置标签</el-dropdown-item
                      >
                      <el-dropdown-item :command="{ row: row, command: 'showModifyLog' }"
                         size="mini">修改日志</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
                <el-button
                  v-if="row.status == 'draft'"
                  type="text"
                  @click="handleCommand({row: row, command: 'delete'})"
                  size="mini"
                  >删除</el-button
                >
              </template>
            </ht-table-column>
          </template>
        </ht-table>
      </el-main>
    </el-container>
    <ht-sidebar-dialog
      width="28%"
      title="绑定关系"
      :visible.sync="dialogVisible2"
      :before-close="handleClose"
    >
      <el-row>
        <el-col>
          PC表单实体对象：
          <span v-if="bindData.pcEnt">
            <el-tag
              style="margin-right: 5px; cursor: pointer"
              @click="handleClose"
            >
              <router-link
                :to="{path: 'businessObj', query: {id: bindData.pcEnt.id_}}"
                >{{ bindData.pcEnt.description_ }}</router-link
              >
            </el-tag>
          </span>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col>
          手机表单实体对象：
          <span v-if="bindData.mobileEnt">
            <el-tag
              style="margin-right: 5px; cursor: pointer"
              @click="handleClose"
            >
              <router-link
                :to="{
                  path: 'businessObj',
                  query: {id: bindData.mobileEnt.id_},
                }"
                >{{ bindData.mobileEnt.description_ }}</router-link
              >
            </el-tag>
          </span>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col>
          PC表单：
          <span v-if="bindData.pcForm">
            <el-tag style="margin-right: 5px" @click="handleClose">
              <router-link
                replace
                :to="{
                  path: 'formManager',
                  query: {
                    formId: bindData.pcForm.pcFormId,
                    defId: bindData.pcForm.pcDefId,
                  },
                }"
                >{{ bindData.pcForm.pcName }}</router-link
              >
            </el-tag>
          </span>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col>
          手机表单：
          <span v-if="bindData.mobileForm">
            <el-tag style="margin-right: 5px" @click="handleClose">
              <router-link
                replace
                :to="{
                  path: 'mobileFormManager',
                  query: {
                    formId: bindData.mobileForm.mobileFormId,
                    defId: bindData.mobileForm.mobileDefId,
                  },
                }"
                >{{ bindData.mobileForm.mobileName }}</router-link
              >
            </el-tag>
          </span>
        </el-col>
      </el-row>
    </ht-sidebar-dialog>

    <ht-sidebar-dialog
      width="100%"
      :close-on-click-modal="false"
      :visible="dialogVisible"
      :key="defConfComponetKey"
      :before-close="handleClose"
      :close-on-press-escape="false"
      class="flow_conf"
    >
      <el-container class="fullheight">
        <el-header height="48px" style="padding: 0">
          <!--   <Navigator /> -->
          <div class="title">
            <span class="title_icon" @click="handleClose">
              <i class="el-icon-back" style="font-weight: bold"></i
            ></span>
            <span class="title_tit">流程编辑({{ defNameAndVrsionTitle }})</span>
          </div>
          <!-- <div class="flex" style="
              float: left;
              justify-content: center;
              background: #fff;
              height: 47px;
              width: 180px;
              border-bottom: 1px solid #eee;

            ">
            <el-page-header @back="handleClose" content="流程编辑" title=""></el-page-header>
          </div>
          <div class="flex" style="
              float: left;
              justify-content: space-between;
              height: 47px;
              width: calc(100% - 181px);
              border-bottom: 1px solid #eee;
            ">
            <el-breadcrumb separator=">" style="margin-left: 20px">
              <el-breadcrumb-item :to="{ path: '/' }">流程设计</el-breadcrumb-item>
              <el-breadcrumb-item>{{
                defNameAndVrsionTitle
              }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div> -->
          <el-link class="bpmn-xml-link" @click="watchBPMNXML">
            <i class="icon-technology" />
            BPMNXML
          </el-link>
        </el-header>
        <el-main style="padding: 0; height: 100%; overflow: hidden">
          <el-tabs
            class="flow-edit-container"
            v-if="dialogVisible"
            type="card"
            style="height: 100%"
            tab-position="left"
            v-model="activeName"
            @tab-click="handlePaneClick"
            @tab-remove="handlePaneRemove"
            :before-leave="beforePanelLeave"
            ref="flowEditTables"
          >
            <el-tab-pane label="流程设计" name="defDesign">
              <BpmnEdit
                ref="BpmnEdit"
                :defId="curSelectDefId"
                :defKey="curSelectDefKey"
                :design-pattern="designPattern"
                :operateType="operateType"
                :processStatus="processStatus"
                @def-deploy-success="handleDefDeploySuccess"
                @switch-config-refresh="handleDefSignSuccess"
              />
            </el-tab-pane>

            <el-tab-pane
              v-if="!isShowSubFlowSet"
              label="流程配置"
              name="defConfig"
            >
              <keep-alive v-if="!flowConfigShouldRefresh">
                <FlowConfig
                  :defId="curSelectDefId"
                  @repeatQuest="repeatQuest"
                />
              </keep-alive>
              <FlowConfig
                v-else
                :defId="curSelectDefId"
                @repeatQuest="repeatQuest"
              />
            </el-tab-pane>
            <el-tab-pane
              label="流程配置"
              v-if="isShowSubFlowSet"
              name="defConfig"
            >
              <SubFlowConfig
                v-if="activeName == 'defConfig'"
                :defId="curSelectDefId"
              />
            </el-tab-pane>
            <el-tab-pane label="初始赋值" name="boSetting">
              <FlowEditBoSetting
                v-if="isCurDefPublish && activeName == 'boSetting'"
                :defId="curSelectDefId"
              />
            </el-tab-pane>
            <el-tab-pane label="变量管理" name="varManage">
              <FlowVarList
                v-if="isCurDefPublish && activeName == 'varManage'"
                :defId="curSelectDefId"
              />
            </el-tab-pane>
<!--            <el-tab-pane label="版本管理" name="versionManage">-->
<!--              <FlowVersionList-->
<!--                v-if="isCurDefPublish && activeName == 'versionManage'"-->
<!--                :defId="curSelectDefId"-->
<!--              />-->
<!--            </el-tab-pane>-->
            <el-tab-pane label="其它设置" name="otherSetting">
              <FlowOtherSetting
                v-if="isCurDefPublish && activeName == 'otherSetting'"
                :defId="curSelectDefId"
                @toggleTab="toggleTab"
              />
            </el-tab-pane>
            <el-tab-pane
              :closable="true"
              label="子流程设置"
              v-if="isShowSubFlowSet"
              name="subFlowSet"
            >
              <SubFlowConfig
                v-if="activeName == 'subFlowSet'"
                :defId="subDefId"
                :topDefKey="topDefKey"
              />
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </ht-sidebar-dialog>

    <el-dialog
      title="导入流程"
      :visible.sync="importDialogVisible"
      width="40%"
      top="30vh"
      :close-on-click-modal="false"
      v-if="importDialogVisible"
    >
      <div style="height: 150px; padding-left: 20px">
        <eip-sys-type-selector
          placeholder="请选择分类"
          type-key="FLOW_TYPE"
          v-model="flowTypeSelectorCatName"
          :sys-type-id.sync="flowTypeSelectorCatId"
          :validate="{required: true}"
        />
        <br /><br />
        <el-upload
          style="display: inline-block"
          :action="imporCheckUrl"
          :on-success="handleUploadResult"
          :on-error="handleUploadResult"
          :headers="uploadHeaders"
          :on-exceed="onExceed"
          accept=".zip"
          :before-upload="beforeUpload"
          :limit="1"
          :data="{isCheck: true}"
          :auto-upload="false"
          ref="upload"
        >
          <el-button size="small" icon="el-icon-upload">选择流程</el-button>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitImport"
          element-loading-text="拼命导入中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      width="60%"
      title="复制流程"
      :close-on-click-modal="false"
      :visible="dialogSaveCopyVisible"
      :before-close="handleCloseSaveCopy"
      :destroy-on-close="true"
    >
      <form v-form data-vv-scope="saveCopyForm">
        <table class="form-table" cellspacing="0" cellpadding="0" border="0">
          <tbody>
            <tr>
              <th width="140px">原流程名称:</th>
              <td>{{ flowRow.name }}</td>
              <th width="140px" class="is-required">新流程名称</th>
              <td>
                <ht-input v-model="newFlow.name" :validate="{required: true}" />
              </td>
            </tr>
            <tr>
              <th width="140px" class="is-required">原流程别名:</th>
              <td>{{ flowRow.defKey }}</td>
              <th width="140px" class="is-required">新流程别名</th>
              <td>
                <ht-input
                  v-model="newFlow.defKey"
                  v-pinyin="newFlow.name"
                  autocomplete="off"
                  :validate="{
                    required: true,
                    regex: {
                      exp: '^[^0-9][\\w]{1,29}$',
                      message: '只能输入字母开头的不超过30位的key',
                    },
                  }"
                  placeholder="请输入别名"
                ></ht-input>
              </td>
            </tr>
            <tr>
              <th width="140px" class="is-required">原流程分类:</th>
              <td>{{ flowRow.typeName }}</td>
              <th width="140px" class="is-required">新流程分类</th>
              <td>
                <EipSysTypeSelector
                  placeholder="请选择流程分类"
                  cat-id="6"
                  v-model="newFlow.typeName"
                  :sys-type-id.sync="newFlow.typeId"
                  :validate="{required: true}"
                />
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseSaveCopy">取消</el-button>
        <el-button type="primary" @click="saveCopy">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="流程版本管理"
        class="form-version__dialog"
        width="60%"
        destroy-on-close
        :visible.sync="bpmVersionVisible"
        :before-close="handleCloseFormVersion"
        top="8vh"
    >
      <FlowVersionList
          v-if="bpmVersionVisible"
          :defId="defId"
          :authorize-right = "authorizeRight"
          @design="design(arguments)"
      />
    </el-dialog>

    <el-dialog
      title="删除流程"
      :visible.sync="deleteDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      v-if="deleteDialogVisible"
      class="delete-dialog"
    >
      <h3 style="color: red">
        重要提醒：删除流程定义，对应的实例和任务会一起删除，并且无法恢复
      </h3>
      <div class="delete-dialog_container">
        <div v-for="def in deleteList" :key="def.defKey">
          {{ def.name }}(共有实例：{{ def.totalCount }}个，其中运行中的实例：{{
            def.runningCount
          }}个)&nbsp;&nbsp;<i
            class="el-icon-close"
            @click="deleteList.remove(def)"
          ></i>
        </div>
      </div>
      <el-input
        v-if="false"
        type="textarea"
        :rows="2"
        placeholder="请输入删除原因"
        v-model="deleteReason"
      >
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="batchDeleteConfirm"
          element-loading-text="删除中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确认删除</el-button
        >
      </span>
    </el-dialog>

    <eip-sys-type-dialog
      ref="typeSetDialog"
      name="typeSetDialog"
      :cat-id="'6'"
      @onConfirm="sysTypeDialogOnConfirm"
    />
    <processSimulation ref="processSimulation"></processSimulation>
    <!-- 授权管理  -->
    <def-authorize-page-dialog
      ref="defAuthorizePageDialog"
      name="defAuthorizePageDialog"
    ></def-authorize-page-dialog>
    <PcModulePublish ref="pcModulePublish" />
    <MobileModulePublish ref="mobileModulePublish" />
    <SysModulePublish ref="sysModulePublish" />
    <TagsSetting ref="tagsSetting" @reloadTable="reloadTable" />
    <!--  修改日志  -->
    <ModifyLog :title="'修改日志'" :showType="'bpmDef'" :defKey="curSelectDefKey" ref="modifyLog"/>
    <el-dialog
      title="删除节点"
      :visible.sync="nodeDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-input v-model="nodeName" placeholder="请输入节点名称"></el-input>
      <el-table
        :data="returnData.error"
        style="width: 100%"
        v-if="isReturn && returnData.error.length > 0"
      >
        <el-table-column prop="name" label="删除异常流程名"> </el-table-column>
        <el-table-column prop="defKey" label="流程KEY"> </el-table-column>
      </el-table>
      <el-table
        :data="returnData.noNode"
        style="width: 100%"
        v-if="isReturn && returnData.noNode.length > 0"
      >
        <el-table-column prop="name" label="不存在节点流程名">
        </el-table-column>
        <el-table-column prop="defKey" label="流程KEY"> </el-table-column>
      </el-table>
      <el-table
        :data="returnData.ok"
        style="width: 100%"
        v-if="isReturn && returnData.ok.length > 0"
      >
        <el-table-column prop="name" label="成功流程名"> </el-table-column>
        <el-table-column prop="defKey" label="流程KEY"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="nodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="nodeConfirm()" v-if="!isReturn"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="新增用户任务节点"
      :visible.sync="addNodeDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" label-width="130px" :model="addNode" :rules="rules">
        <el-form-item label="规则类型" prop="type">
          <el-radio v-model="addNode.type" label="1">节点之前</el-radio>
          <el-radio v-model="addNode.type" label="2"
            >节点之后</el-radio
          ></el-form-item
        >
        <el-form-item label="对应节点名称" prop="selectNode"
          ><el-input
            v-model="addNode.selectNode"
            prop="selectNode"
            placeholder="请输入对应节点名称"
          ></el-input
        ></el-form-item>
        <el-form-item label="新增节点名称" prop="nodeName">
          <el-input
            v-model="addNode.nodeName"
            placeholder="请输入节点名称"
          ></el-input
        ></el-form-item>
        <!-- <el-form-item label="新增节点key" prop="nodeKey"
          ><el-input
            v-model="addNode.nodeKey"
            placeholder="请输入节点key"
          ></el-input
        ></el-form-item> -->
        <el-form-item label="审批人"
          ><el-button
            icon="el-icon-circle-plus-outline"
            @click="setNodeUser()"
            type="text"
            >新增</el-button
          >
          <div
            class="alert-danger alert"
            v-if="!nodeUsers || nodeUsers.length == 0"
          >
            &nbsp;&nbsp;尚未配置节点人员，请添加人员设置
          </div>
          <div v-else class="alert">
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content="批次顺序由上至下增大，第一批次无法获取到审批人时才会获取下一个批次审批人信息。"
                placement="left"
              >
                <span class="control-label left-label">
                  <i class="el-icon-warning"></i>
                </span>
              </el-tooltip>

              {{ nodeUsers.description }}
            </div>
          </div>
        </el-form-item>
      </el-form>
      <el-table
        :data="returnData.error"
        style="width: 100%"
        v-if="isReturn && returnData.error.length > 0"
      >
        <el-table-column prop="name" label="新增异常流程名"> </el-table-column>
        <el-table-column prop="defKey" label="流程KEY"> </el-table-column>
        <el-table-column prop="errMsg" label="错误信息"> </el-table-column>
      </el-table>
      <el-table
        :data="returnData.noNode"
        style="width: 100%"
        v-if="isReturn && returnData.noNode.length > 0"
      >
        <el-table-column prop="name" label="不存在节点流程名">
        </el-table-column>
        <el-table-column prop="defKey" label="流程KEY"> </el-table-column>
      </el-table>
      <el-table
        :data="returnData.ok"
        style="width: 100%"
        v-if="isReturn && returnData.ok.length > 0"
      >
        <el-table-column prop="name" label="成功流程名"> </el-table-column>
        <el-table-column prop="defKey" label="流程KEY"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addNodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNodeConfirm('1')" v-if="!isReturn"
          >发布</el-button
        >
        <el-button type="primary" @click="addNodeConfirm('2')" v-if="!isReturn"
          >保存</el-button
        >
      </span>
    </el-dialog>
    <FlowNodeUserCondition
      @nodeUserConditionConfirm="nodeUserConditionConfirm"
      ref="flowNodeUserCondition"
      :paramNodes="paramNodes"
    />
  </el-container>
</template>

<script>
/* import Navigator from '@/views/Navigator.vue' */
import {mapState} from 'vuex'
import flow from '@/api/flow.js'
import BpmnEdit from '@/components/VueBpmn/BpmnEdit.vue'
import req from '@/request.js'
import utils from '@/hotent-ui-util.js'
const FlowNodeUserCondition = () =>
  import('@/components/flow/FlowNodeUserCondition.vue')
const htAsideTree = () => import('@/components/common/HtAsideTree.vue')
const FlowConfig = () => import('@/components/flow/FlowConfig.vue')
const SubFlowConfig = () => import('@/components/flow/FlowConfig.vue')
const FlowOtherSetting = () => import('@/components/flow/FlowOtherSetting.vue')
const FlowVarList = () => import('@/components/flow/FlowVarList.vue')
const FlowVersionList = () => import('@/components/flow/FlowVersionList.vue')
const eipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const FlowEditBoSetting = () =>
  import('@/components/flow/FlowEditBoSetting.vue')
const eipSysTypeDialog = () =>
  import('@/components/dialog/EipSysTypeDialog.vue')
const processSimulation = () =>
  import('@/views/flow/simulation/ProcessSimulation.vue')
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const defAuthorizePageDialog = () =>
  import('@/components/dialog/DefAuthorizePageDialog.vue')
const PcModulePublish = () => import('@/components/common/PcModulePublish.vue')
const MobileModulePublish = () =>
  import('@/components/common/MobileModulePublish.vue')
const SysModulePublish = () =>
  import('@/components/common/SysModulePublish.vue')
const TagsSetting = () => import('@/components/common/TagsSetting.vue')
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
import ModifyLog from '@/components/VueBpmn/BpmnModifyLog.vue'

export default {
  components: {
    FlowNodeUserCondition,
    BpmnEdit,
    /*   Navigator, */
    htAsideTree,
    FlowConfig,
    FlowOtherSetting,
    SubFlowConfig,
    FlowVarList,
    FlowVersionList,
    FlowEditBoSetting,
    eipSysTypeSelector,
    eipSysTypeDialog,
    processSimulation,
    EipSysTypeSelector,
    defAuthorizePageDialog,
    PcModulePublish,
    MobileModulePublish,
    SysModulePublish,
    TagsSetting,
    ModifyLog,
  },
  mixins: [tableHeaderFilter],
  data() {
    return {
      rules: {
        selectNode: [{required: true, message: '必填', trigger: 'blur'}],
        nodeKey: [
          {required: true, message: '必填', trigger: 'blur'},
          {
            pattern: '^[a-zA-Z][\\s\\S]{1,60}$',
            message: '字母开头字母数字下划线，最长60',
            trigger: 'blur',
          },
        ],
        nodeName: [{required: true, message: '必填', trigger: 'blur'}],
      },
      paramNodes: [],
      addNode: {
        selectNode: '',
        nodeKey: '',
        nodeName: '',
        type: '2',
      },
      nodeUsers: [],
      addNodeDialogVisible: false,
      isReturn: false,
      returnData: {error: [], noNode: [], ok: []},
      selectIds: [],
      nodeDialogVisible: false,
      nodeName: '',
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      dialogVisible: false,
      defEditTabComponent: [
        {alias: 'defConfig', name: '流程设计'},
        {alias: 'defVarList', name: '变量管理'},
      ],
      statusArray: [
        {text: '已发布', value: 'deploy', type: 'info'},
  
        {text: '禁用', value: 'forbidden', type: 'danger'},
        {text: '禁止实例', value: 'forbidden_instance', type: 'warning'},
      ],
      activeName: 'defConfig',
      curSelectDefId: '',
      curSelectDefKey: '',
      // 配置页面是否需要刷新缓存
      flowConfigShouldRefresh: false,
      topDefKey: '',
      subDefId: '',
      isShowSubFlowSet: false,
      isCurDefPublish: false,
      selectTypeIds: '',
      fullscreenLoading: false,
      importDialogVisible: false,
      flowTypeSelectorCatId: '',
      flowTypeSelectorCatName: '',
      startDef: '',
      defNameAndVrsionTitle: '',
      dialogVisible2: false,
      bindData: {},
      dialogSaveCopyVisible: false,
      newFlow: {},
      flowRow: {},
      deleteList: [],
      deleteDialogVisible: false,
      deleteReason: '111',
      defConfComponetKey: '',
      isDisabled: true,
      selectedList: [],
      operateType: '',
      processStatus: 'draft',
      designPattern: 'normal', // normal 正常模式  simple简易模式
      bpmVersionVisible: false,
      defId:'',
      authorizeRight: {}
    }
  },
  computed: mapState({
    isForbidden: function () {
      return [
        {text: '正常', value: '0', type: 'success'},
        {text: '挂起', value: '1', type: 'danger'},
      ]
    },
    deleteUrl: function () {
      return window.context.bpmModel + '/flow/def/v1'
    },
    uploadHeaders: function (mapState) {
      return {Authorization: 'Bearer ' + mapState.login.currentUser.token}
    },
    imporCheckUrl: function () {
      return (
        window.context.bpmModel +
        '/flow/def/v1/importCheck?typeId=' +
        this.flowTypeSelectorCatId
      )
    },
    account: (state) => state.login.currentUser.account,
    token: (state) => state.login.currentUser.token,
    frontUrl: function () {
      return `${window.context.front}/matter/startProcess?token=${this.token}`
    },
  }),
  mounted() {
    //数据建模-》查看绑定关系
    if (this.$route.query.bpmId) {
      this.isCurDefPublish = true
      this.curSelectDefId = this.$route.query.bpmId
      this.activeName = 'defDesign'
      this.dialogVisible = true
      this.$router.push('/defManager')
      this.handleDefSignSuccess()
    }
    this.$validator = this.$root.$validator
  },
  // 监听选中
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true,
    },
  },
  methods: {
    openDefVersion(row){
      this.authorizeRight = row.authorizeRight
      this.bpmVersionVisible = true
      this.defId = row.defId
    },
    handleCloseFormVersion() {
      this.bpmVersionVisible = false
      this.$refs.htTable.load()
    },
    setNodeUser() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let conf = {nodeId: this.addNode.nodeKey}
          this.paramNodes = [
            {
              name: this.addNode.nodeName,
              nodeId: this.addNode.nodeKey,
              type: 'userTask',
            },
          ]
          this.$nextTick(() => {
            this.$refs.flowNodeUserCondition.showDialog(conf)
          })
        } else {
          return false
        }
      })
    },
    nodeUserConditionConfirm(res) {
      let userJson = {}
      userJson[this.addNode.nodeKey] = []
      userJson[this.addNode.nodeKey].push(res)
      this.nodeUsers = res
      this.userJson = JSON.stringify(userJson)
    },
    addNodeConfirm(action) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let _this = this
          let obj = {
            nodeName: this.addNode.nodeName,
            nodeKey: this.addNode.nodeKey,
            defIds: this.selectIds.join(','),
            selectNode: this.addNode.selectNode,
            userJson: this.userJson,
            type: this.addNode.type,
            action: action,
          }
          this.$http
            .post(`${window.context.bpmRunTime}/flow/def/v1/batchAddNode`, obj)
            .then(function (resp) {
              _this.returnData = resp.data
              _this.isReturn = true
              _this.$refs.htTable.load()
            })
        } else {
          return
        }
      })
    },
    nodeConfirm() {
      let _this = this
      this.$http
        .get(
          `${window.context.bpmRunTime}/flow/def/v1/batchDeleteNode?nodeName=${
            this.nodeName
          }&defIds=${this.selectIds.join(',')}`
        )
        .then(function (resp) {
          _this.returnData = resp.data
          _this.isReturn = true
        })
    },
    batchAddNode() {
      this.isReturn = false
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      let defKeys = []

      for (let item of elTable.selection) {
        if (item.designPattern != 'simple') {
          this.$message.warning('此操作只适用于简易模式')
          return
        }
        defKeys.push(item['id'])
      }

      if (defKeys.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      this.selectIds = defKeys
      this.nodeName = ''
      this.addNodeDialogVisible = true
      // 随机生成节点id
      this.addNode.nodeKey = 'UserTask_' + utils.randomString(7)
    },
    batchDeleteNode() {
      this.isReturn = false
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      let defKeys = []

      for (let item of elTable.selection) {
        if (item.designPattern != 'simple') {
          this.$message.warning('此操作只适用于简易模式')
          return
        }
        defKeys.push(item['id'])
      }

      if (defKeys.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      this.selectIds = defKeys
      this.nodeName = ''
      this.nodeDialogVisible = true
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    reloadTable() {
      this.$refs.htTable.load()
    },
    rowClick(row) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    handleDefSignSuccess() {
      this.flowConfigShouldRefresh = true
      if (!this.curSelectDefId) {
        return
      }
      let this_ = this
      req
        .get('${bpmModel}/flow/def/v1/defGet?defId=' + this.curSelectDefId)
        .then(function (resp) {
          let data = resp.data
          if (data) {
            this_.processStatus = data.status
            this_.defNameAndVrsionTitle = data.name + '/版本' + data.version
          }
        })
    },
    handleDefDeploySuccess(id) {
      this.curSelectDefId = id
      this.isCurDefPublish = true
      this.defConfComponetKey = new Date().getTime()
      this.activeName = 'defConfig'
      this.handleDefSignSuccess()
    },
    //跳转指定选项卡
    toggleTab(name) {
      this.activeName = name
      this.flowConfigShouldRefresh = true
    },
    //启动流程
    startFlow(row) {
      this.startDef = row.id
      let url = `${this.frontUrl}&defId=${row.defId}`
      window.open(url, '_blank')
    },
    //获取url指定参数
    getQueryString(url, name) {
      var arrObj = url.split('?')
      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split('&')
        var arr
        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split('=')

          if (arr != null && arr[0] == name) {
            return arr[1]
          }
        }
        return null
      } else {
        return null
      }
    },
    handleUploadResult(response) {
      var height =
        (document.documentElement.clientHeight || document.body.clientHeight) *
          0.85 +
        'px'
      this.fullscreenLoading = false
      let this_ = this
      if (response.state) {
        this_.handleImportSuccess()
      } else {
        if (
          response.message &&
          response.message.indexOf('是否继续为其新增版本') > 0
        ) {
          this.$confirm(
            '<div style="overflow-x:hidden;overflow-y:auto ;max-height:' +
              height +
              '">' +
              response.message +
              '</div>',
            '提示',
            {
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'warning',
              closeOnClickModal: false,
            }
          )
            .then(() => {
              this_.fullscreenLoading = true
              req
                .post(
                  window.context.bpmModel +
                    '/flow/def/v1/importSave?cacheFileId=' +
                    response.value +
                    '&confirmImport=' +
                    true +
                    '&typeId=' +
                    this.flowTypeSelectorCatId
                )
                .then(function (resp) {
                  this_.fullscreenLoading = false
                  let data = resp.data
                  if (data.state) {
                    this_.handleImportSuccess()
                  }
                })
            })
            .catch(() => {
              req.post(
                window.context.bpmModel +
                  '/flow/def/v1/importSave?cacheFileId=' +
                  response.value +
                  '&confirmImport=' +
                  false
              )
              this_.importDialogVisible = false
              this.$refs.upload.clearFiles()
            })
        } else {
          this.$message.error(response.message || '流程导入失败')
        }
      }
    },
    handleImportSuccess() {
      this.$message.success('流程导入成功')
      this.importDialogVisible = false
      this.$refs.htTable.load()
      this.$refs.upload.clearFiles()
    },
    beforeUpload(file) {
      if (!file.name.endsWith('.zip')) {
        this.$message.warning('只能导入zip文件!')
        return false
      }
      this.imporActionUrl = this.imporCheckUrl
      this.fullscreenLoading = true
    },
    onExceed() {
      this.$message.warning('只能选择一个zip文件!')
    },
    submitImport() {
      if (
        !this.$refs.upload.uploadFiles ||
        this.$refs.upload.uploadFiles.length == 0
      ) {
        this.$message.warning('请选择要导入的流程!')
        return false
      }
      if (!this.flowTypeSelectorCatId) {
        this.$message.warning('请选择要导入的分类!')
        return false
      }
      this.$refs.upload.submit()
    },
    watchBPMNXML() {
      let url =
        window.context.bpmModel +
        '/flow/def/v1/bpmnXml?defId=' +
        this.curSelectDefId
      let tenantId = '-1'
      try {
        if (this.$store.state.login.currentUser.userAttrs.tenantId) {
          tenantId = this.$store.state.login.currentUser.userAttrs.tenantId
        }
      } catch (error) {}
      if (tenantId != '-1') {
        url = url + '&tenantId=' + tenantId
      }
      window.open(url, '_blank')
    },
    beforePanelLeave() {
      if (!this.isCurDefPublish) {
        this.$message.warning('流程还未发布,无法进行配置')
        return false
      }
    },
    handlePaneClick: function (data) {
      if (data.alias) {
        this.currentTabComponent = data.alias
      }
      //流程设计
      if (data.name == 'defConfig') {
        this.flowConfigShouldRefresh = false
      }
    },
    handlePaneRemove: function () {
      this.activeName = 'defConfig'
      this.flowConfigShouldRefresh = true
      this.isShowSubFlowSet = false
    },
    handleNodeClick(node) {
      if (node.id == '6') {
        this.selectTypeIds = ''
      } else {
        this.selectTypeIds = node.id
      }
      this.$refs.htTable.doQuickSearch()
    },
    check(data, checkObj) {
      this.selectTypeIds = checkObj.checkedKeys.join(',')
      this.$refs.htTable.load()
    },
    handleClose() {
      this.dialogVisible = false
      this.dialogVisible2 = false
      this.$refs.htTable.load(true)
      this.$emit('handleDefManagerClose',false)
    },
    handleCloseMenuPerm() {
      this.dialogVisibleMenuPerm = false
    },

    dialogCancel(dialogVisible) {
      this[dialogVisible] = false
    },
    loadData(param, cb) {
      param.querys = param.querys || []
      if (this.selectTypeIds) {
        let hasTypeQuery = false
        for (const query of param.querys) {
          if (query.property == 'typeId') {
            query.value = this.selectTypeIds
            hasTypeQuery = true
            break
          }
        }
        if (!hasTypeQuery) {
          param.querys.push({
            group: 'main',
            operation: 'IN',
            property: 'typeId',
            relation: 'AND',
            value: this.selectTypeIds,
          })
        }
      } else {
        param.querys = param.querys.filter((q) => {
          return q.property != 'typeId'
        })
      }
      flow
        .getDefPage(param)
        .then((response) => {
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total,
          }
        })
        .finally(() => cb())
    },
    design(params){
      this.handleCommand({row: params[0], command: 'edit'})
    },
    handleCommand(params) {
      console.log('params: ', params);
      this.operateType = params.command
      if (params.command == 'add') {
        this.processStatus = 'draft'
      } else {
        this.processStatus = params.row.status
      }
      switch (params.command) {
        case 'edit': //编辑
          this.curSelectDefId = params.row.defId
          this.curSelectDefKey = params.row.defKey
          this.defNameAndVrsionTitle =
            params.row.name + '/版本' + params.row.version
          if (params.row.status == 'draft') {
            this.isCurDefPublish = false
            this.activeName = 'defDesign'
          } else {
            this.isCurDefPublish = true
            this.activeName = 'defConfig'
          }
          this.isShowSubFlowSet = false
          this.dialogVisible = true
          break
        case 'mainEdit': //编辑
          this.curSelectDefId = params.row.mainId
          this.curSelectDefKey = params.row.defKey
          this.defNameAndVrsionTitle =
              params.row.name + '/版本' + params.row.mainVersion
          if (params.row.status == 'draft') {
            this.isCurDefPublish = false
            this.activeName = 'defDesign'
          } else {
            this.isCurDefPublish = true
            this.activeName = 'defConfig'
          }
          this.isShowSubFlowSet = false
          this.dialogVisible = true
          break
        case 'add': //新增
          this.designPattern = 'normal'
          this.curSelectDefId = ''
          this.activeName = 'defDesign'
          this.dialogVisible = true
          this.isCurDefPublish = false
          this.isShowSubFlowSet = false
          this.defNameAndVrsionTitle = ''
          break
        case 'addSimpleMode': //新增
          this.designPattern = 'simple'
          this.curSelectDefId = ''
          this.activeName = 'defDesign'
          this.dialogVisible = true
          this.isCurDefPublish = false
          this.isShowSubFlowSet = false
          this.defNameAndVrsionTitle = ''
          break
        case 'restore': //恢复
          break
        case 'isForbidden': //挂起/取消挂起
          this.forbiddenOrUnForbiddenInst(params)
          break
        case 'cleanData':
          this.cleanData(params.row.id)
          break
        case 'startFlow':
          this.startFlow(params.row)
          break
        case 'bindRelation':
          this.bindRelation(params.row.defId)
          break
        case 'delete':
          // if (params.row.status == 'draft') {
          this.deleteFlow(params.row.defId)
          // } else {
          //   this.batchDelete(params.row)
          // }
          break
        case 'processSimulation':
          this.$refs.processSimulation.showProcessSimulation(params.row.defKey)
          break
        case 'add': //新增
          this.curSelectDefId = ''
          this.activeName = 'defDesign'
          this.dialogVisible = true
          this.isCurDefPublish = false
          this.defNameAndVrsionTitle = ''
          break
        case 'restore': //恢复
          break
        case 'isForbidden': //挂起/取消挂起
          this.forbiddenOrUnForbiddenInst(params)
          break
        case 'cleanData':
          this.cleanData(params.row.id)
          break
        case 'startFlow':
          this.startFlow(params.row)
          break
        case 'bindRelation':
          this.bindRelation(params.row.defId)
          break
        case 'delete':
          this.deleteFlow(params.row.defId)
          break
        case 'processSimulation':
          this.$refs.processSimulation.showProcessSimulation(params.row.defKey)
          break
        case 'copy':
          this.copy(params.row)
          break
        case 'goLive':
          this.goLive(params.row)
          break
        case 'goTest':
          this.goTest(params.row)
          break
        case 'auth':
          this.auth(params.row)
          break
        case 'pcModulePublish':
          this.handlePcModule(params.row)
          break
        case 'mobileModulePublish':
          this.handleMobileModulePublish(params.row)
          break
        case 'sysModulePublish':
          this.handleSysModulePublish(params.row)
          break
        case 'tagsSetting':
          this.handleTagsSetting(params.row)
          break
        case 'showModifyLog':
          this.curSelectDefKey = params.row.defKey
          this.showRecords(params.row)
          break
        default:
          break
      }
    },
    auth(row) {
      this.$refs.defAuthorizePageDialog.showDialog(row)
    },
    copy(flow) {
      this.flowRow = {...flow}
      this.newFlow = {
        defId: this.flowRow.id,
        defKey: '',
        name: '',
        typeId: '',
      }
      this.dialogSaveCopyVisible = true
    },
    goLive(flow) {
      this.goRunOrTest(flow.defId, true, "上线")
    },
    goTest(flow){
      this.goRunOrTest(flow.defId, false, "测试")
    },
    batchGoLive(){
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let defIds = []
      for (let item of elTable.selection) {
        defIds.push(item['defId'])
      }
      if (defIds.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      this.goRunOrTest(defIds.join(','), true, '批量上线')
    },
    batchGoTest(){
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let defIds = []
      for (let item of elTable.selection) {
        defIds.push(item['defId'])
      }
      if (defIds.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      this.goRunOrTest(defIds.join(','), false, '批量测试')
    },
    goRunOrTest(defIds,isRun,message){
      const this_ = this
      req.get(window.context.bpmModel + '/flow/def/v1/goRunOrTest?defIds=' + defIds+'&isRun=' + isRun)
          .then(function (response) {
            let data = response.data
            if (data.state) {
              this_.$message.success(message + data.value)
              this_.$refs.htTable.load()
            } else {
              this_.$message.success(message + data.value)
            }
          })
    },
    handleCloseSaveCopy() {
      this.dialogSaveCopyVisible = false
    },
    saveCopy() {
      const this_ = this
      this.$validator.validateAll('saveCopyForm').then((result) => {
        if (result) {
          req.get(window.context.bpmModel + '/flow/def/v1/checkDefKey?defKey=' + this_.newFlow.defKey).then(resp =>{
            if(!resp.data.value){
              flow.copy(this_.newFlow).then((resp) => {
                if (resp.data.state) {
                  this_.dialogSaveCopyVisible = false
                  this_.$message.success(resp.data.message)
                  this_.$refs.htTable.load()
                }     
              })
            }else{
              this_.$message.error('流程key已存在')
            }
          })
        } else {
          this_.$message.error('表单校验不通过， 请完善信息')
        }
      })
    },
    bindRelation(defId) {
      this.dialogVisible2 = true
      flow.getBindRelation(defId).then((resp) => {
        this.bindData = resp.data
      })
    },
    cleanData(defId) {
      let this_ = this
      this.$confirm(
        '此操作会清除该流程所有的实例任务等数据，是否确认清除？',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          closeOnClickModal: false,
        }
      ).then(() => {
        req
          .post(
            window.context.bpmModel + '/flow/def/v1/cleanData?defId=' + defId
          )
          .then(function (response) {
            let data = response.data
            if (data.state) {
              this_.$message.success(data.message)
            } else {
              this_.$message.fail(data.message)
            }
          })
      })
    },
    deleteFlow(defId) {
      let this_ = this
      this.$confirm('删除后不可恢复，是否确定删除?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        closeOnClickModal: false,
      }).then(() => {
        req
          .remove(
            this_.deleteUrl + '/physicsRemoveAllVersionByIds?ids=' + defId
          )
          .then(function (response) {
            if (response.data && response.data.state) {
              this_.$message.success('删除成功')
              this_.$refs.htTable.load()
            }
          })
      })
    },
    handExport() {
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      if (elTable && elTable.selection && elTable.selection.length > 10) {
        this.$message.warning('因流程和表单相关数据较大，单次最多导出10条')
        return
      }

      let ids = []

      for (let item of elTable.selection) {
        ids.push(item['id'])
      }

      if (ids.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let url = `${window.context.bpmModel}/flow/def/v1/exportXml?bpmDefId=${ids}`
      req.download(url)
    },
    batchDelete() {
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      let defKeys = []

      for (let item of elTable.selection) {
        defKeys.push(item['defKey'])
      }

      if (defKeys.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let me_ = this
      this.$http
        .get(
          '${bpmRunTime}/runtime/instance/v1/getInstanceCountByDefKeys?defKeys=' +
            defKeys.join(',')
        )
        .then(function (resp) {
          if (resp.data) {
            let countMap = {}
            resp.data.forEach((d) => {
              countMap[d['PROC_DEF_KEY_']] = d
            })
            let list = []
            elTable.selection.forEach((s) => {
              s = JSON.parse(JSON.stringify(s))
              if (countMap[s.defKey]) {
                s.totalCount = countMap[s.defKey].totalCount
                s.runningCount = countMap[s.defKey].runningCount
              } else {
                s.totalCount = 0
                s.runningCount = 0
              }
              list.push(s)
            })
            me_.deleteList = list
            me_.deleteDialogVisible = true
            me_.deleteReason = ''
            return
          }
          me_.$message.error(resp.data.message)
        })
    },
    batchDeleteConfirm() {
      if (!this.deleteReason) {
        //this.$message.warning('请输入删除原因');
        //return
      }
      if (!this.deleteList || this.deleteList.length == 0) {
        this.$message.warning('删除的流程不能为空')
        return
      }
      let ids = []
      this.deleteList.forEach((e) => {
        ids.push(e.defId)
      })
      let this_ = this
      this.fullscreenLoading = true
      req
        .remove(
          '${bpmModel}/flow/def/v1/physicsRemoveAllVersionByIds?ids=' +
            ids.join(',')
        )
        .then(function (response) {
          if (response.data && response.data.state) {
            this_.$message.success('删除成功')
            this_.deleteDialogVisible = false
            this_.$refs.htTable.load()
          }
        })
        .finally(() => {
          this.fullscreenLoading = false
        })
    },
    //设置分类
    openTypeSetDialog() {
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      this.$refs.typeSetDialog.showDialog({})
    },
    sysTypeDialogOnConfirm(data) {
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      let id = []

      for (let item of elTable.selection) {
        id.push(item['id'])
      }
      let this_ = this
      this.$http
        .post('${bpmModel}/flow/def/v1/defSetCategory', {
          typeName: data.name,
          typeId: data.id,
          defIds: id.join(','),
        })
        .then(function (resp) {
          if (resp.data && resp.data.state) {
            this_.$message({message: resp.data.message, type: 'success'})
            setTimeout(function () {
              this_.$refs.htTable.load()
            }, 3000)

            return
          }
          this_.$message.error(resp.data.message)
        })
    },
    handlePcModule(row) {
      let data = {
        id: row.id,
        name: row.name,
        key: row.defKey,
      }
      this.$refs.pcModulePublish.showDialog(JSON.stringify(data), 8)
    },
    handleMobileModulePublish(row) {
      let {id, name} = row
      this.$refs.mobileModulePublish.showDialog(
        JSON.stringify({
          id,
          name,
        }),
        5
      )
    },
    handleSysModulePublish(row) {
      this.$refs.sysModulePublish.showDialog(row)
    },
    handleTagsSetting(row) {
      this.$refs.tagsSetting.showDialog(row)
    },
    repeatQuest() {
      this.$refs.BpmnEdit.getModelData()
    },
    /**
     * 展示查阅记录
     */
    showRecords(currentRow){
      this.$refs.modifyLog.showRecordDialog(currentRow, 'read');
    },
  },
  created() {
    let this_ = this
    this.$root.$on('set-sub-flow', function (data) {
      this_.activeName = ''
      this_.showSubFlowSet = false
      req
        .get(
          window.context.bpmModel +
            '/flow/def/v1/subFlowDetail?defId=' +
            data.defId +
            '&nodeId=' +
            data.nodeId
        )
        .then((response) => {
          let data = response.data
          this_.topDefKey = data.topDefKey
          this_.subDefId = data.defId
          this_.activeName = 'subFlowSet'
          this_.isShowSubFlowSet = true
        })
    })
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

div[aria-invalid='true'] {
  ::v-deep {
    .el-input__inner,
    .el-input__inner:focus {
      border-color: #f56c6c;
    }
  }
}

div.flow_conf {
  ::v-deep {
    & > .el-dialog {
      .el-dialog__header {
        display: none;
        height: 100%;
        padding: 0;
      }

      .el-dialog__body {
        height: 100%;
        padding: 0;
      }
    }
  }
}

.flow-edit-container {
  padding: 0 !important;

  ::v-deep {
    & > .el-tabs__header {
      width: 180px;
      background: #fff;
      border-right: 1px solid #eee;
      margin-right: 0;
    }
    .el-tabs__nav {
      border-bottom: none;
    }
    & > .el-tabs__content {
      height: calc(100% - 5px) !important;

      .el-tab-pane {
        height: 100%;
      }
    }

    .el-tabs__item {
      border: none !important;
      color: #666;
      font-weight: bold;
      margin: 5px 0;
      padding-left: 30px !important;
    }
    .is-left {
      .el-tabs__item.is-active {
        background: #f0f7ff !important;
        color: #409eff;
        position: relative;
        &::before {
          content: ' ';
          height: 100%;
          width: 2px;
          background: #409eff;
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
        }
      }
    }
  }
}

.bpmn-xml-link {
  position: fixed;
  bottom: 30px;
  left: 35px;
  z-index: 9999;

  ::v-deep {
    .el-link--inner {
      font-size: 13px;
      color: $--color-primary;

      i {
        font-size: 13px;
        font-weight: bold;
        color: $--color-primary;
      }
    }
  }
}

@media (max-width: 1366px) {
  /deep/ .search-container__col {
    flex-wrap: wrap;

    .el-button-group {
      margin-top: 10px;
    }
  }
}

.delete-dialog_container {
  height: 300px;
  padding-left: 20px;
  margin-bottom: 10px;
  overflow: auto;
}

.delete-dialog_container > div {
  font-weight: 500;
  font-size: 14px;
}

.delete-dialog_container /deep/ .el-icon-close {
  padding: 6px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
}

.delete-dialog /deep/ .el-dialog__body {
  padding: 0px 30px;
}

::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
}
.title {
  height: 48px;
  line-height: 48px;
  border-bottom: 1px solid #e6e6e6;

  &_icon {
    margin-left: 24px;
    margin-right: 10px;
    color: #409eff;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
  }
  &_tit {
    font-size: 16px;
    font-weight: bold;
    color: #222222;
  }
}
</style>
