<template>
  <div  v-loading="loading||detailLoading">
    <div class="drawer-head">
      <div class="cell-title">
          <p class="title">{{title}}</p>
      </div>
      <div class="cell-btn">
        <el-button type="primary" v-if="pListData && pListData.procInstId" @click="handleMonitor" icon="el-icon-data-line">流程监控</el-button>
        <el-button v-if="(editStatus || workflowStatus)" type="primary" @click="submitForm" icon="el-icon-finished">提交</el-button>
        <el-button v-if="editStatus && !pListData.procInstId" type="primary" @click="saveForm" icon="el-icon-check">暂存</el-button>
        <el-button v-if="editStatus && pListData.procInstId" type="danger" @click="deleteForm" icon="el-icon-close">撤销</el-button>
        <el-button @click="close" icon="el-icon-close">关闭</el-button>
      </div>
    </div>
    <template v-if="attributeModelBool('approve') && workflowStatus">
      <div class="divide double"></div><!--divide 分隔-->
      <div class="tboper">
        <div class="tit"> {{submitLabel}}</div>
      </div><!--tboper 标题与操作按钮-->
      <div class="el-form-border">
        <el-form>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="submitLabel+'结论:'" prop="pass">
                <el-radio-group v-model.trim="formSubmit.pass" @change="passChange">
                  <el-radio
                    v-for="dict in passoptions"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="24">
              <el-form-item :label="submitLabel+'意见:'">
                <el-input
                  v-model="formSubmit.summary"
                  type="textarea"
                  :placeholder="'请输入'+submitLabel+'意见'"
                  maxlength="200"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                  :style="{ width: '100%' }"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </template>

    <div class="divide double"></div><!--divide 分隔-->
    <div class="tboper">
      <div class="tit">工具信息</div>
    </div>
    <div class="el-form-border">
      <el-form ref="eForm" :model="form" :rules="rules" label-width="150px">
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="编号" prop="toolCode">
                <el-input v-if="editStatus" v-model="form.toolCode" placeholder="请输入编号"/>
                <span v-else>{{form.toolCode}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中文别名" prop="toolName">
                <el-input v-if="editStatus" v-model="form.toolName" placeholder="请输入中文别名"/>
                <span v-else>{{form.toolName}}</span>
              </el-form-item>
            </el-col>
          </el-row>
<!--          <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="toolPrincipals">
              <el-input v-if="editStatus" v-model="form.toolPrincipalsName" placeholder="请选择负责人"
                        maxlength="11" @focus="toolPrincipalsChoose = true"/>
              <span v-else>{{form.toolPrincipalsName}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="toolRespDept">
              <treeselect :disabled="!editStatus" v-model="form.toolRespDept" :options="deptOptions"
                          :multiple="false"
                          :disable-branch-nodes="true" noOptionsText="暂无数据"
                          noChildrenText="没有子选项" noResultsText="没有匹配的结果"
                          @select="handleSelectNode" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>

        </el-row>-->
          <el-row>
            <el-col :span="12">
              <el-form-item label="来源" prop="toolSource">
                <el-select v-if="editStatus" v-model="form.toolSource" placeholder="请选择工具来源" style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.tool_source"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
                <dict-tag v-else :options="dict.type.tool_source" :value="form.toolSource"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用途" prop="toolUse">
                <el-input v-if="editStatus" v-model="form.toolUse" placeholder="请输入工具用途" />
                <span v-else>{{form.toolUse}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="类别" prop="toolType">
                <el-select v-if="editStatus" v-model="form.toolType" placeholder="请选择工具类别" style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.tool_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
                <dict-tag v-else :options="dict.type.tool_type" :value="form.toolType"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="形态" prop="status">
                <el-radio-group v-model="form.status" v-if="editStatus">
                  <el-radio
                    v-for="dict in dict.type.tool_status"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
                <dict-tag v-else :options="dict.type.tool_status" :value="form.status"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="加密方式" prop="encryptionMode">
                <el-input v-if="editStatus" v-model="form.encryptionMode" placeholder="请输入加密方式"/>
                <span v-else>{{form.encryptionMode}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务时间" prop="serviceTime">
                <el-input v-if="editStatus" v-model="form.serviceTime" placeholder="请输入服务时间"/>
                <span v-else>{{form.serviceTime}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input v-if="editStatus" v-model="form.contactPerson" placeholder="请输入联系人"/>
                <span v-else>{{form.contactPerson}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contactPhone">
                <el-input v-if="editStatus" v-model="form.contactPhone" maxlength="11" placeholder="请输入联系方式"/>
                <span v-else>{{form.contactPhone}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="负责人" prop="toolPrincipals">
                <el-input v-if="editStatus" v-model="form.toolPrincipalsName" placeholder="请选择负责人" maxlength="11" @focus="toolPrincipalsChoose = true"/>
                <span v-else>{{form.toolPrincipalsName}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属单位">
                {{userInfo.dept.deptName}}
                <!--                <treeselect :disabled="!editStatus" v-model="form.toolRespDept" :options="deptOptions" @select="handleSelectNode" :show-count="true" placeholder="请选择归属部门" />-->
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="测评机构" prop="testSituation">
                <el-input :readonly="!editStatus" v-model="form.testSituation" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="功能简介" prop="functionDesc">
                <el-input :readonly="!editStatus" v-model="form.functionDesc" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="适用条件" prop="applyCondition">
                <el-input :readonly="!editStatus" v-model="form.applyCondition" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="操作说明" prop="operateExplain">
                <el-input :readonly="!editStatus" v-model="form.operateExplain" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input :readonly="!editStatus" v-model="form.remark" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="关联工具" prop="association">
<!--                <el-button type="primary" icon="el-icon-search" size="mini" @click="getToolRelationTree">查看</el-button>
                <el-button type="primary" icon="el-icon-check" size="mini" @click="handleToolSelect">新增关联工具</el-button>
                <el-button type="primary" icon="el-icon-edit" size="mini"  @click="handleToolEdit">编辑关联工具</el-button>-->
                <el-select
                  :disabled="!editStatus"
                  v-model="form.association"
                  ref="selectHeadTool"
                  value-key="toolId"
                  multiple
                  filterable
                  remote
                  placeholder="请选择关联工具"
                  @focus="toolSelect">
                  <el-option
                    v-for="item in form.association"
                    :key="item.toolId"
                    :label="item.toolName"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!-- 上传 -->
      <add-doc :show.sync="addDocShow" ref="addDocRef" @addFileData="addFileData"/>
    </div><!--el-form-border 表单-->

    <div class="divide double"></div><!--divide 分隔-->
    <div class="tboper">
      <div class="tit">关联附件</div>
    </div>
    <div class="el-form-border">
      <div class="operate">
<!--        <el-form-item label="文件" required>
        </el-form-item>
        <el-button type="primary" icon="el-icon-upload2" v-if="editStatus" @click="handleDocAdd">上传</el-button>-->
        <template v-if="editStatus">
          <uploadVue
            :display="editStatus"
            :uploadUrl="uploadFileUrl"
            :type="['.txt','.doc','.docx','.pdf','.mp4','.webm','.zip','.rar','.png','.jpg','.jpeg']"
            :acceptType="acceptType"
            :isMultiple="true"
            :dataFile="dataFile"
            :isDetail="detailBoolean"
            ref="uploadFile"
            @handleSuccess="handleUploadSuccess"
            @handleError="handleUploadError"
          />
        </template>
        <!--            <el-button icon="el-icon-delete">删除</el-button>-->
      </div><!--operate 操作按钮-->
      <el-table :data="paginatedData" style="width: 100%" v-loading="previewLoading" element-loading-text="预览转换中，请耐心等待">
        <!--            <el-table-column type="selection" width="50" align="center"> </el-table-column>-->
        <el-table-column label="序号" width="60" align="center" type="index"></el-table-column>
        <el-table-column label="附件名称" prop="fileName" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope" v-if="scope.row.roleId !== 1">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              v-if="previewAuth(scope.row)"
              @click="handlePreview(scope.row)"
            >预览</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="editStatus"
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-button type="text" icon="el-icon-download"  v-if="isShowOperation(scope.row)" @click="handleDownload(scope.row)" v-loading="loadingDownload">下载</el-button>
          </template>
        </el-table-column>
      </el-table><!--el-table-->
      <!-- 分页组件 -->
      <el-pagination
        v-show="total > 0"
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :total="total"
        @current-change="handlePageChange"
        layout="total, prev, pager, next"
      />
    </div>

    <!-- 流程选择下一环节及人员  开始 -->
    <el-dialog
      title="选择下一环节及人员"
      v-if="dialogVisible" :visible.sync="dialogVisible"
      width="60%"
      append-to-body
      v-loading = flowStepLoading
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <processcode
        ref="prochild"
        :searchQuery="searchQuery"
        :pListData="pListData"
        :isSummary="isSummary"
      ></processcode>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleWorkflowSubmit">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 流程选择下一环节及人员  结束 -->
    <monitor-drawer
      v-if="monitorDrawerVisible"
      ref="monitorDrawer"
    ></monitor-drawer>
    <tool-selector ref="toolSelect" @selectHandle="selectHandle" :toolData="form.association"></tool-selector>
    <bl-user-selector  ref="peopleSelect" :type="'single'" :isCheck="true" :open="toolPrincipalsChoose" :deptFilter="true" @cancel="toolPrincipalsChoose=false" @submit="submitPeople"></bl-user-selector>

    <preview-util v-if="isPreviewDisable" ref="previewForm" @previewClose="previewClose" @previewLoadingClose="previewLoadingClose"></preview-util>

    <el-dialog :title="viewDialogTitle" :visible.sync="viewDialogOpen" fullscreen width="500px" append-to-body :before-close="handleBeforeClose">
      <i-frame :src="previewUrl" v-if="viewDialogOpen"/>
    </el-dialog>


    <!-- 关联工具展示 -->
    <el-dialog title="编辑关联工具" :visible.sync="editToolVisible"  width="980px" append-to-body :close-on-press-escape="false" :close-on-click-modal="false"
               :show-close="false" :wrapperClosable="false">
      <el-table
        :data="relationToolData"
        border
        ref="multipleTable"
        header-align="left"
      >
        <el-table-column label="序号" width="60" type="index" align="center"></el-table-column>
        <el-table-column label="编号"  key="toolCode" prop="toolCode"/>
        <el-table-column label="中文别名"  key="toolName" prop="toolName":show-overflow-tooltip="true" />
        <el-table-column label="操作" width="100px" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="selectDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        v-show="relationToolTotal > 0"
        :current-page.sync="currentToolPage"
        :page-size.sync="pageToolSize"
        :total="relationToolTotal"
        @current-change="handlePageToolChange"
        layout="total, prev, pager, next"
      />
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="editToolVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 关联工具展示 -->
    <el-dialog title="关联工具" :visible.sync="toolTreeVisible"  width="980px" append-to-body :close-on-press-escape="false" :close-on-click-modal="false"
               :show-close="false" :wrapperClosable="false" v-loading="toolTreeLoading">
      <el-tree :data="toolRelationOptions" :props="defaultProps" @node-click="handleToolNodeClick"></el-tree>
      <!--      <el-table
              :data="relationToolData"
              border
              ref="multipleTable"
              header-align="left"
            >
              <el-table-column label="序号" width="60" type="index" align="center"></el-table-column>
              <el-table-column label="工具编号"  key="toolCode" prop="toolCode"/>
              <el-table-column label="工具名称"  key="toolName" prop="toolName":show-overflow-tooltip="true" />
              <el-table-column label="操作" width="100px" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="selectDelete(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            &lt;!&ndash; 分页组件 &ndash;&gt;
            <el-pagination
              v-show="relationToolTotal > 0"
              :current-page.sync="currentToolPage"
              :page-size.sync="pageToolSize"
              :total="relationToolTotal"
              @current-change="handlePageToolChange"
              layout="total, prev, pager, next"
            />-->
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="toolTreeVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import iFrame from "@/components/iFrame/index"
import { listAttachment } from "@/api/attachment/attachment";
import processcode from "@/views/workflowList/processcode/index.vue";
import {
  workflowprocesskey,
  getStartActdef,
  getExtAttributeModel,
  procInstInfoAndStatus,
} from '@/api/my_business/workflow'
import WorkflowLogs from '@/views/workflowList/workflowLogs/index.vue'
import AddDoc from '@/views/tool/AddDoc.vue'
import Treeselect from '@riophae/vue-treeselect'
import { addUser, deptTreeSelect, updateUser } from '@/api/system/user'
import { addTool, checkToolExist, getInfoByBpmcId, updateTool } from '@/api/tool/tool'
import { getDataThree } from '@/api/tool/toolRelation'
import blUserSelector from '@/components/user-selector/src/user-selector.vue'
import ToolSelector from '@/components/tool-selector/index.vue'
import uploadVue from '@/components/FileUpload/optimizeToolUpload.vue'
import { addCount } from "@/api/tool/downloadCount";
import previewUtil from '@/components/PreviewUtil/previewUtil.vue'
import store from '@/store'

// PDF本地文件预览
export default {
  dicts: ['sys_normal_disable','tool_type', 'tool_source', 'tool_status', 'doc_source','doc_class'],
  components: {
    ToolSelector,
    blUserSelector,
    Treeselect, AddDoc,
    WorkflowLogs,
    processcode,
    iFrame,
    uploadVue,
    previewUtil
  },
  name: "Borrow_doc",
  props: ['data'],
  data() {
    let validatorToolExist = (rule, value, callback) => {
      let _this = this
      if (_this.editStatus&&_this.form.toolCode&&_this.form.toolRespDept) {
        checkToolExist({toolId:_this.form.toolId,toolCode:_this.form.toolCode,toolRespDept:_this.form.toolRespDept}).then((response) => {
          if (response.data) {
            callback(new Error(_this.userInfo.dept.deptName+"下已存在编号为"+_this.form.toolCode+'的工具，请勿重复添加！'))
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    return {
      toolPrincipalsChoose: false,
      addDocShow: false,
      attQueryParams: {
        pageNum: 1,
        pageSize: 99999,
      },
      defaultStaff: [],
      yes: 'Y',
      searchQuery: {},
      deptList: [],
      companyList: [],
      deptOptions: [],
      docClassList: [],
      submitLabel:undefined,
      passoptions: [
        { value: true, label: "通过" },
        { value: false, label: "不通过" },
      ],
      formSubmit: { summary: "通过", actionType: "", pass: true },
      isSummary: false,
      activeName: "info",
      nodeDetail: [],
      procDefKey: undefined,
      viewId: "",
      userInfo: this.$store.getters.userInfo,
      viewShow: false,
      monitorDrawerVisible:false,
      form: {
        toolRespDept: this.$store.getters.userInfo.deptId,
        status: "zy",
        association: []
      },
      rules: {
        toolCode: [
          { required: true, message: "编号不能为空", trigger: "blur" },
          { min: 2, max: 30, message: '编号长度必须介于 2 和 30 之间', trigger: 'blur' },
          { validator: validatorToolExist, trigger: "blur" },
        ],
        toolName: [
          { max: 50, message: '中文别名不能超过50个字', trigger: 'blur' }
        ],
        toolPrincipals: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        toolRespDept: [
          { required: true, message: "请选择归属单位", trigger: ['blur','change'] }
        ],
        toolSource: [
          { required: true, message: "请选择来源", trigger: "change" }
        ],
        toolType: [
          { required: true, message: "请选择类别", trigger: "change" }
        ],
        toolUse: [
          { required: true, message: "请输入用途", trigger: "blur" },
          { max: 50, message: '用途不能超过50个字', trigger: 'blur' }
        ],
        testSituation: [
          { required: true, message: "请输入测评机构", trigger: "blur" },
        ],
        functionDesc: [
          { required: true, message: "请输入功能简介", trigger: "blur" },
        ],
        applyCondition: [
          { required: true, message: "请输入适用条件", trigger: "blur" },
        ],
        operateExplain: [
          { required: true, message: "请输入操作说明", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择形态", trigger: "change" },
        ],
        encryptionMode: [
          { required: true, message: "请输入加密方式", trigger: "blur" },
          { max: 50, message: '加密方式不能超过50个字', trigger: 'blur' }
        ],
        serviceTime: [
          { required: true, message: "请输入服务时间", trigger: "blur" },
          { max: 50, message: '服务时间不能超过50个字', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: "请输入联系人", trigger: "blur" },
          { max: 50, message: '联系人不能超过50个字', trigger: 'blur' }
        ],
        contactPhone: [
          {required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码'}
        ],
      },
      kuozhanshuju: {},
      kuozhanshujuBool: {},
      kuozhanshujuLabel: {},
      pListData: {},
      editStatus:false,
      workflowStatus: false,
      dialogVisible: false,
      loading: false,
      detailLoading: false,
      flowStepLoading : false,
      // 默认密码
      initPassword: undefined,
      viewDialogTitle: "",
      viewDialogOpen: false,
      previewUrl: '',
      loadingDownload: false,
      //当前部门
      curDeptId: null,
      curDeptName: null,

      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      acceptType: ".txt,.docx,.pdf,.mp4,.webm,.zip,.rar,.png,.jpg",
      dataFile: [],
      detailBoolean: false,
      attachmentList: [],
      attFileType: "zip,rar,7z",
      isPreviewDisable: false,
      title: '工具发布',
      currentPage: 1,     // 当前页
      pageSize: 10,       // 每页显示数量
      previewLoading: false,
      editToolVisible: false,
      //编辑
      currentToolPage: 1,     // 当前页
      pageToolSize: 10,       // 每页显示数量
      //工具树显示
      toolTreeVisible: false,
      toolTreeLoading: false,
      toolDataList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //工具关系选择项
      toolRelationOptions: [],

    };
  },
  computed: {
    // 分页后的数据
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.attachmentList.slice(start, end);
    },
    // 总数据条数
    total() {
      return this.attachmentList.length;
    },
    // 分页后的数据
    relationToolData() {
      const start = (this.currentToolPage - 1) * this.pageToolSize;
      const end = this.currentToolPage * this.pageToolSize;
      return this.form.association.slice(start, end);
    },
    // 总数据条数
    relationToolTotal() {
      return this.form.association.length;
    },
  },
  watch: {
    data (val) {
      if (val) {
        this.init(val)
      }
    },
  },
  mounted() {
    this.curDeptId = this.$store.getters.userInfo.deptId
    this.curDeptName = this.$store.getters.userInfo.dept.deptName
    if (this.data) {
      if(this.data.title){
        this.title = this.data.title
      }
      this.init(this.data)
    }
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
    this.getDeptTree()
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    async init(row) {
      let _this = this
      _this.rest()
      _this.loading = true
      _this.procDefKey = 'Process_FHXOQXVP'
      _this.form.type = row.type
      //是否编辑模式
      _this.$nextTick(() => {
        if (row && row.procInstId) {
          let procInstId = row.procInstId
          _this.workflowStatus = row.status == '1'
          _this.procInstInfoAndStatus(procInstId)
          _this.getDetail(procInstId)
        } else {
          _this.workflowStatus = true
          _this.loading = false
          _this.editStatus = true
          _this.getWorkflowprocesskey();
        }
      });
    },
    getDetail(procInstId) {
      let _this = this
      _this.detailLoading = true
      getInfoByBpmcId(procInstId).then(async (res) => {
        let formData = res.data;
        formData.type = _this.form.type
        // _this.attachmentList = formData.attachmentList
        formData.association = JSON.parse(res.data.association)
        _this.form = formData
        _this.getAttachmentList(res.data.toolId)
      }).finally(()=>{
        _this.detailLoading = false
      });
    },
    rest(){
      let _this = this
      _this.activeName = "info"
    },
    procInstInfoAndStatus(procInstId){
      let _this = this
      procInstInfoAndStatus(procInstId).then((res) => {
        if (res) {
          _this.pListData = res
        }else {
          _this.pListData = {procInstId:procInstId}
        }
        _this.getExtAttributeModel()
      });
    },
    getWorkflowprocesskey() {
      let _this = this
      _this.loading = true
      _this.pListData = {}
      if (_this.procDefKey) {
        workflowprocesskey(_this.procDefKey).then((data) => {
          getStartActdef(data.data.procDefId).then((res) => {
            _this.pListData = res.data;
            this.getExtAttributeModel()
          });
        });
      }else {
        _this.$message.warning("该文件类型尚未进行流程设置，将无法发起流程！");
      }
    },
    getExtAttributeModel(){
      let _this = this
      let procDefId = _this.pListData.procDefId
      let curActDefId = _this.pListData.curActDefId || _this.pListData.actDefId
      if (procDefId&&curActDefId) {
        getExtAttributeModel(
          procDefId,
          curActDefId
        ).then((res) => {
          let kuozhanshujuBool = {}
          let kuozhanshuju = {}
          let kuozhanshujuLabel = {}
          res.data.forEach(item=>{
            kuozhanshujuLabel[item.objKey] = item.objName
            if (item.objType==='Boolean') {
              kuozhanshujuBool[item.objKey] = item.objValue
            } else {
              kuozhanshuju[item.objKey] = item.objValue
            }
          })
          _this.kuozhanshujuBool = kuozhanshujuBool;
          _this.kuozhanshuju = kuozhanshuju;
          _this.kuozhanshujuLabel = kuozhanshujuLabel;
          _this.editStatus =_this.attributeModelBool('edit')&&_this.workflowStatus
          _this.submitLabel = _this.attributeModelLabel('approve')
        }).finally(()=>{
          _this.loading = false
        });
      }else {
        _this.kuozhanshujuBool = {}
        _this.kuozhanshuju = {}
        _this.loading = false
      }
    },
    attributeModelBool(val){
      if (this.kuozhanshujuBool&&this.kuozhanshujuBool!=={}) {
        let obj = this.kuozhanshujuBool[val]
        return obj?obj==='true':false
      }else {
        return false
      }
    },
    attributeModel(val){
      return this.kuozhanshuju[val]
    },
    attributeModelLabel(val){
      return this.kuozhanshujuLabel[val]
    },
    close() {
      this.viewShow = false;
      this.$emit("close")
    },
    //不需要验证必填的保存
    saveForm() {
      let _this = this
      _this.$refs["eForm"].validate(valid => {
        if(_this.attachmentList.length == 0){
          _this.$message.warning("最少上传一个附件");
          return;
        }
        if (valid) {
          if (!_this.procDefKey) {
            _this.$message.warning("尚未进行流程设置，将无法发起流程！");
            return;
          }
          _this.loading = true
          let formData = JSON.parse(JSON.stringify(_this.form))
          formData.recordStatus = "draft";
          formData.editStatus = _this.editStatus
          formData.association = JSON.stringify(_this.form.association)
          formData.toolRespDept = _this.userInfo.dept.deptId
          if (formData.toolId) {
            this.$set(formData,'attachmentList',_this.attachmentList)
            updateTool(formData).then((res) => {
              if (res.code===200) {
                _this.$message({
                  message: '保存成功',//提示的信息
                  type:'success',　　//类型是成功
                  duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
                });
              }
            }).finally(()=>{
              _this.loading = false
            });
          } else {
            let wf_receivers = [];
            wf_receivers.push({
              receiveUserId: _this.userInfo.userName,
              receiveUserOrgId: _this.userInfo.deptId
            });
            let wf_procTitle = "【工具发布】" + (formData.toolName?formData.toolName:"")
            formData.bpmClientInputModel = {
              model: {
                wf_procDefId: _this.pListData.procDefId,
                wf_procDefKey: _this.procDefKey,
                wf_procTitle: wf_procTitle,
                wf_sendUserId: _this.userInfo.userName,
                wf_sendUserOrgId: _this.userInfo.deptId,
                wf_receivers: wf_receivers,
                wf_curActDefName: _this.pListData.actDefName,
                wf_curActDefId: _this.pListData.actDefId,
                wf_nextActDefName: _this.pListData.actDefName,
                wf_nextActDefId: _this.pListData.actDefId,
              },
              type: formData.type,
              review: _this.attributeModelBool('approve'),
            };
            formData.editStatus = _this.editStatus
            this.$set(formData,'attachmentList',_this.attachmentList)
            addTool(formData).then((res) => {
              if (res.code===200) {
                _this.form.toolId = res.data.businessKey;
                _this.procInstInfoAndStatus(res.data.procInstId)
                _this.$message({
                  message: '保存成功',//提示的信息
                  type:'success',　　//类型是成功
                  duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
                });
              }
            }).finally(()=>{
              _this.loading = false
            });
          }
        }
      });
    },
    deleteForm(){
      let _this = this
      _this.$modal.confirm('该流程待办任务将会被撤销，请谨慎操作。是否确认执行？')
        .then(()=> {
          _this.loading = true
          let formData = {
            toolId: _this.form.toolId,
            bpmClientInputModel: {
              model: {
                wf_procInstId: _this.pListData.procInstId,
                wf_sendUserId: _this.userInfo.userName,
                wf_sendUserOrgId: _this.userInfo.deptId,
              },
            },
            review: false,
            recordStatus: 'cancel',
            editStatus: false
          }
          addTool(formData).then((res) => {
            if (res.code === 200) {
              this.$modal.msgSuccess("撤销成功");
              this.close(true);
            }
          });
        })
    },
    // 提交
    async submitForm() {
      let _this = this
      // 首先页签调整为 信息内容
      _this.activeName = 'info'
      if (!_this.procDefKey) {
        _this.$message.warning("尚未进行流程设置，将无法发起流程！");
        return;
      }
      let dialogVisible = true
      //审核
      if (_this.attributeModelBool('approve')) {
        if (_this.formSubmit.pass==='') {
          _this.$modal.msgError(_this.submitLabel+"结论不能为空！");
          return true;
        } else if (!_this.formSubmit.pass&&!_this.formSubmit.summary) {
          _this.$modal.msgError("请填写"+_this.submitLabel+"意见");
          return true;
        }
      }
      if (!!_this.$refs["eForm"]) {
        let valid = await _this.$refs["eForm"].validate()
        if (!valid) {
          dialogVisible = false
        }
      }
      if(this.attachmentList.length == 0){
        _this.$message.warning("最少上传一个附件");
        return true;
      }
      _this.searchQuery.pass = _this.formSubmit.pass
      let defaultStaff = []
      this.defaultStaff=defaultStaff
      this.dialogVisible = true;
    },

    //提交表单和流程数据
    handleWorkflowSubmit() {
      let _this = this
      let formData = JSON.parse(JSON.stringify(_this.form))
      formData.association = JSON.stringify(_this.form.association)
      let wf_receivers = [];
      if (_this.$refs.prochild.receiveUserList.length < 1 &&_this.$refs.prochild.nextData.actDefType!=='endEvent') {
        _this.$message.warning("请选择人员！");
        return;
      }
      _this.$refs.prochild.receiveUserList.forEach((element) => {
        wf_receivers.push({
          receiveUserId: element.id,
          receiveUserOrgId: element.parentId,
        });
      });
      let wf_nextActDefId = _this.$refs.prochild.nextData.actDefId;
      let wf_nextActDefName = _this.$refs.prochild.nextData.actDefName;
        // 显示加载中
        _this.flowStepLoading = true
        _this.detailLoading = true
        let wf_procTitle = "【工具发布】" + (formData.toolName?formData.toolName:"")
        if (_this.pListData && _this.pListData.procInstId) {
          //流程执行参数
          formData.bpmClientInputModel = {
            model: {
              wf_procDefKey: _this.procDefKey,
              wf_procDefId: _this.pListData.procDefId,
              wf_procTitle: wf_procTitle,
              wf_curActInstId: _this.pListData.curActInstId,
              wf_sendUserId: _this.userInfo.userName,
              wf_sendUserOrgId: _this.userInfo.deptId,
              wf_receivers: wf_receivers,
              wf_nextActDefId: wf_nextActDefId,
              wf_curComment: _this.formSubmit.summary,
              wf_curActDefId: _this.pListData.curActDefId,
              wf_curActDefName: _this.pListData.curActDefName,
              wf_nextActDefName: wf_nextActDefName,
            },
            applyStatus: _this.formSubmit.pass,
            review: _this.attributeModelBool('approve'),
            type: formData.type
          };
        }else{
          //创建流程参数
          formData.bpmClientInputModel = {
            model: {
              wf_procTitle:  wf_procTitle,
              wf_nextActDefId: wf_nextActDefId,
              wf_procDefId: _this.pListData.procDefId,
              wf_procDefKey: _this.procDefKey,
              wf_sendUserId: _this.userInfo.userName,
              wf_sendUserOrgId: _this.userInfo.deptId,
              wf_receivers: wf_receivers,
              wf_curActDefName: _this.pListData.actDefName,
              wf_curActDefId: _this.pListData.actDefId,
              wf_nextActDefName: wf_nextActDefName,
            },
            review: _this.attributeModelBool('approve'),
            type: formData.type,
          };
        }
        if (_this.$refs.prochild.nextData.actDefType==='endEvent') {
          //办结
          formData.recordStatus = 'done'
        } else {
          //进行中
          formData.recordStatus = 'doing'
        }
        formData.editStatus = _this.editStatus
        this.$set(formData,'attachmentList',_this.attachmentList)
        addTool(formData).then((res) => {
          if (res.code===200) {
            _this.$message({
              message: '流程提交成功',//提示的信息
              type:'success',　　//类型是成功
              duration:1200,　　//显示时间, 毫秒。设为 0 则不会自动关闭，建议1200
              onClose:()=>{
                _this.flowStepLoading = false
                _this.detailLoading = false
                _this.dialogVisible = false;
                _this.close();
              }
            });

            store.dispatch('GetUserMsgCount').then(() => { })
          }
        });
    },
    handleMonitor() {
      this.monitorDrawerVisible = true;
      this.$nextTick(() => {
        this.$refs.monitorDrawer.init(this.pListData.procInstId);
      });
    },
    handleDelete(row){
      const index = this.attachmentList.findIndex(item => item.fileNewName == row.fileNewName);
      if (index !== -1) {
        // 从 attachmentList 中删除数据
        this.attachmentList.splice(index, 1);
        // 处理当前页面可能没有数据的情况，跳到上一页
        if (this.paginatedData.length === 0 && this.currentPage > 1) {
          this.currentPage--;
        }
      }
    },
    /**
     * 新增上传附件
     */
    handleDocAdd() {
      this.addDocShow = true
      this.$nextTick(() => {
        this.$refs.addDocRef.resetForm()
      })
    },
    getAttachmentList(toolId) {
      this.loading = true
      this.$set(this.attQueryParams,'del',"0")
      this.$set(this.attQueryParams,'businessId',toolId)
      listAttachment(this.attQueryParams).then(res => {
          this.attachmentList = res.rows;
          // this.total = res.total;
          this.loading = false;
        }
      );
    },
    submitPeople(peopleList){
      this.$set(this.form,'toolPrincipals',peopleList[0]['userId'])
      this.$set(this.form,'toolPrincipalsName',peopleList[0]['nickName'])
      this.toolPrincipalsChoose = false;
      this.$refs['eForm'].validateField("toolPrincipals");
    },
    handleSelectNode(node){
      this.$set(this.form,'toolRespDeptName',node.label)
      this.$set(this.form,'toolRespDept',node.id)
      this.$refs.eForm.validateField('toolRespDept');
    },
    handleToolSelect(){
      let self = this
      let toolIds = []
      if(self.form.association && self.form.association.length > 0){
        self.form.association.forEach(item=>{
          toolIds.push(item.toolId)
        })
      }
      // this.form.association.list();
      // this.$refs.selectHeadTool.blur();
      this.$nextTick(()=>{
        this.$refs.toolSelect.init(null,null,true, toolIds)
      })
    },
    /** 处理工具编辑 **/
    handleToolEdit(){
      let self = this
      self.editToolVisible = true
    },
    selectHandle(source,index,data){
      let list = this.form.association
      if (!list) {
        list = []
      }
      data.forEach(item=>{
        list.push({toolId:item.toolId,toolCode:item.toolCode,toolName:item.toolName})
      })
      this.form.association = list
    },
    /** 添加关联附件数据**/
    addFileData(dataInfo){
      let document = JSON.parse(JSON.stringify(dataInfo))
      this.attachmentList.push(document)
    },
    findDeptInTree(tree, id) {
      for (const node of tree) {
        if (node.id == id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findDeptInTree(node.children, id);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    /** 获取部门名称 **/
    convertDeptName(row){
      let foundDept = this.findDeptInTree(this.deptOptions, row.docRespDept);
      if(foundDept){
        return foundDept.label
      }
      return null
    },
    isShowOperation(row){
      let self = this
      if(row.businessId == null || row.businessId == undefined || row.businessId == ''){
        return false
      }
      return true
    },
    previewAuth(row){
      if(row.fileUrl == null || row.fileUrl == '' || row.fileUrl == undefined){
        return false
      }
      let extension = this.getExtension(row.fileUrl);
      const acceptedExtensions = this.attFileType.toLowerCase().split(',');
      if(acceptedExtensions.includes(extension)){
        return false
      }
      return true
    },
    getExtension(filePath) {
      // 分割字符串，以 '.' 为分隔符
      const parts = filePath.split('.');
      // 取最后一个部分作为后缀名
      const extension = parts.pop();
      return extension;
    },
    handlePreview(row){
      this.isPreviewDisable = true
      this.previewLoading = true
      this.$nextTick(() => {
        this.$refs.previewForm.frontModulePreview(row)
      })
    },
    /** 关闭预览 **/
    previewClose(){
      this.isPreviewDisable = false
    },
    /** 关闭预览遮罩 **/
    previewLoadingClose(){
      this.previewLoading = false
    },
    /**
     * 处理下载
     * **/
    handleDownload(row){
      let self = this
      self.loadingDownload = true
      this.$download.resource(row.fileUrl);

      //保存下载记录
      if(row.businessId){
        let formData = {
          'businessId': row.businessId,
          'businessType': 'tool',
          'attId': row.id,
          'attName': row.fileOldName
        }
        addCount(formData).then(res => {
        });
      }

      setTimeout(()=>{
        self.loadingDownload = false
      },1000)
    },
    handleBeforeClose() {
      this.viewDialogOpen = false
    },
    handleUploadSuccess(res) {
      this.attachmentList.push(res)
      // 处理上传成功后的逻辑
    },
    handleUploadError(error) {
      // 处理上传失败后的逻辑
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
    },
    /** 删除 **/
    selectDelete(row){
      const index = this.form.association.findIndex(item => item.toolId == row.toolId);
      if (index !== -1) {
        // 从 attachmentList 中删除数据
        this.form.association.splice(index, 1);
      }
    },
    handlePageToolChange(newPage) {
      this.currentToolPage = newPage;
    },
    //处理树节点点击事件
    handleToolNodeClick(data){
      console.log(data);
    },
    /** 获取工具关联树展示 */
    getToolRelationTree() {
      let self = this
      let toolRelation ={
        resourceId: "",
      }
      let toolIds = []
      if(this.form.toolId){
        self.$set(toolRelation,"resourceIds",[this.form.toolId])
      }else if(self.form.association && self.form.association.length > 0){
        self.form.association.forEach(item=>{
          toolIds.push(item.toolId)
        })
        self.$set(toolRelation,"resourceIds",toolIds)
      }

      self.toolTreeVisible = true;
      self.toolTreeLoading = true;
      getDataThree(toolRelation).then(res => {
        /* if(self.form.toolName){
          let treeArray = []
          let treeData = {
            "id": "20240908",
            "label": self.form.toolName,
            "types": null,
            "children": res.data
          }
          treeArray.push(treeData)
          this.toolRelationOptions = treeArray;
          self.toolTreeLoading = false;
          return
        } */
        this.toolRelationOptions = res.data;
        self.toolTreeLoading = false;
      }).catch(err => {
        console.error("err========", err)
        self.toolTreeLoading = false;
      });
    },
    toolSelect(){
      /* this.$refs.selectHeadTool.blur();
      this.$nextTick(()=>{
        this.$refs.toolSelect.init(null,null,true)
      }) */
      let self = this
      this.$refs.selectHeadTool.blur();
      let toolIds = []
      if(self.form.association && self.form.association.length > 0){
        self.form.association.forEach(item=>{
          toolIds.push(item.toolId)
        })
      }
      this.$nextTick(()=>{
        this.$refs.toolSelect.init(null,null,true, toolIds)
      })
    },
    /**
     * 状态变更
     */
    passChange(){
      let self = this
      if(self.formSubmit.summary == null || self.formSubmit.summary == '' || self.formSubmit.summary == undefined ){
        if(self.formSubmit.pass){
          self.formSubmit.summary = '通过'
        }else{
          self.formSubmit.summary = '不通过'
        }
      }else{
        if(self.formSubmit.pass){
          self.formSubmit.summary = self.formSubmit.summary.replace("不通过", "通过")
        }else{
          self.formSubmit.summary = self.formSubmit.summary.replace("通过", "不通过")
        }
      }

    }

},

};
</script>
