<template>
  <h5-card-pane label="流程信息">
    <template #default>
      <div class="flowPath-box">
        <div class="t"><span>任务情况</span></div>
        <div class="c">
          <div class="name">
            {{ (wfInfo.createDate ? wfInfo.createDate.substring(0, 10) : '') + wfInfo.name }}
            <el-tag :type="getWfStatusType()" size="mini">{{ getWfStatusLabel() }}</el-tag>
          </div>
        </div>
        <div class="m2">
          <div class="t"><span>流程图</span></div>
          <div class="c">
            <el-button icon="" class="btn" @click="showPreviewDialog=true" icon="el-icon-view">查看流程图</el-button>
          </div>
        </div>
        <div class="m2">
          <div class="t"><span>任务情况</span></div>
          <div class="c">
            <el-button icon="" class="btn" @click="showRenwuDialog=true" icon="iconfont icon-preview">查看任务情况
            </el-button>
          </div>
        </div>

      </div>
      <div class="flowPath-btns">
        <el-button type="success" plain class="btn" @click="openAgreeDialog" v-show="wfInfo.toSubmit"
                   icon="iconfont icon-tongguo">{{ $t2('通过', 'components.wf.agree') }}
        </el-button>
        <el-button type="warning" plain class="btn" @click="openManualDialog" v-show="wfInfo.toInterrupt"
                   icon="iconfont icon-caozuozhongduan">{{ $t2('中断', 'components.wf.manual') }}
        </el-button>
        <el-button type="danger" plain class="btn" @click="rejectWfTask" v-show="wfInfo.toReject"
                   icon="iconfont icon-a-bohui1">{{ $t2('驳回', 'components.wf.reject') }}
        </el-button>
        <el-button type="primary" plain class="btn" @click="openChangeWfForm"
                   v-show="(wfInfo.toTransfer===null || wfInfo.toTransfer===undefined) ? wfInfo.toSubmit: wfInfo.toTransfer"
                   icon="iconfont icon-zhuanban">{{ $t2('转办', 'components.wf.transfer') }}
        </el-button>
        <el-button type="primary" plain class="btn" @click="openUrgingDialog" v-show="wfInfo.toInterrupt"
                   icon="iconfont icon-cuiban">{{ $t2('催办', 'components.wf.urging') }}
        </el-button>
        <el-button type="primary" plain class="btn" @click="openAddIncreaseSign" v-show="wfInfo.toAddIncreaseSign"
                   icon="el-icon-plus">{{ $t2('加签', 'components.wf.addIncreaseSign') }}
        </el-button>
        <el-button type="primary" plain class="btn" @click="openDeleteTaskUserDialog"
                   v-show="wfInfo.toDeleteIncreaseSign"
                   icon="el-icon-delete">{{ $t2('减签', 'components.wf.deleteIncreaseSign') }}
        </el-button>
        <el-button type="primary" plain class="btn" @click="openTalkDialog()"
                   icon="el-icon-chat-dot-square" v-if="toTalk && wfInfo.toLinkup">
          {{ $t2('沟通', 'components.wf.talk') }}
        </el-button>
        <el-button type="primary" plain class="btn" @click="openSetCandidateDialog(null)"
                   v-show="wfInfo.toSetCandidate"
                   icon="el-icon-user">{{ $t2('修改候选人', 'components.wf.setCandidate') }}
        </el-button>
        <el-button type="danger" plain class="btn" @click="openRevokeDialog(null)"
                   v-show="wfInfo.toRevoke"
                   icon="el-icon-document-delete">{{ $t2('撤回', 'components.wf.revoke') }}
        </el-button>
      </div>
      <div class="pop-box" v-if="showPreviewDialog">
        <div>
          <div class="header-box">
            <i class="back el-icon-close" @click="showPreviewDialog=false"></i>流程图预览
          </div>
          <div class="flex" style="height:calc(100vh - 38px)">
            <el-form label-position="top" class="form-box">
              <div class="tit"><span>{{
                  (wfInfo.createDate ? wfInfo.createDate.substring(0, 10) : '') + wfInfo.name
                }}</span></div>
              <iframe style="width: 100%;flex:1" :src="wfImage"></iframe>
            </el-form>
          </div>
          <div class="fixed-bottom-btns">
            <el-button type="primary" plain class="btn" @click="showPreviewDialog=false" icon="el-icon-close">取 消
            </el-button>
            <el-button type="primary" class="btn" icon="el-icon-check" @click="showPreviewDialog=false">确 定
            </el-button>
          </div>
        </div>
      </div>

      <div class="pop-box" v-if="showRenwuDialog">
        <div>
          <div class="header-box">
            <i class="back el-icon-close" @click="showRenwuDialog=false"></i>任务情况预览
          </div>
          <div class="flex" style="height:calc(100vh - 38px);overflow:auto">
            <div class="h5-process-info">
              <div class="item" v-for="wftaskLineData in wftaskData" :key="wftaskLineData.id">
                <div class="time">
                  {{ wftaskLineData.approveTime ? wftaskLineData.approveTime.substring(0, 10) : '' }}
                  <br/>
                  {{ wftaskLineData.approveTime ? wftaskLineData.approveTime.substring(11) : '' }}
                </div>
                <div class="status"
                     :class="taskStatuses[wftaskLineData.type]?taskStatuses[wftaskLineData.type].class:''">
                  {{ taskStatuses[wftaskLineData.type] ? taskStatuses[wftaskLineData.type].value : null }}
                </div>
                <i class="circle"></i>
                <div class="info">
                  <p>
                    <span class="name">{{ wftaskLineData.taskName }}</span>
                    <span>{{ $t2('执行人', 'components.wf.approverName') }}：{{ wftaskLineData.approverName }}</span>
                    <span>
                  {{ $t2('候选人', 'components.wf.candidateName') }}：
                  <span class="">{{ wftaskLineData.candidateNames }}</span>
                </span>
                  </p>
                  <p class="t"><span class="t1">{{ $t2('备注/意见', 'components.wf.opinion') }}：</span><span>{{
                      wftaskLineData.opinion
                    }}</span></p>
                </div>
              </div>
            </div>
          </div>
          <div class="fixed-bottom-btns">
            <el-button type="primary" plain class="btn" @click="showRenwuDialog=false" icon="el-icon-close">取 消
            </el-button>
            <el-button type="primary" class="btn" icon="el-icon-check" @click="showRenwuDialog=false">确 定
            </el-button>
          </div>
        </div>
      </div>

      <div class="pop-tipsBox" style="display: block;" v-if="showWfManualDialog">
        <div>
          <i class="icon"></i>
          <div class="cont">
            <p class="name">
              {{ $t2('流程中断', 'components.wf.wfManual') }}<span>—</span><b
              class="f-red">{{ $t2('节点', 'components.wf.node') }}：{{
                wfInfo.taskName
              }}</b>
            </p>
            <p class="txt">{{ $t2('您确定要中断流程吗？', 'components.wf.manualTip') }}</p>
          </div>
          <div class="btns">
            <el-button type="primary" class="btn" plain icon="el-icon-close" @click="showWfManualDialog = false">{{
                $t2('取 消', 'system.button.cancel2')
              }}
            </el-button>
            <el-button type="primary" class="btn" icon="el-icon-check" @click="manualEndWf()">{{
                $t2('确 定', 'system.button.confirm2')
              }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="pop-tipsBox" style="display: block;" v-if="rejectDialogVisible">
        <div>
          <i class="icon"></i>
          <div class="cont">
            <p class="name">{{ $t2('流程驳回', 'components.wf.wfReject') }}<span
            >—</span><b
              class="f-red">{{ $t2('节点', 'components.wf.node') }}：{{
                wfInfo.taskName
              }}</b></p>
            <el-form label-position="top" class="form-box">
              <el-form-item label="驳回节点" field="nodeId">
                <el-select v-model="rejectForm.nodeId"
                           :placeholder="$t2('请选择驳回节点', 'components.wf.rejectNodePlaceholder')">
                  <el-option v-for="(rejectNode,index) in rejectNodes" :label="rejectNode.nodeName"
                             :value="rejectNode.nodeId" :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="驳回意见" field="opinion">
                <el-input type="textarea" :rows="8"
                          :placeholder="$t2('请输入内容', 'components.wf.rejectOpinionPlaceholder')"
                          v-model="rejectForm.opinion" class="txt"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="btns">
            <el-button type="primary" class="btn" plain icon="el-icon-close" @click="rejectDialogVisible = false">{{
                $t2('取 消', 'system.button.cancel2')
              }}
            </el-button>
            <el-button type="primary" class="btn" icon="el-icon-check" @click="subRejectForm()">{{
                $t2('确 定', 'system.button.confirm2')
              }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="pop-tipsBox" style="display: block;" v-if="agreeDialogVisible">
        <div>
          <i class="icon"></i>
          <div class="cont">
            <p class="name">{{ $t2('流程通过', 'components.wf.wfAgree') }}<span
            >—</span><b
              class="f-red">{{ $t2('节点', 'components.wf.node') }}：{{
                wfInfo.taskName
              }}</b></p>
            <el-form label-position="top" class="form-box">
              <el-form-item label="通过节点" field="nodeId">
                <el-select v-model="agreeForm.nodeId"
                           :placeholder="$t2('请选择通过节点', 'components.wf.agreeNodePlaceholder')">
                  <el-option v-for="(node,index) in agreeNodes" :label="node.nodeName"
                             :value="node.nodeId" :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="通过意见" field="opinion">
                <el-input type="textarea" :rows="8" :placeholder="$t2(`请填写您的意见~
         注：
         通过默认意见为“同意”
          `, 'components.wf.agreeOpinionPlaceholder')" v-model="agreeForm.opinion"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="btns">
            <el-button type="primary" class="btn" plain icon="el-icon-close" @click="agreeDialogVisible = false">{{
                $t2('取 消', 'system.button.cancel2')
              }}
            </el-button>
            <el-button type="primary" class="btn" icon="el-icon-check" @click="subAgreeForm()">{{
                $t2('确 定', 'system.button.confirm2')
              }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="pop-tipsBox" style="display: block;" v-if="changeWfDialogVisible">
        <div>
          <i class="icon"></i>
          <div class="cont">
            <p class="name">{{ $t2('流程转办', 'components.wf.wfTransfer') }}<span>—</span><b
              class="f-red">{{ $t2('节点', 'components.wf.node') }}：{{
                wfInfo.taskName
              }}</b></p>
            <el-form label-position="top" class="form-box">
              <el-form-item label="转办人" field="nodeId">
                <el-input
                  class="search-input"
                  max="200"
                  v-model="changeWfForm.userNickNames"
                  @clear="
                          changeWfForm.userIds = '';
                          changeUserRows = [];
                          $forceUpdate();
                        "
                  v-el-readonly
                  clearable
                >
                  <i slot="suffix" class="el-input__icon el-icon-search" @click="showUserDialog = true"></i>
                </el-input>
              </el-form-item>
              <el-form-item label="转办意见" field="opinion">
                <el-input type="textarea" :rows="8"
                          :placeholder="$t2('请输入内容', 'components.wf.transferOpinionPlaceholder')"
                          v-model="changeWfForm.opinion"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="btns">
            <el-button type="primary" class="btn" plain @click="changeWfDialogVisible = false">{{
                $t2('取 消', 'system.button.cancel2')
              }}
            </el-button>
            <el-button type="primary" class="btn" @click="subChangeWfForm()">
              {{ $t2('确认转办', 'components.wf.confirmTransfer') }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="pop-tipsBox" style="display: block;" v-if="showAddIncreaseSignDialog">
        <div>
          <i class="icon"></i>
          <div class="cont">
            <p class="name">
              {{ $t2('流程加签', 'components.wf.wfAddIncreaseSign') }}<span>—</span><b
              class="f-red">{{ $t2('节点', 'components.wf.node') }}：{{
                wfInfo.taskName
              }}</b>
            </p>
            <el-form label-position="top" class="form-box">
              <el-form-item label="候选人">
                <el-input
                  class="search-input"
                  max="200"
                  v-model="addIncreaseSignForm.userNickNames"
                  @clear="
                            addIncreaseSignUsers = [];
                            $forceUpdate();
                          "
                  :placeholder="$t2('候选人', 'components.wf.addIncreaseSignUser')"
                  v-el-readonly
                  clearable
                >
                  <i slot="suffix" class="el-input__icon el-icon-search"
                     @click="showAddTaskUserDialog = true"></i>
                </el-input>
              </el-form-item>
              <el-form-item label="加签意见" field="opinion">
                <el-input type="textarea" :rows="8"
                          :placeholder="$t2('请输入内容', 'components.wf.addIncreaseSignOpinionPlaceholder')"
                          v-model="addIncreaseSignForm.opinion"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="btns">
            <el-button type="primary" class="btn" plain @click="showAddIncreaseSignDialog = false">{{
                $t2('取 消', 'system.button.cancel2')
              }}
            </el-button>
            <el-button type="primary" class="btn" @click="submitAddTaskUserForm(0)">
              {{ $t2('确认加签', 'components.wf.confirmAddIncreaseSign') }}
            </el-button>
          </div>
        </div>
      </div>

      <user-dialog v-if="showUserDialog" :visiable.sync="showUserDialog" @close="showUserDialog = false"
                   @confirm="userConfirm" multi="true" :param.sync="wfUserParamForTransfer"
                   :rows="changeUserRows"></user-dialog>
      <urgingDialog v-if="urgingDialogVisible" :visiable.sync="urgingDialogVisible" :wfInfo="wfInfo"
                    :current_prefix="current_prefix"
                    @confirm="reloadContent" multi="true"></urgingDialog>
      <deleteTaskUserDialog v-if="showDeleteTaskUserDialog" :visiable.sync="showDeleteTaskUserDialog" :wfInfo="wfInfo"
                            :current_prefix="current_prefix"
                            @confirm="reloadContent" multi="true"></deleteTaskUserDialog>

      <addTaskUserdialog v-if="showAddTaskUserDialog" :visiable.sync="showAddTaskUserDialog" :wfInfo="wfInfo"
                         :current_prefix="current_prefix" :rows.sync="addIncreaseSignUsers"
                         @confirm="confirmAddTaskUser" multi="true"
                         :param.sync="wfUserParamForAddSign"></addTaskUserdialog>
      <user-dialog v-if="showTalkUserDialog" :visiable.sync="showTalkUserDialog" @close="showTalkUserDialog = false"
                   @confirm="confirmTalkUserDialog" multi="false" :param.sync="wfUserParamForTalk"></user-dialog>
      <setCandidateDialog v-if="showSetCandidateDialog" :visiable.sync="showSetCandidateDialog"
                          @close="closeSetCandidateDialog"
                          :wfInfo="wfInfo"
                          :current_prefix="current_prefix"></setCandidateDialog>
    </template>
  </h5-card-pane>
</template>
<script>
import Vue from "vue";

import settingConfig from "@/settings";
import commonMixin from "../../../mixins/mobile/common/index";
import {getToken} from "../../../utils/auth";

let configUtil = {
  baseUrl: process.env.VUE_APP_BASE_API,
  getToken,
  settingConfig,
  Vue,
  requireView: (url) => {
    return require("../../../views" + url).default;
  },
};

function appendPrevChildDom(parentDom, newDom) {
  if (parentDom.hasChildNodes()) {
    let currentDom = parentDom.children[0];
    parentDom.insertBefore(newDom, currentDom);
  } else {
    parentDom.append(newDom);
  }
}

function getTarget(t) {
  return t.parentVue;
}

export default {
  mixins: [commonMixin],
  props: {
    _wfInfo: Object,
    _taskParam: Object,
    wfOption: Object,
    defaultShowWfContent: Boolean,
  },
  components: {
    UserDialog: () => import('../../../views/mobile/user/user/dialog.vue'),
    urgingDialog: () => import('./urgingDialog'),
    deleteTaskUserDialog: () => import('./deleteTaskUserDialog'),
    addTaskUserdialog: () => import('./addTaskUserdialog'),
    setCandidateDialog: () => import('./setCandidateDialog')
  },
  computed: {
    current_prefix() {
      return this.serviceId ? "/" + this.serviceId : "";
    },
    viewTarget() {
      return getTarget(this);
    },
    isHideWf() {
      let that = this.viewTarget;
      let _hideWf = that._hideWf || that.$attrs._hideWf;
      return _hideWf === true || _hideWf === 'true';
    }
  },
  data() {
    let showWfFold =
      settingConfig.showWfFold != null && settingConfig.showWfFold != undefined
        ? settingConfig.showWfFold
        : false;
    let showWfContent =
      showWfFold &&
      settingConfig.defaultShowWfContent != null &&
      settingConfig.defaultShowWfContent != undefined
        ? settingConfig.defaultShowWfContent
        : true;
    if (
      this.defaultShowWfContent != null &&
      this.defaultShowWfContent != undefined
    ) {
      showWfContent = this.defaultShowWfContent;
    }

    return {
      showRenwuDialog: false,
      showDomContent: false,
      showPreviewDialog: false,
      objId: null,
      wfCode: null,
      serviceId: null,
      parentVue: null,
      wfConfig: null,

      fileInfos: [],
      showUserDialog: false,
      showContent: true,
      objTypeCode: "",
      // objId: '',
      wfInfo: {},
      // currentTask: {},
      taskParam: {},
      wfImage: "",
      wfStartBtn: false,
      wfManualendBtn: false,
      wfSubmitBtn: false,
      wfRejectBtn: false,
      changeHandlerBtn: false,
      wftaskData: [],
      allWfTaskOpinions: [],
      vxeOption: {},
      rejectNodes: [],
      rejectDialogVisible: false,
      rejectForm: {
        rejectSubmitModel: null,
        nodeId: null,
        opinion: null,
      },
      formLabelWidth: "120px",
      agreeDialogVisible: false,
      agreeForm: {
        opinion: this.$t2('同意', 'components.wf.defaultAgreeOption'),
        nodeId: null,
      },
      changeWfDialogVisible: false,
      changeWfForm: {},
      changeUserRows: [],
      taskStatuses: {
        start: {
          class: "blue",
          value: this.$t2('开始', 'components.wf.startStatus'),
        },
        approve: {
          class: "orgn",
          value: this.$t2('待审批', 'components.wf.approveStatus'),
        },
        submit: {
          class: "green",
          value: this.$t2('同意', 'components.wf.submitStatus'),
        },
        reject: {
          class: "red",
          value: this.$t2('驳回', 'components.wf.rejectStatus'),
        },
        transfer: {
          class: "green",
          value: this.$t2('转办', 'components.wf.transferStatus'),
        },
        addIncreaseSign: {
          class: "green",
          value: this.$t2('加签', 'components.wf.addIncreaseSignStatus'),
        },
        revoke: {
          class: "red",
          value: this.$t2('撤回', 'components.wf.revokeStatus'),
        },
        end: {
          class: "gray",
          value: this.$t2('结束', 'components.wf.endStatus'),
        },
      },
      opinion: "",
      showWfFold: showWfFold,
      showWfContent: showWfContent,

      urgingForm: {},
      urgingDialogVisible: false,
      urgingUserIds: [],
      urgingUsers: [],
      agreeNodes: [],
      showWfManualDialog: false,

      showDeleteTaskUserDialog: false,
      showAddTaskUserDialog: false,
      wfUserParam: {},
      wfUserParamForTransfer: {},//转办
      wfUserParamForAddSign: {},//加签
      wfUserParamForTalk: {},//沟通
      tabIndex: "1",
      linkupOption: {},
      talkForm: {
        receiverName: null,
        content: null,
        attachmentDTOs: [],
        replyId: null
      },
      showTalkUserDialog: false,
      showTalkDialog: false,
      showFlowImg: true,
      operateType: null,
      addIncreaseSignUsers: [],
      addIncreaseSignForm: {
        userNickNames: null,
        opinion: null
      },
      showAddIncreaseSignDialog: false,
      showOpeaImg: true,
      showSetCandidateDialog: false,
      toTalk: false,
      showAllWfOpinon: false,

      revokeDialogVisible: false,
      revokeForm: {opinion: null},
      wfStatusMap: {
        1: {label: "审核中", type: "warning"},
        3: {label: "已驳回", type: "danger"},
        2: {label: "已完成", type: "success"}
      }
    };
  },
  provide() {
    return {
      getParentVue: () => {
        return this.parentVue;
      }
    };
  },
  created() {
    // this.wfInfo = this._wfInfo;
    this.showFlowImg = settingConfig.expandWfImage === false ? false : true;
    this.showAllWfOpinon = settingConfig.showAllWfOpinon === true;
  },
  mounted() {
    this.init();
  },
  methods: {
    getWfStatusLabel() {
      return this.wfStatusMap[this.wfInfo.stat]?.label;
    },
    getWfStatusType() {
      return this.wfStatusMap[this.wfInfo.stat]?.type;
    },
    init() {
      let opt = this.wfOption;
      this.objId = opt.objId;
      this.wfCode = opt.wfCode;
      this.serviceId = opt.serviceId;
      this.parentVue = opt.parentVue;
      this.wfConfig = this.wfOption;

      let wfConfig = this.wfOption;
      let that = getTarget(this);
      let hasWf = false;
      let wfInfo, currentTask, taskParam;
      let option = {
        objId: this.objId,
        wfCode: this.wfCode
      }
      let current_prefix = this.current_prefix;

      let initButton = () => {
        /*return
        this.$nextTick(() => {
          that.$refs.wfButtonGroup.init({
            taskParam,
            wfInfo,
            hasWf,
            current_prefix,
            wfConfig
          });
        });*/
      }

      this.initWfInfo(option, {
        success: res => {
          if (res.objx && res.objx.procInstId) {
            hasWf = true;
            wfInfo = res.objx;
            this.wfInfo = wfInfo;
            // this.showDomContent = true;

            if (wfInfo.taskId) {
              this.getTaskParams(wfInfo.taskId, {
                success: res2 => {
                  taskParam = res2.objx || {};
                  taskParam.objId = option.objId;
                  this.taskParam = taskParam;

                  initButton();
                }
              });
            } else {
              initButton();
            }
            this.initOperateType();
            this.initForAll();
          } else {
            initButton();
          }
        }
      });
    },
    initWfInfo(option, httpConfig) {

      let that = getTarget(this);
      let id = option.objId;
      let code = option.wfCode;
      return that.$http({
        url: this.current_prefix + '/wf/getWfInfo',
        method: `post`,
        data: {
          objTypeCode: code,
          objId: id
        },
        isLoading: true,
        modalStrictly: true,
        ...httpConfig
      });
    },
    getTaskParams(taskId, httpConfig) {
      let that = getTarget(this);
      return that.$http({
        url: this.current_prefix + '/wf/getTaskVariables',
        method: `post`,
        data: {
          stringOne: taskId
        },
        isLoading: true,
        modalStrictly: true,
        ...httpConfig
      });
    },


    initOperateType() {
      if (this.operateType) {
        let wfInfo = this.wfInfo;
        if (wfInfo.toSubmit) {
          this.openAgreeDialog('submit');
        } else if (wfInfo.toReject) {
          this.rejectWfTask('reject');
        } else if (wfInfo.toAddIncreaseSign) {
          this.openAddIncreaseSign('addIncreaseSign')
        } else if (wfInfo.toRevoke) {
          this.openRevokeDialog('revoke')
        } else if (wfInfo.toLinkup) {
          this.openTalkDialog(null, null, 'talk');
        } else {
          this.operateType = null;
        }
      }
    },
    initForAll() {
      let that = getTarget(this);
      this.initWf(() => {
        if (this.wfInfo.procInstId) {
          this.initCurrentTask(this.wfInfo.procInstId, () => {
            this.initWftask(this.wfInfo.procInstId);
            this.getAllWfTaskOpinions();
          });
          this.initWfUserParam();
          this.initTabIndex();
        }
      });
    },
    initTabIndex() {
      let that = getTarget(this);
      that.$http({
        url: USER_PREFIX + "/wf_diy_attribute/getValue",
        method: `post`,
        data: {attributeKey: "param7"},
        isLoading: true,
        success: (res) => {
          let val = res !== null ? res.objx === true : false;
          this.toTalk = val;
          let flag = false;
          if (val) {
            let flag1 = that.$attrs._isNotifyMessage == true || that.$attrs._isNotifyMessage == "true";
            if (flag1) {
              this.tabIndex = "2";
            }
            if (settingConfig.autoOpenWfLinkup) {
              flag = true;
              let flag2 = that.$attrs._wfNotifyType == "wfLinkup";
              let flag3 = flag1 && flag2;
              if (flag3) {
                this.$nextTick(() => {
                  let wfTabPane = this.$refs.wfTabPane;
                  if (!wfTabPane.showContent) {
                    wfTabPane.handleFold();
                  }
                });
              }
            }
          }
          this.initLinkup(flag);
        }
      });

    },
    initWf(done) {
      var data = this.wfInfo;
      if (data && data.procInstId) {
        /** 流程状态：0未启动，1审核中，2已完成，3驳回，4中断 */
        var statuses = {
          1: '<span class="tag">' + this.$t2('审核中', 'components.wf.wfStatus1') + '</span>',
          3: '<span class="tag red">' + this.$t2('已驳回', 'components.wf.wfStatus2') + '</span>',
          2: '<span class="tag green">' + this.$t2('已完成', 'components.wf.wfStatus3') + '</span>',
        };
        var statusStr = "";
        if (data.stat != null) {
          statusStr = statuses[data.stat] || "";
        }
        data.statusStr = statusStr;
        this.wfInfo = data;

        this.wfStartBtn = false;
        if (data.status != 2 && data.starterId) {
          this.wfManualendBtn = true;
        }
        this.wfSubmitBtn = false;
        this.wfRejectBtn = false;

        var url =
          this.current_prefix +
          "/wf/flowImage?procInstId=" +
          data.procInstId +
          "&_r=" +
          Math.random() +
          "&access_token=" +
          configUtil.getToken();
        this.wfImage = configUtil.baseUrl + url;
        done();
      }
    },
    initCurrentTask(procInstId, done) {
      if (this.wfInfo.taskId) {
        this.wfSubmitBtn = true;
        this.wfRejectBtn = true;
        this.changeHandlerBtn = true;
      }
      done();
    },
    initWftask(procInstId) {
      let that = getTarget(this);
      that.$http({
        url: this.current_prefix + "/wf/getWfTaskOpinionMerge",
        data: {
          stringOne: procInstId,
        },
        method: "post",
        isLoading: true,
        modalStrictly: true,
        success: (resultmsg) => {
          var datas = resultmsg.objx || [];
          this.wftaskData = datas;
        },
      });
    },
    getAllWfTaskOpinions() {
      if (!this.showAllWfOpinon) {
        return;
      }
      let that = getTarget(this);
      let wfInfo = this.wfInfo;
      that.$http({
        url: this.current_prefix + "/wf/getAllWfTaskOpinions",
        data: {
          objId: wfInfo.objId,
          objTypeCode: wfInfo.objTypeCode
        },
        method: "post",
        isLoading: true,
        modalStrictly: true,
        success: (resultmsg) => {
          var datas = resultmsg.objx || [];
          this.allWfTaskOpinions = datas;
        },
      });
    },
    openManualDialog(operateType) {
      this.operateType = operateType;
      this.showWfManualDialog = true;
    },
    manualEndWf() {
      this.showWfManualDialog = false;
      let that = getTarget(this);
      var procInstId = this.wfInfo.procInstId;
      var taskId = this.wfInfo.taskId ? this.wfInfo.taskId : "";
      var data = JSON.stringify({
        uuid: this.wfInfo.uuid,
      });
      that.$http({
        url: this.current_prefix + "/wf/interrupt",
        data: data,
        method: "post",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        isLoading: true,
        success: (resultMsg) => {
          that.$message({
            message: resultMsg.content,
            type: "success",
            duration: 500,
            onClose: (t) => {
              this.reloadContent();
              this.closeWinOnCheck(3);
            },
          });
        },
      });
    },
    async rejectWfTask(operateType) {
      let that = getTarget(this);
      var procInstId = this.wfInfo.procInstId;
      var taskId = this.wfInfo.taskId;
      var destinations = [];

      await that.$http({
        url: this.current_prefix + "/wf/getPreIncomeNodes",
        data: {
          stringOne: taskId,
        },
        method: "post",
        //contentType: 'application/json;charset=utf-8',
        isLoading: true,
        success: (resultMsg) => {
          destinations = (resultMsg.objx || []).reverse();
        },
      });

      if (destinations == null) {
        return false;
      }
      if (destinations.length == 0) {
        that.$message({
          message: this.$t2('无法驳回，没有目标节点', 'components.wf.rejectWarnMsg1'),
          type: "error",
          duration: 2 * 1000,
        });
        return false;
      }
      this.operateType = operateType;

      this.rejectForm.rejectSubmitModel = this.wfInfo.toRejectNode == false ? 2 : null
      this.rejectForm.nodeId = destinations[0].nodeId;
      this.rejectForm.opinion = "";
      this.rejectNodes = destinations;
      this.rejectDialogVisible = true;
    },
    subRejectForm() {
      let that = getTarget(this);
      var procInstId = this.wfInfo.procInstId;
      var taskId = this.wfInfo.taskId;

      if (!this.rejectForm.nodeId) {
        that.$message({
          message: this.$t2('请选择驳回节点', 'components.wf.rejectWarnMsg2'),
          type: "error",
          duration: 2 * 1000,
        });
        return false;
      }

      if (!this.rejectForm.opinion) {
        that.$message({
          message: this.$t2('请输入驳回意见', 'components.wf.rejectWarnMsg3'),
          type: "error",
          duration: 2 * 1000,
        });
        return false;
      }

      var data = JSON.stringify({
        taskId: taskId,
        uuid: this.wfInfo.uuid,
        nodeId: this.rejectForm.nodeId,
        suggestion: this.rejectForm.opinion,
        rejectSubmitModel: this.rejectForm.rejectSubmitModel
      });
      this.rejectDialogVisible = false;
      that.$http({
        url: this.current_prefix + "/wf/reject",
        data: data,
        method: "post",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        isLoading: true,
        success: (resultMsg) => {
          that.$message({
            message: resultMsg.content,
            type: "success",
            duration: 500,
            onClose: (t) => {
              this.reloadContent();
              this.closeWinOnCheck(2);
            },
          });
        },
      });
    },
    openAgreeDialog(operateType) {
      this.operateType = operateType;
      let that = getTarget(this);
      this.agreeForm = {
        opinion: this.$t2('同意', 'components.wf.defaultAgreeOption'),
        nodeId: null,
      };
      this.agreeNodes = [];
      that.$http({
        url: this.current_prefix + "/wf/getNextOutgoingNodes",
        data: {
          stringOne: this.wfInfo.taskId,
        },
        method: "post",
        isLoading: true,
        success: (res) => {
          let nodes = res.objx || [];
          /*if (tq == true) {
            nodes.reverse();
          }*/
          if (nodes.length) {
            this.agreeForm.nodeId = nodes[0].nodeId;
          }
          this.agreeNodes = nodes;
          this.agreeDialogVisible = true;
        },
      });
    },
    subAgreeForm() {
      let wfConfig = this.wfConfig;
      let done = () => {
        this.subAgreeHandle();
      }
      if (wfConfig.onBeforeAgree) {
        wfConfig.onBeforeAgree(done)
      } else {
        done();
      }
    },
    subAgreeHandle() {
      let that = getTarget(this);
      let nodeId = null;
      if (this.agreeNodes.length) {
        if (!this.agreeForm.nodeId) {
          that.$message({
            message: this.$t2('请选择节点', 'components.wf.agreeWarnMsg1'),
            type: "error",
            duration: 2 * 1000,
          });
          return;
        }
        nodeId = this.agreeForm.nodeId;
      }

      var procInstId = this.wfInfo.procInstId;
      var taskId = this.wfInfo.taskId;
      var memo = this.agreeForm.opinion || this.$t2('同意', 'components.wf.defaultAgreeOption');
      var data = JSON.stringify({
        taskId: taskId,
        uuid: this.wfInfo.uuid,
        suggestion: memo,
        nodeId: nodeId,
      });
      this.agreeDialogVisible = false;
      that.$http({
        url: this.current_prefix + "/wf/submit",
        data: data,
        method: "post",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        isLoading: true,
        success: (resultMsg) => {
          if (resultMsg.objx && resultMsg.objx.code == "999999") {
            this.errorSubmit({
              taskId: taskId,
              uuid: this.wfInfo.uuid,
              suggestion: memo,
              errorMsg: resultMsg.objx.errorMsg
            });
          } else {
            that.$message({
              message: resultMsg.content,
              type: "success",
              duration: 500,
              onClose: (t) => {
                this.reloadContent();
                this.closeWinOnCheck(1);
              },
            });
          }
        },
      });
    },
    errorSubmit(data) {
      let that = getTarget(this);
      that.$http({
        url: this.current_prefix + "/wf/errorSubmit",
        data: data,
        method: "post",
        isLoading: true,
        success: (resultMsg) => {
          that.$message({
            message: resultMsg.content,
            type: "success",
            duration: 500,
            onClose: (t) => {
              this.reloadContent();
              this.closeWinOnCheck(1);
            },
          });
        },
      });
    },
    openChangeWfForm(operateType) {
      this.operateType = operateType;
      this.changeWfDialogVisible = true;
      this.changeUserRows = [];
      this.changeWfForm = {
        userIds: [],
        userNickNames: null,
        opinion: null,
      };
    },
    subChangeWfForm() {
      let that = getTarget(this);
      var procInstId = this.wfInfo.procInstId;
      var taskId = this.wfInfo.taskId;

      var userIds = this.changeWfForm.userIds || [];
      var opinion = this.changeWfForm.opinion || null;

      if (!userIds.length) {
        that.$message({
          message: this.$t2('请选择转办人', 'components.wf.transferWarnMsg1'),
          type: "error",
          duration: 2000,
          onClose: (t) => {
          },
        });
        return false;
      }

      var data = JSON.stringify({
        taskId: taskId,
        uuid: this.wfInfo.uuid,
        transferTo: userIds,
        suggestion: opinion,
      });
      this.changeWfDialogVisible = false;
      that.$http({
        url: this.current_prefix + "/wf/transfer",
        data: data,
        method: "post",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
        },
        isLoading: true,
        success: (resultMsg) => {
          that.$message({
            message: resultMsg.content,
            type: "success",
            duration: 500,
            onClose: (t) => {
              this.reloadContent();
              this.closeWinOnCheck(4);
            },
          });
        },
      });
    },
    userConfirm(rows) {
      if (rows.length > 0) {
        let changeUserRows = this.changeUserRows;
        let ids = changeUserRows.map((changeUserRow) => changeUserRow.id);
        let addRows = rows.filter((row) => !ids.includes(row.id));
        changeUserRows.push(...addRows);

        let row = rows[0];
        this.changeWfForm.userIds = changeUserRows.map(
          (changeUserRow) => changeUserRow.id
        );
        this.changeWfForm.userNickNames = changeUserRows
          .map((changeUserRow) => changeUserRow.nickName)
          .join(",");
      }
    },
    reloadContent() {
      let that = getTarget(this);
      that.$baseReload();
    },
    closeWinOnCheck(flag) {
      //_closeWindowOnCheck=true, 1提交，2驳回，3中断，4转办时，5沟通 关闭窗口
      let that = getTarget(this);
      let _closeWindowOnCheck = that.$attrs._closeWindowOnCheck || that._closeWindowOnCheck;
      if (_closeWindowOnCheck === true || _closeWindowOnCheck === "true") {
        window.close && window.close();
      }
      let _handleCallback = that.$attrs._handleCallback || that._handleCallback;
      _handleCallback && _handleCallback(flag);
    },
    manualCallback() {
      this.$emit("manualCallback");
    },
    openUrgingDialog(operateType) {
      this.operateType = operateType;
      this.urgingDialogVisible = true;
    },
    openDeleteTaskUserDialog(operateType) {
      this.operateType = operateType;
      this.showDeleteTaskUserDialog = true;
    },
    openAddTaskUserDialog(operateType) {
      this.operateType = operateType;
      this.showAddTaskUserDialog = true;
    },
    openAddIncreaseSign(operateType) {
      this.operateType = operateType;
      this.addIncreaseSignUsers = [];
      this.addIncreaseSignForm = {userNickNames: null};
      this.showAddIncreaseSignDialog = true;
    },
    initWfUserParam(callback) {
      this.initTransferUserParam();//转办
      this.initAddSignUserParam();//加签
      this.initTalkUserParam();//沟通
    },
    //
    initTransferUserParam(callback) {
      //初始化转办用户参数
      let that = getTarget(this);
      return that.$http({
        url: USER_PREFIX + "/wf_diy_attribute/getValue",
        method: `post`,
        data: {attributeKey: "param1"},
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          this.wfUserParamForTransfer = res.objx || {};
          callback && callback();
        },
      });
    },
    initAddSignUserParam(callback) {
      //初始化加签用户参数
      let that = getTarget(this);
      return that.$http({
        url: USER_PREFIX + "/wf_diy_attribute/getValue",
        method: `post`,
        data: {attributeKey: "param2"},
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          this.wfUserParamForAddSign = res.objx || {};
          callback && callback();
        },
      });
    },
    initTalkUserParam(callback) {
      //初始化沟通用户参数
      let that = getTarget(this);
      return that.$http({
        url: USER_PREFIX + "/wf_diy_attribute/getValue",
        method: `post`,
        data: {attributeKey: "param3"},
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          this.wfUserParamForTalk = res.objx || {};
          callback && callback();
        },
      });
    },
    //
    resetLinkup() {
      this.formData = {};
      this.$refs["table-linkup"].commitProxy("reload");
    },
    searchLinkup() {
      this.$refs["table-linkup"].commitProxy("reload");
    },
    initLinkup(flag) {
      return
      let h = this.$createElement;
      let statusMap = {
        0: this.$t2('未完成', 'components.wf.talkStatus0'),
        1: this.$t2('已完成', 'components.wf.talkStatus1'),
        2: this.$t2('已取消', 'components.wf.talkStatus2')
      };
      let tableOption = {
        vue: this,
        tableRef: "table-linkup",
        tableName: "wf_table-linkup",
        path: this.current_prefix + "/wf_linkup/listPage",
        param: () => {
          return {
            uuid: this.wfInfo.uuid,
          };
        },
        config: {
          height: 350
        },
        columns: [
          {type: "checkbox", width: 48, resizable: false, fixed: "left"},
          {
            title: this.$t2('任务名称', 'components.wf.taskName'),
            field: "taskName",
            width: 150,
            fixed: "left",
          },
          {
            title: this.$t2('发送人', 'components.wf.senderName'),
            field: "senderName",
            width: 150,
            slots: {
              default: "sender",
            },
          },
          {
            title: this.$t2('接收人', 'components.wf.receiverName'),
            field: "receiverName",
            width: 150,
            slots: {
              default: "receiver",
            },
          },
          {
            title: this.$t2('沟通内容', 'components.wf.talkContent'),
            field: "content",
            width: 250,
            showOverflow: false,
            slots: {
              default: ({row, rowIndex}) => {
                return row.replyId ? ("[" + this.$t2('回复', 'components.wf.reply') + "]" + row.content) : row.content;
              },
            },
          },
          {
            width: 150,
            title: this.$t2('沟通资料', 'components.wf.talkAttachment'),
            field: "attachmentImage",
            sortable: false,
            slots: {
              default: ({row, rowIndex}) => {
                let option = {
                  title: this.$t2('沟通资料', 'components.wf.talkAttachment'),
                  edit: false,
                  rows: (done) => {
                    done(row.attachmentDTOs);
                  },
                };
                return [
                  h("base-attachment", {
                    props: {
                      option: option,
                    },
                  }),
                ];
              },
            },
          },

          {
            title: this.$t2('状态', 'components.wf.status'),
            field: "status",
            width: 150,
            slots: {
              default: ({row, rowIndex}) => {
                return statusMap[row.status] || "";
              },
            },
          },
          {
            title: this.$t2('创建时间', 'system.label.createDate'),
            field: "createDate",
            width: 150,
          },
          {
            width: 80,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: "operate"
            }
          },
        ],
        callback: (rows) => {
          if (rows.length && flag) {
            let row = rows[0];
            if (row.replyToSender) {
              this.$nextTick(() => {
                this.tabIndex = "2";
                this.openTalkDialog(row.sender, row.senderName, 'talk', 1, row.id)
              });
            }
          }
        }
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.linkupOption = opts;
      });
    },
    cancelTalk(row) {
      let that = getTarget(this);
      that.$baseConfirm(this.$t2('您确定要取消沟通记录吗？', 'components.wf.cancelTalkTip')).then(() => {
        that.$http({
          url: this.current_prefix + "/wf_linkup/cancel",
          data: {id: row.id},
          method: "post",
          loadingTarget: document.body,
          isLoading: true,
          success: (resultMsg) => {
            that.$message({
              message: resultMsg.content,
              type: "success",
              duration: 500,
              onClose: (t) => {
                this.reloadContent();
              },
            });
          },
        });
      });
    },
    openTalkDialog(receiver, receiverName, operateType, flag, replyId) {
      this.operateType = operateType;
      /*this.talkForm.receiver = receiver || null;
      this.talkForm.receiverName = receiverName || null;
      this.talkForm.replyId = replyId || null;
      this.talkForm.content = null;
      this.talkForm.attachmentDTOs = [];*/
      this.initTalkForm(receiver, receiverName, replyId)
      this.showTalkDialog = true;
      if (flag == 1) {
        let opeaBtnDom = this.$refs.opeaBtn;
        opeaBtnDom && opeaBtnDom.scrollIntoView();
      }
    },
    initTalkForm(receiver, receiverName, replyId) {
      this.talkForm.receiver = receiver || null;
      this.talkForm.receiverName = receiverName || null;
      this.talkForm.replyId = replyId || null;
      this.talkForm.content = null;
      this.talkForm.attachmentDTOs = [];
    },
    submitTalkForm() {
      let that = getTarget(this);
      var procInstId = this.wfInfo.procInstId;
      var taskId = this.wfInfo.taskId;

      if (!this.talkForm.receiver) {
        that.$message({
          message: this.$t2('请选择接收人', 'components.wf.talkWarnMsg1'),
          type: "error",
          duration: 2 * 1000,
        });
        return false;
      }
      if (!this.talkForm.content) {
        that.$message({
          message: this.$t2('请输入沟通内容', 'components.wf.talkWarnMsg2'),
          type: "error",
          duration: 2 * 1000,
        });
        return false;
      }

      var data = {
        taskId: taskId,
        uuid: this.wfInfo.uuid,
        receiver: this.talkForm.receiver,
        receiverName: this.talkForm.receiverName,
        replyId: this.talkForm.replyId,
        content: this.talkForm.content,
        attachmentDTOs: this.talkForm.attachmentDTOs,
        notifyType: "wfLinkup",
      };
      this.showTalkDialog = false;
      that.$http({
        url: this.current_prefix + "/wf_linkup/save",
        data: data,
        method: "post",
        isLoading: true,
        success: (resultMsg) => {
          that.$message({
            message: resultMsg.content,
            type: "success",
            duration: 500,
            onClose: (t) => {
              this.reloadContent();
              this.closeWinOnCheck(5);
            },
          });
        },
      });
    },
    openTalkUserDialog() {
      this.showTalkUserDialog = true;
    },
    confirmTalkUserDialog(rows) {
      if (rows.length > 0) {
        let row = rows[0];
        if (this.talkForm.receiver != row.id) {
          this.talkForm.replyId = null;
        }
        this.talkForm.receiver = row.id;
        this.talkForm.receiverName = row.nickName;
      }
    },
    confirmUrging() {
      this.reloadContent();
    },
    confirmDeleteTaskUser() {
      this.reloadContent();
    },
    confirmAddTaskUser(rows) {
      this.addIncreaseSignUsers = rows;
      this.addIncreaseSignForm.userNickNames = rows.map(row => row.nickName).join(',');
      // this.reloadContent();
    },
    submitAddTaskUserForm(flag) {
      let that = getTarget(this);
      let userIds = this.addIncreaseSignUsers.map((checkRow) => checkRow.id);
      if (userIds.length == 0) {
        that.$message({
          message: this.$t2('请选择候选人', 'components.wf.addIncreaseSignWarnMsg1'),
          type: "error",
          duration: 2000,
          onClose: (t) => {
          },
        });
        return false;
      }
      let toDo = () => {
        var data = JSON.stringify({
          uuid: this.wfInfo.uuid,
          taskId: this.wfInfo.taskId,
          userIds: userIds,
          suggestion: this.addIncreaseSignForm.opinion

        });
        this.agreeDialogVisible = false;
        that.$http({
          url: this.current_prefix + "/wf/addIncreaseSign",
          data: data,
          method: "post",
          loadingTarget: document.body,
          headers: {
            "Content-Type": "application/json;charset=utf-8",
          },
          isLoading: true,
          success: (resultMsg) => {
            that.$message({
              message: resultMsg.content,
              type: "success",
              duration: 500,
              onClose: (t) => {
                this.reloadContent();
              },
            });
          },
        });
      }
      if (flag === 0) {
        toDo();
      } else {
        that.$baseConfirm(this.$t2('您确定要加签吗？', 'components.wf.addIncreaseSignConfirmTip')).then(() => {
          toDo();
        });
      }
    },
    openSetCandidateDialog(operateType) {
      this.operateType = operateType;
      this.showSetCandidateDialog = true;
    },
    closeSetCandidateDialog() {
      this.showSetCandidateDialog = false;
      this.reloadContent();
    },
    openRevokeDialog(operateType) {
      this.operateType = operateType;
      this.revokeForm = {opinion: null}
      this.revokeDialogVisible = true;
    },
    subRevokeForm(flag) {
      //撤回
      let that = getTarget(this);
      let toDo = () => {
        var data = JSON.stringify({
          uuid: this.wfInfo.uuid,
          taskId: this.wfInfo.taskId,
          suggestion: this.revokeForm.opinion,
        });
        this.revokeDialogVisible = false;
        that.$http({
          url: this.current_prefix + "/wf/revoke",
          data: data,
          method: "post",
          loadingTarget: document.body,
          headers: {
            "Content-Type": "application/json;charset=utf-8",
          },
          isLoading: true,
          success: (resultMsg) => {
            that.$message({
              message: resultMsg.content,
              type: "success",
              duration: 500,
              onClose: (t) => {
                this.reloadContent();
              },
            });
          },
        });
      }
      if (flag === 0) {
        toDo();
      } else {
        that.$baseConfirm(this.$t2('您确定要撤回吗？', 'components.wf.revokeConfirmTip')).then(() => {
          toDo();
        });
      }
    }
  }
}
</script>

<style scoped>
::v-deep .form-box.el-form .el-form-item .el-form-item__label {
  width: 70px
}
</style>
