<template>
  <div id="headerBtn">
    <el-dropdown>
      <span class="el-dropdown-link">
        <i class="el-icon-s-fold"></i>流程<i class="el-icon-arrow-down"></i>
      </span>
      <el-dropdown-menu slot="dropdown" v-if='!!processInfoData && !processInfoData.pid && !processInfoData.processType'>
                      <el-dropdown-item
                        v-if="
                          processItem.state == '5' ||
                          processItem.state == '7' ||
                          processItem.state == '9' ||
                          processItem.state == '12'
                        "
                        @click.native="
                          operatingprocess(processItem, 'bpaPublish')
                        "
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/processOut.png" />
                          </i>
                          流程发布
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="processItem.state == '1' || processItem.state == '8'"
                        @click.native="operatingprocess(processItem, 'abolish')"
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/void.png" />
                          </i>
                          作废
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="processDoc(processItem, 'view')"
                        v-if="processItem.state != '2'"
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/docView.png" />
                          </i>
                          文档预览
                        </span>
                      </el-dropdown-item>
                      <!-- <el-dropdown-item
                        @click.native="chartIdentify(processItem, 'img')"
                      >
                        <span class="eldropdown">{{
                          $t("ImageResolution")
                        }}</span>
                      </el-dropdown-item> -->

                      <!-- <el-dropdown-item
                        @click.native="chartIdentify(processItem, 'word')"
                      >
                        <span class="eldropdown">{{ $t("WordParsing") }}</span>
                      </el-dropdown-item> -->
                      <el-dropdown-item
                        @click.native="processCardIn(processItem)"
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/processChartIn.png" />
                          </i>
                          流程图导入
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item @click.native="processIn(processItem)">
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/processIn.png" />
                          </i>
                          流程导入
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="chartIdentify(processItem, 'viso')"
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/viso.png" />
                          </i>
                          智能识别
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="processDoc(processItem, 'download')"
                        v-if="processItem.state !== '2'"
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/docDownLoad.png" />
                          </i>
                          文档下载
                        </span>
                      </el-dropdown-item>

                      <el-dropdown-item
                        v-if="
                          processItem.state == '5' ||
                          processItem.state == '7' ||
                          processItem.state == '9' ||
                          processItem.state == '11' ||
                          processItem.state == '12'
                        "
                        @click.native="operatingprocess(processItem, 'clear')"
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/clear.png" />
                          </i>
                          清空
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="toBack(processItem)"
                        v-if="
                          (processItem.state == '5' && !!processItem.submitby) ||
                          processItem.state == '7' ||
                          processItem.state == '9' ||
                          processItem.state == '11' ||
                          processItem.state == '12'
                        "
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/reduction.png" />
                          </i>
                          还原
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="processOut(processItem)"
                        v-if="
                          processItem.state === '1' || processItem.state === '8'
                        "
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/processOut.png" />
                          </i>
                          流程导出
                        </span>
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click.native="processCardOut(processItem)"
                        v-if="
                          processItem.state === '1' || processItem.state === '8'
                        "
                      >
                        <span class="eldropdown">
                          <i>
                            <img src="../../../img/processChartOut.png" />
                          </i>
                          流程图导出
                        </span>
                      </el-dropdown-item>
      </el-dropdown-menu>
      <el-dropdown-menu v-else></el-dropdown-menu>
    </el-dropdown>
    <a href="javascript:void(0)" title="保存" type="save" id="btn_save" class="GooFlow_head_btn">
      <span @click="save('ico_save')">保存</span>
    </a>
    <a href="javascript:void(0)" title="暂存" type="temporalit" id="btn_temporalit" class="GooFlow_head_btn">
      <span @click="save('ico_temporalit')">暂存</span>
    </a>
    <process-in
      v-model="processDialogsVisible"
      :processMethod="processMethod"
      :processId="processId"
      :processState="processState"
      @confirm="processConfirm"
    ></process-in>
    <!-- 智能识别 -->
    <chart-identify
      v-model="chartDialogsVisible"
      :modelid="listid"
      :bpmid="bpmid"
      :upType="upType"
      @closeChart="closeChart"
    >
    </chart-identify>
     <add-process-dialog v-model="isDialogsVisible"
      :processForm=processForm
      :type=addType
      :saveType=saveType
      @confirm=confirmUpdate>
    </add-process-dialog>
  </div>
</template>

<script>
import {
  getProcesslist,
  viewProcessDoc,
  downloadProcessDoc,
  restoreProcess,
  publishProcess,
  publishbpmProcess,
  abolishProcess,
  abolishProcess2,
  clearprocess,
  saveReview,
  saveReview2,
  processStarted,
  releaseVerification,
  getModelapprove,
  requireProcess,
  getPost,
  getstation,
  getDownloadAuthByModelId,
  queryProcessDesignListInfo,
  processSaveAttr
} from '../../api/processDesignCenter'
import {
  getProcessTreeNodeCode,
  getProcessIframeTree
} from '../../api/processTree'
import { getCookie } from '../../utils/utils'
import processIn from "./components/processIn.vue";
import chartIdentify from "./components/chartIdentify.vue";
import addProcessDialog from '../leftNav/components/addProcessDialog.vue'
import {
  baseUrl
} from '../../utils/url'
export default {
   components: {
    processIn,
    chartIdentify,
    addProcessDialog
  },
  data() {
    return {
      userId: getCookie("username"),
      process_bpa_publish: '',
      process_bpm_publish: '',
      process_review: '',
      process_invalid: '',
      bpmListId: '',
      processDialogsVisible: false,
      processMethod: "",
      processId: "",
      processState: "",
      upType: "",
      listid: "",
      bpmid: "",
      chartDialogsVisible: false,
      showProcessEditor: false,
      isDialogsVisible: false,
      processForm : {
        "code":"",
        "custom":"",
        "ename":"",
        "processcode":"",
        "ico":"",
        "managerList":[],
        "consultmanagerList":[],
        "name":"",
        "parentname":"",
        "pid":"",
        "remark":"",
        "sort":"",
        "status":"",
        "vtmpmanager":"",
        "rank":'',
        "updatenewForm":"",
        "systematic":"function",
        "typeid":"2",
        "processoptions":"",
        "rulemanagerList":[],
        "rulename":"",
        "rulecode":"",
        "displaymode":"treeShape"
      },
      addType: 'add',
      saveType: '' // 保存 暂存
    };
  },
  computed: {
    processInfoData() {
      return JSON.parse(sessionStorage.getItem('processInfo')) || null
    },
    processItem() {
      return sessionStorage.getItem('processInfo') ? JSON.parse(sessionStorage.getItem('processInfo')).item : {}
    },
    modelid() {
      return sessionStorage.getItem('processInfo') ? JSON.parse(sessionStorage.getItem('processInfo')).treeId : ''
    },
    host() {
      return baseUrl
    },
  },
  mounted() {
    // 流程发布获取值
    this.getprocessType();
    console.log(this.processItem, 'processItemprocessItem')
  },
  methods:{
    // 重新获取列表数据  更新状态
    getList() {
      getProcesslist({
        filters: [{ key: "modelid", value: this.modelid }],
        orderby: "createon",
        pageNum: 1,
        pageSize: 10,
        sort: "desc",
      }).then((res) => {
        if (!res) return false;
        let val = res.list[0];
        let obj = {
              id: val.bpmid,
              listid: val.id,
              treeId: this.modelid,
              processName: val.name,
              username: '',
              processNum: val.code,
              state: val.state,
              isRead: 'no',
              item: val,
              treeData: sessionStorage.getItem('processInfo').treeData || {}
        }
        if (val.state === "2") {
            processSaveAttr({
              // id: item.bpmid,
              bpo: val.bpo,
              bponame: val.bponame,
              code: val.code,
              listid: val.id,
              modelid: val.id,
              signer: this.userid,
              signername: this.username,
              version: val.version,
              name: val.name,
              modelInstitution: {},
            }).then((rt) => {
              if (!rt) return false;
              obj.id = rt.split(",")[0]
              obj.state = '5';
              obj.item.state = '5';
              this.updateJsonData(obj)
            });
          } else {
            this.updateJsonData(obj)
          }


      });
    },
    // 解决清空之后 bpmid为空
    updateJsonData (obj) {
        let processTabMenu = JSON.parse(sessionStorage.getItem('processTabMenu')) || []
              if (processTabMenu) {
                let tabMenus = processTabMenu.map(item => item.listid).join(',')
                if (tabMenus.indexOf(obj.listid) === -1) {
                  processTabMenu.push(obj)
                } else {
                  processTabMenu.forEach(item => {
                    if (item.listid === obj.listid) {
                      item = obj
                    }
                  })
                }
              }
        sessionStorage.setItem('processTabMenu', JSON.stringify(processTabMenu))
        sessionStorage.setItem('processInfo', JSON.stringify(obj))
        window.getProcessJson('Update')
    },
    // 控流程发布的方式
    getprocessType() {
      requireProcess({
        filters: [],
      }).then((res) => {
        if (!res) return false;
        // bpa发布
        let index1 = res.list.findIndex(
          (v) =>
            v.name === 'bpa发布' ||
            v.name === 'bpa发布' + " "
        );
        // 流程评审
        let index2 = res.list.findIndex((v) => v.name === "流程评审");
        // 流程作废
        let index3 = res.list.findIndex((v) => v.name === "流程作废");
        // bpm发布
        let index4 = res.list.findIndex(
          (v) =>
            v.name === 'bpm发布' ||
            v.name === 'bpm发布' + " "
        );
        if (index1 != -1) {
          this.process_bpa_publish = res.list[index1].choosed;
        } else {
          this.process_bpa_publish = "direct";
        }
        if (index2 != -1) {
          this.process_bpm_publish = res.list[index1].choosed;
        } else {
          this.process_bpm_publish = "direct";
        }
        if (index3 != -1) {
          this.process_review = res.list[index1].choosed;
        } else {
          this.process_review = "direct";
        }
        if (index4 != -1) {
          this.process_invalid = res.list[index1].choosed;
        } else {
          this.process_invalid = "direct";
        }
      });
    },
    // 流程操作
    operatingprocess(data, type) {
      this.versionId = data.bpmid;
      this.versionObj = data;
      if (type === "bpaPublish") {
        getModelapprove("4").then((res) => {
          if (!res) return false;
          if (res.choosed === "direct") {
            this.$confirm(
              '确认发布该条流程吗？',
              '提 示',
              {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                type: "warning",
              }
            ).then(() => {
              this.openBpmUrl(data.state, data.id, data.bpmid, "direct");
            });
          } else {
            this.bpmListId = data.id;
            releaseVerification(data.id).then((res) => {
              if (res) {
                this.toFlow();
              }
            });
          }
        });
      } else if (type === "bpmPublish") {
        // if (data.state === "1") {
        //   this.$message.error(
        //     this.$t("hintText.aPublishedProcessCannotBePublishedAgain")
        //   );
        //   return;
        // }
        this.$confirm(
          '确认发布该条流程吗？',
          '提 示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: "warning",
          }
        ).then(() => {
          this.openBpmUrl4(data.state, data.id, data.bpmid, "direct");
        });
      } else if (type === "abolish") {
        this.$confirm(
          '确认作废该条流程吗？',
          '提 示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: "warning",
          }
        ).then(() => {
          this.openBpmUrl2(data.state, data.id, data.bpmid, "direct");
        });
      } else if (type === "clear") {
        this.$confirm(
          '确认清空该条流程的数据吗？',
          '提 示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: "warning",
          }
        ).then(() => {
          clearprocess(data.id).then((res) => {
            if (!res) return false;
            this.$message({
              type: "sucess",
              message: '卡片信息清空成功',
            });
            this.getList()
          });
        });
      } else if (type === "review") {
        this.$confirm(
          '确认评审该条流程吗？',
          '提 示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: "warning",
          }
        ).then(() => {
          window.openBpmUrl3(data.state, data.id, data.bpmid, "direct");
        });
      }
    },
    // 流程文档
    processDoc(data, type) {
      if (type === "download") {
        getModelapprove("5").then((resp) => {
          if (!resp) return false;
          if (resp.choosed === "direct") {
            downloadProcessDoc({
              id: data.bpmid,
              json: "",
              listid: data.id,
              name: "",
              num: "",
              userid: "",
              language: "zh-CN",
            }).then((res) => {
              if (!res) return false;
              window.open(res);
            });
          } else {
            getDownloadAuthByModelId(data.modelid, this.userId).then((res) => {
              if (res === "0") {
                this.$confirm(
                  "您暂无此流程文档的下载权限，是否确认申请？",
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }
                )
                  .then(() => {
                    window.open(
                      `${window.location.origin}${window.location.pathname}#/processForm/start?name=%E6%96%87%E6%A1%A3%E6%9D%83%E9%99%90%E5%AE%A1%E6%89%B9&processName=WDQXSP&projectName=WDQXSP&modelid=${data.modelid}&version=${data.version}`
                    );
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "已取消",
                    });
                  });
              } else if (res === "1") {
                downloadProcessDoc({
                  id: data.bpmid,
                  json: "",
                  listid: data.id,
                  name: "",
                  num: "",
                  userid: "",
                  language: "zh-CN",
                }).then((res) => {
                  if (!res) return false;
                  window.open(res);
                });
              } else {
                this.$message({
                  type: "warning",
                  message: "当前文档的申请权限正在审批中，暂不可下载！",
                });
              }
            });
          }
        });
      } else if (type === "view") {
        viewProcessDoc({
          id: data.bpmid,
          json: "",
          listid: data.id,
          name: "",
          num: "",
          userid: "",
          language: "zh-CN",
        }).then((res) => {
          if (!res) return false;
          window.open(res);
        });
      }
    },
    // 流程导入
    processIn(row) {
      this.processDialogsVisible = true;
      this.processMethod = '流程导入';
      this.processId = row.id;
    },
    // 流程导出
    processOut(row) {
      let modelid = row.modelid || this.modelid
      window.open(
        this.host +
          "/modellist/exportProcessJsonToTxt/" +
          modelid+
          `?username=${this.userId}`
      );
      // exportProcessJsonToTxt(this.modelid).then(res => {
      //   if (!res) return false
      //   this.$message({
      //     type: 'success',
      //     message: '导出成功!'
      //   })
      // })
    },
    // 流程图导入
    processCardIn(row) {
      this.processDialogsVisible = true;
      this.processMethod = '流程图导入';
      this.processId = row.id;
      this.processState = row.state;
    },
    processConfirm(data) {
      this.getList()
    },
    // 智能识图
    chartIdentify(item, i) {
      this.upType = i;
      this.listid = item.id;
      this.bpmid = item.bpmid;
      this.chartDialogsVisible = true;
    },
    // l流程图识别跳转
    closeChart(data) {
      // this.showProcessEditor = true;
      // this.lisdata = [
      //   {
      //     name: this.processItem.name,
      //     id: this.bpmid,
      //     listid: this.listid,
      //     treeId: this.modelid,
      //     state: this.processItem.state,
      //     processNum: this.processItem.code,
      //   },
      // ];
      // this.iframeSrc = data;
      this.getList()
    },
    // 流程图导出
    processCardOut(row) {
      let modelid = row.modelid || this.modelid
      window.open(
        this.host +
          "/listhistory/exportProcessChartJsonToTxt/" +
          modelid +
          `?username=${this.userId}`
      );
      // exportProcessChartJsonToTxt(this.modelid).then(res => {
      //   if (!res) return false
      //   this.$message({
      //     type: 'success',
      //     message: '导出成功!'
      //   })
      // })
    },
     // 还原
    toBack(data) {
      this.$confirm(
        '确认还原该条流程吗？',
        '提示',
        {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: "warning",
        }
      ).then(() => {
        restoreProcess(data.id).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '还原成功！',
          });
          this.getList();
        });
      });
    },
    toFlow() {
      getPost().then((rt) => {
        if (rt.status === "200") {
          if (rt.data && rt.data.length > 0) {
            if (rt.data.length > 1) {
              this.itemData = rt.data;
              this.dialogVisible = true;
            } else {
              this.toHref(rt.data[0].id);
            }
          } else {
            this.$message.error(
              '岗位信息缺失，请联系管理员'
            );
          }
        }
      });
    },
    toHref(pid) {
      let routeData = this.$router.resolve({
        name: "processFormStart",
        query: {
          name: "流程审批管理流程",
          processName: "LCSPGLLC",
          projectName: "LCSPGLLC",
          pid: pid,
          listId: this.bpmListId,
        },
      });
      // window.open(routeData.href, "_blank");
      let a = document.createElement("a");
      // 给创建好的a标签赋值
      a.setAttribute("href", routeData.href);
      // 设置css 隐藏属性
      a.setAttribute("style", "display:none");
      // 设置 a标签为新窗口打开
      a.setAttribute("target", "_blank");
      // 将设置好的a标签，添加到 body 内
      document.body.appendChild(a);
      // 模拟点击
      a.click();
      // 移除a标签
      a.parentNode.removeChild(a);
    },
    // bpa发布
    openBpmUrl(state, listid, bpmid, type) {
      if (this.process_bpa_publish === "bpm") {
        /* ------------------走发布流程代码---------------------开始 */
        // let lang = '';
        // if (translateCookie() === 'en') {
        //   lang = 'JnJlcXVlc3RfbG9jYWxlPWVu';
        // } else if (translateCookie() === 'zh-CN') {
        //   lang = 'JnJlcXVlc3RfbG9jYWxlPXpoX0NO';
        // }
        // if (state == '3' || state == '4') {
        //   let urlStr = '/bpm/creater-process!apply.action?processname=SPLCProcess&processnodename=Start&projectname=SPLCProject&defaultOrganization=39390&baProcessId='+listid+'&state=' + (state == 3 ? 3:4);
        //   let str = self.bpmurl + window.localStorage.getItem('loginInfo')+'&param=';
        //   window.open(str + Base64.encode(urlStr) + lang);
        // }
        // else if (state == '5') {
        //   let urlStr = '/bpm/creater-process!apply.action?processname=ZFLCProcess&processnodename=Start&projectname=ZFLCProject&defaultOrganization=39390&baProcessId='+listid;
        //   let str = self.bpmurl  + window.localStorage.getItem('loginInfo')+'&param=';
        //   window.open(str + Base64.encode(urlStr) + lang);
        // } else if (state == '7' || state == '8') {
        //   $.ajax({
        //     type: 'post',
        //     data: JSON.stringify({
        //       'docid': listid,
        //       'type': 'process',
        //       'userid': getCookie('username')
        //     }),
        //     dataType: 'json',
        //     contentType: 'application/json;charset=UTF-8',
        //     url: 'http://http://10.226.57.77/tmportal/regulationBpm/getBpmUrl ',
        //     success: function (data) {
        //       let urlStr = data.url;
        //       let str = url  + window.localStorage.getItem('loginInfo')+'&param=';
        //       window.open(str + Base64.encode(urlStr) + lang);
        //     }
        //   })
        // }
        getstation(this.userid).then((res) => {
          if (!res) return false;
          processStarted({
            bizData: { FBLCBPAID: listid },
            positionId: res[0].id,
            processName: "流程发布审批",
            processNodeName: "Start",
            projectName: "Lcfbsp",
            subject: "流程发布审批",
            userId: this.userid,
          }).then((res) => {
            if (!res) return false;
            this.$message({
              type: "sucess",
              message: "发布成功!",
            });
            this.getList();
          });
        });
        /* ------------------直接走发布流程代码---------------------结束 */
      } else if (this.process_bpa_publish === "direct") {
        publishProcess({
          id: listid,
        }).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '发布成功!',
          });
          this.getList();
        });
        // 外部系统审核
      } else if (this.process_bpa_publish === "directbpm") {
        /* ------------------发布调用bpm的接口---------------------开始 */
        // publishbpmProcess({
        //   listid: bpmid,
        //   swimid: listid
        // }).then(res => {
        //   console.log(res)
        //   this.$message({
        //     type: 'success',
        //     message: '发布成功!'
        //   })
        // })
        /* ------------------发布调用bpm的接口---------------------结束 */
      }
    },
    // bpm发布
    openBpmUrl4(state, listid, bpmid, type) {
      if (this.process_bpm_publish === "bpm") {
        /* ------------------走发布流程代码---------------------开始 */
        // let lang = '';
        // if (translateCookie() === 'en') {
        //   lang = 'JnJlcXVlc3RfbG9jYWxlPWVu';
        // } else if (translateCookie() === 'zh-CN') {
        //   lang = 'JnJlcXVlc3RfbG9jYWxlPXpoX0NO';
        // }
        // if (state == '3' || state == '4') {
        //   let urlStr = '/bpm/creater-process!apply.action?processname=SPLCProcess&processnodename=Start&projectname=SPLCProject&defaultOrganization=39390&baProcessId='+listid+'&state=' + (state == 3 ? 3:4);
        //   let str = self.bpmurl + window.localStorage.getItem('loginInfo')+'&param=';
        //   window.open(str + Base64.encode(urlStr) + lang);
        // }
        // else if (state == '5') {
        //   let urlStr = '/bpm/creater-process!apply.action?processname=ZFLCProcess&processnodename=Start&projectname=ZFLCProject&defaultOrganization=39390&baProcessId='+listid;
        //   let str = self.bpmurl  + window.localStorage.getItem('loginInfo')+'&param=';
        //   window.open(str + Base64.encode(urlStr) + lang);
        // } else if (state == '7' || state == '8') {
        //   $.ajax({
        //     type: 'post',
        //     data: JSON.stringify({
        //       'docid': listid,
        //       'type': 'process',
        //       'userid': getCookie('username')
        //     }),
        //     dataType: 'json',
        //     contentType: 'application/json;charset=UTF-8',
        //     url: 'http://http://10.226.57.77/tmportal/regulationBpm/getBpmUrl ',
        //     success: function (data) {
        //       let urlStr = data.url;
        //       let str = url  + window.localStorage.getItem('loginInfo')+'&param=';
        //       window.open(str + Base64.encode(urlStr) + lang);
        //     }
        //   })
        // }
        getstation(this.userid).then((res) => {
          if (!res) return false;
          processStarted({
            bizData: { FBLCBPAID: listid },
            positionId: res[0].id,
            processName: "流程发布审批",
            processNodeName: "Start",
            projectName: "Lcfbsp",
            subject: "流程发布审批",
            userId: this.userid,
          }).then((rt) => {
            if (!rt) return false;
            this.$message({
              type: "sucess",
              message: '发布成功!',
            })
            this.getList();
          })
        })
        /* ------------------直接走发布流程代码---------------------结束 */
      } else if (this.process_bpm_publish === "direct") {
        publishProcess({
          id: listid,
        }).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '发布成功!',
          })
          this.getList();
        })
        // 外部系统审核
      } else if (this.process_bpm_publish === "directbpm") {
        /* ------------------发布调用bpm的接口---------------------开始 */
        // publishbpmProcess({
        //   listid: bpmid,
        //   swimid: listid
        // }).then(res => {
        //   console.log(res)
        //   this.$message({
        //     type: 'success',
        //     message: '发布成功!'
        //   })
        // })
        /* ------------------发布调用bpm的接口---------------------结束 */
      }
    },
     // 作废
    openBpmUrl2 (state, listid, bpmid, type) {
      // 直接走作废流程
      if (this.process_invalid === "direct") {
        abolishProcess({ id: listid }).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '作废成功!',
          });
          this.getList();
        });
        /* ------------------走bpm的作废流程---------------------结束 */
      } else if (this.process_invalid === "bpm") {
        abolishProcess2(listid, this.postId).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '作废成功!',
          });
          this.getList();
        });
        // 外部系统审核
      } else if (this.process_invalid === "directbpm") {
        /* ------------------发布调用bpm的接口---------------------开始 */
        // publishbpmProcess({
        //   listid: bpmid,
        //   swimid: listid
        // }).then(res => {
        //   console.log(res)
        //   this.$message({
        //     type: 'success',
        //     message: '发布成功!'
        //   })
        // })
        /* ------------------发布调用bpm的接口---------------------结束 */
      }
    },
    // 评审
    openBpmUrl3(state, listid, bpmid, type) {
      // 直接走评审流程
      if (this.process_review === "direct") {
        saveReview2(listid).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '评审成功!',
          });
          this.getList();
        });
      } else if (this.process_review === "bpm") {
        // listId:流程id和postId:岗位id bpmid
        saveReview(listid, this.postId).then((res) => {
          if (!res) return false;
          this.$message({
            type: "success",
            message: '正在评审中!',
          });
          this.getList();
        });
        // 外部系统审核
      } else if (this.process_review === "directbpm") {
        /* ------------------发布调用bpm的接口---------------------开始 */
        // publishbpmProcess({
        //   listid: bpmid,
        //   swimid: listid
        // }).then(res => {
        //   console.log(res)
        //   this.$message({
        //     type: 'success',
        //     message: '发布成功!'
        //   })
        // })
        /* ------------------发布调用bpm的接口---------------------结束 */
      }
    },
    save (type) {
      this.saveType = type
      let flag = window.isNodesInProcess(null, null, this.saveType)
      if (!flag) {
        return
      }
      let processInfo = JSON.parse(sessionStorage.getItem('processInfo'))
      if (!!processInfo && !!processInfo.pid) { // 表示的是自建
        this.addType = 'selfBuilt'
        this.processForm.pid = processInfo.pid;
        this.processForm.status = processInfo.treeData.state;
        this.processForm.parentname = processInfo.treeData.name;
        this.processForm.rank = processInfo.treeData.rank + 1;
        getProcessTreeNodeCode(processInfo.pid).then(res => {
          if (!res) return
          this.isDialogsVisible = true;
          this.processForm.name = "";
          this.processForm.ename = "";
          this.processForm.code = res.code;
          if (res.code.substr(2, 1) || res.code.substr(3, 1) == 0) {
            this.processForm.rank = 2;
          }
          if (processInfo.item.id == "79957553BD2F3978E053BF1A13ACD486") {
            this.processForm.businessLayer = true;
            this.processForm.code = "";
          } else {
            this.processForm.businessLayer = false;
          }
        });
      } else if (!processInfo) {
            this.addType = 'new'
            this.processForm = {
              name: '',
              typeid: '2',
              systematic: 'function',
              displaymode: 'treeShape'
            }
            this.isDialogsVisible = true;
      } else if ( processInfo.processType=== 'busObj') { // 业务对象
        this.saveBusObj(type)
      } else {
        window.onBtnSaveClick(null, null, type) // type  'ico_save' ico_temporalit
      }
    },
    confirmUpdate(data) {
      console.log(data)
      this.onLoad()
    },
    async onLoad() {
			await this.saveObj()
			// await this.btnSave()
      // await this.processJson()
		},
    saveObj (type) {
      return new Promise((resolve, reject) => {
      let processInfo = JSON.parse(sessionStorage.getItem('processInfo'))
      getProcessIframeTree(processInfo.pid).then((resp) => {
        if (!resp) return
        let processData = resp[resp.length-1] // 新增的为最后一条  没有好的解决方法
        queryProcessDesignListInfo(processData.id, {
          fullFilters: [
            {
              filters: [
                {
                  key: "code",
                  opt: "LIKE",
                  type: "S",
                  value: '',
                  logic: "or",
                },
                {
                  key: "name",
                  opt: "LIKE",
                  type: "S",
                  value: '',
                  logic: "or",
                },
              ],
              logic: "and",
            },
          ],
          logic: "and",
          pageNum: 1,
          pageSize: 10,
          sort: "desc"
        }).then((res) => {
          if (!res) return false;
          let val = res.list[0];
          let obj = {
                id: val.bpmid,
                listid: val.id,
                treeId: processData.id,
                processName: val.name,
                username: '',
                processNum: val.code,
                state: val.state,
                isRead: 'no',
                version: val.version,
                item: val,
                treeData: processData,
                pidInfo: processInfo.pidInfo
          }
           if (val.state === "2") {
            processSaveAttr({
              // id: item.bpmid,
              bpo: val.bpo,
              bponame: val.bponame,
              code: val.code,
              listid: val.id,
              modelid: val.id,
              signer: this.userid,
              signername: this.username,
              version: val.version,
              name: val.name,
              modelInstitution: {},
            }).then((rt) => {
              if (!rt) return false;
              obj.id = rt.split(",")[0]
              obj.state = '5';
              obj.item.state = '5';
              sessionStorage.setItem('processInfo', JSON.stringify(obj))
              this.saveBpmId (obj, this.saveType)
            });
          } else {
            sessionStorage.setItem('processInfo', JSON.stringify(obj))
            this.saveBpmId (obj, this.saveType)
          }

        })
      })
      });
    },
    saveBpmId (obj, type){
      let that = this
      let processTabMenu = JSON.parse(sessionStorage.getItem('processTabMenu')) || []
          // processTabMenu.forEach((item, index) => {
          //   console.log(!!item.pid, item, 1111111111)
            if (!!obj.pidInfo) {
              // 保存session前先把改流程加到父级流程的引用流程里
              var resData = {}
              jq.ajax({
                type: "POST",
                url: basFlow.baseUrl + "/listhistory/getMyJson/" + obj.pidInfo.listPid + '?username=' + getCookie("username"),
                async: false,// 此处设为同步 是为了获取加载好的数据的泳道的高度
                success: function (data) {
                    if (data.data.json) {
                        resData = JSON.parse(data.data.json);
                        console.log(resData)
                    } else {
                        resData = null
                    }
                    if (!resData.controls || resData.controls.length === 0) {
                      return
                    }
                    resData.controls.forEach(list => {
                      if (list.id === obj.pidInfo.id) {
                        console.log(list.id, obj.pidInfo.id, obj, '1121')
                        // list.processGroup.push({
                        //   pid: obj.pidInfo.pid,
                        //   id: obj.treeId,
                        //   name: obj.processName
                        // })
                        list.processGroup = [{
                          pid: obj.pidInfo.pid,
                          id: obj.treeId,
                          name: obj.processName
                        }]
                      }
                    })
                }
              })
              jq.ajax({
                type: "POST",
                url: basFlow.baseUrl + "/listhistory/saveHistory?username=" + getCookie("username"),
                async: false,
                contentType: 'application/json;',
                data: JSON.stringify({
                  "listid": obj.pidInfo.bpmid,
                  "json": JSON.stringify(resData),
                  "swimid": obj.pidInfo.listPid,
                  "swimlane": getCookie("qiehuan"),
                }),
                success: function (data) {
                  if (typeof data === 'string') {
                    that.$message({
                      type: "warning",
                      message: data,
                    });
                  }
                  if (data) {
                    that.$message({
                      type: "success",
                      message: type === 'ico_temporalit' ? '暂存成功！' : "保存成功！",
                    });
                  } else {
                    that.$message({
                      type: "success",
                      message: type === 'ico_temporalit' ? '暂存失败！' : "保存失败！",
                    });
                  }
                }
              })
              if (processTabMenu) {
                // let tabMenus = processTabMenu.map(item => item.listid).join(',')
                // if (tabMenus.indexOf(obj.listid) === -1) {
                //   processTabMenu.push(obj)
                //   sessionStorage.setItem('processTabMenu', JSON.stringify(processTabMenu))
                // } else { // 设置只能存在一个自建流程tab  更新父级的内容
                //   processTabMenu.forEach(item => {
                //     if (item.listid === obj.listid) {
                //       item = obj
                //     }
                //   })
                //   sessionStorage.setItem('processTabMenu', JSON.stringify(processTabMenu))
                // }
                processTabMenu.forEach((item, index) => {
                  if (!!item.pid) {
                    item = obj
                    this.$set(processTabMenu, index, obj)
                    sessionStorage.setItem('processTabMenu', JSON.stringify(processTabMenu))
                  }
                })
              }
              // sessionStorage.setItem('processTabMenu', JSON.stringify(processTabMenu))
              window.onBtnSaveClick(null, null, type, 'bpmid')
            }
          // })
    },
    saveBusObj (type) {
      let that = this
      let processTabMenu = JSON.parse(sessionStorage.getItem('processTabMenu')) || []
      let parentItem = !sessionStorage.getItem('processInfo') ? {} : JSON.parse(sessionStorage.getItem('processInfo'))
      let chartJson = window.chartJson()
      console.log(chartJson, parentItem)
      var resData = {}
      jq.ajax({
           type: "POST",
           url: basFlow.baseUrl + "/listhistory/getMyJson/" + parentItem.item.listid + '?username=' + getCookie("username"),
           async: false,// 此处设为同步 是为了获取加载好的数据的泳道的高度
           success: function (data) {
               if (data.data.json) {
                   resData = JSON.parse(data.data.json);
                   console.log(resData)
               } else {
                   resData = null
               }
               if (!resData.controls || resData.controls.length === 0) {
                 return
               }
               resData.controls.forEach(item => {
                 if (item.id === parentItem.id) {
                   console.log(item.id, parentItem.id)
                   if (chartJson.controls.length > 0) {
                     chartJson.controls.forEach(jsonItem => {
                      delete jsonItem.processGroupList
                      delete jsonItem.messageFileType
                       if (jsonItem.type === 'KCP') {
                        console.log(jsonItem.keyControl, 'jsonItem.keyControl')
                        item.isKeyCtrl = jsonItem.keyControl.length > 0 ? true : false
                        item.keyControl = jsonItem.keyControl
                       }
                       if (jsonItem.type === 'KSF') {
                        item.isKeyKSFCtrl = jsonItem.keyKSFControl.length > 0 ? true : false
                        item.keyKSFControl = jsonItem.keyKSFControl
                       }
                       if (jsonItem.type === 'processInput') {
                         console.log(jsonItem.inputDesc, 'jsonItem.inputDesc')
                         item.inputDesc = jsonItem.inputDesc
                         item.input = jsonItem.input || []
                       }
                       if (jsonItem.type === 'processOutput') {
                         item.outputDesc = jsonItem.outputDesc
                         item.output = jsonItem.output || []
                       }
                       if (jsonItem.type === 'processForm') {
                         item.messagefileForm = jsonItem.messagefileForm
                         item.messageFile = jsonItem.messageFile || []
                       }
                       if (jsonItem.type === 'processTool') {
                         item.modelListToolsDtos = jsonItem.modelListToolsDtos || []
                       }
                     })
                   }
                   item.busObjData = chartJson
                 }
               })
               console.log(resData, 'resDataresDataresData')
               console.log(chartJson, 'chartJsonchartJson')
           }
      })
      console.log(chartJson, 'chartJsonchartJsonchartJson')
      jq.ajax({
            type: "POST",
            url: basFlow.baseUrl + "/listhistory/saveHistory?username=" + getCookie("username"),
            async: false,
            contentType: 'application/json;',
            data: JSON.stringify({
              "listid": parentItem.item.id,
              "json": JSON.stringify(resData),
              "swimid": parentItem.item.listid,
              "swimlane": getCookie("qiehuan"),
            }),
            success: function (data) {
              if (typeof data === 'string') {
                that.$message({
                  type: "warning",
                  message: data,
                });
              }
              if (data) {
                that.$message({
                  type: "success",
                  message: type === 'ico_temporalit' ? '暂存成功！' : "保存成功！",
                });
              } else {
                that.$message({
                  type: "success",
                  message: type === 'ico_temporalit' ? '暂存失败！' : "保存失败！",
                });
              }
              parentItem.busObjData = chartJson
              processTabMenu.forEach(item => {
                if (item.listid === parentItem.listid) {
                  item.busObjData = chartJson
                }
              })
              sessionStorage.setItem('chartJson', JSON.stringify(chartJson))
              sessionStorage.setItem('processInfo', JSON.stringify(parentItem))
              sessionStorage.setItem('processTabMenu', JSON.stringify(processTabMenu))
            }
          })
    },
    btnSave(){
      return new Promise((resolve, reject) => {
         window.onBtnSaveClick(null, null, 'ico_save')
      });
    },
    processJson(){
      return new Promise((resolve, reject) => {
        window.getProcessJson('Update');
      });
    }
  },
  watch: {
  }

};
</script>
<style lang='scss' scoped>
#headerBtn {
  position:relative;
  // width: 90px;
  // width: 152px;
   width: 215px;
  height: 40px;
  display: block;
  float: left;
  &:after{
    position: absolute;
    display: block;
    content: '';
    width: 1px;
    height: 14px;
    top: 50%;
    right: -2px;
    transform: translate(0%, -50%);
    background: #F3F3F3;
  }
}
.el-dropdown {
    // width: 100%;
    width: 90px;
    font-size: 13px;
    text-align: center;
    // display: inline-block;
    height: 40px;
    line-height: 46px;
    float: left;
    .el-dropdown-link {
      color: #555555;
      i {
        font-size: 17px;
        margin: 0 4px;
      }
    }
}
.el-dropdown-menu {
      .el-dropdown-menu__item {
        padding: 6px 10px!important;
        line-height: 24px!important;
        .eldropdown {
          color: #555555;
          i {
            float: left;
            img {
              height: 20px;
            }
          }
        }
      }
}
#btn_save {
  width: 58px;
  text-align: center;
  display: inline-block;
  border: 0;
  height: 100%;
  cursor: default;
  padding: 14px 4px 8px;
  span {
    cursor: pointer;
    font-size: 13px;
    color: #555555;
    padding: 0px 12px;
    line-height: 18px;
    &:hover{
    color: #fff;
    background: #E77A4B;
    font-weight: Bold;
    opacity: 1;
    border-radius: 20px;
  }
  }
}
</style>
