<template>
  <div class="workflow-content">
    <div
      class="fd-nav"
      v-if="isView == '' || isView == 'add' || isView == 'edit'"
    >
      <div class="fd-nav-left">
        <!-- <div class="fd-nav-back" v-if="!isApp" @click="toReturn"><i class="anticon anticon-left"></i></div> -->
        <!-- <div class="fd-nav-title">{{workFlowDef.name}}</div> -->
        <div class="fd-nav-title">
          <div class="fd-nav-title-insert">
            <el-input
              ref="workFlowCode"
              v-model="requestObj.wfCode"
              placeholder="请输入流程编码"
              :disabled="isView == 'show'"
            />
          </div>
          <div class="fd-nav-title-insert">
            <el-input
              ref="workFlowName"
              v-model="workFlowDef.name"
              placeholder="定义当前审批流名称"
              :disabled="isView == 'show'"
            />
          </div>
          <!-- <div class="fd-nav-title-insert">
          {{response}}
        </div> -->
        </div>
        <div>
          <!-- {{id}} -->
          <!-- {{workflowData}} -->
        </div>
      </div>
      <!-- <div class="fd-nav-center">
   <div class="fd-nav-container">
    <div class="ghost-bar" style="transform: translateX(300px);"></div>
    <div class="fd-nav-item"><span class="order-num">1</span>基础设置</div>
    <div class="fd-nav-item"><span class="order-num">2</span>表单设计</div>
    <div class="fd-nav-item active"><span class="order-num">3</span>流程设计</div>
    <div class="fd-nav-item"><span class="order-num">4</span>高级设置</div>
   </div>
  </div> -->
      <div
        class="fd-nav-right"
        v-if="isView == '' || isView == 'add' || isView == 'edit'"
      >
        <!-- <button type="button" class="ant-btn button-preview"><span>预 览</span></button> -->
        <button type="button" class="ant-btn button-publish" @click="saveSet">
          <span>发 布</span>
        </button>
      </div>
    </div>
    <div
      class="fd-nav-content"
      :class="{ 'box-scale-no-padding': boxScalePaddingTop }"
    >
      <section class="dingflow-design">
        <!-- <div class="zoom">
    <div :class="'zoom-out'+ (nowVal==50?' disabled':'')" @click="zoomSize(1)"></div>
    <span>{{nowVal}}%</span>
    <div :class="'zoom-in'+ (nowVal==300?' disabled':'')" @click="zoomSize(2)"></div>
   </div> -->
        <div
          class="box-scale"
          id="box-scale"
          :style="
            'transform: scale(' +
            nowVal / 100 +
            '); transform-origin: 50% 0px 0px;'
          "
          :class="{ 'box-scale-no-padding': boxScalePaddingTop }"
        >
          <div v-if="isView == 'show'">
            <div class="followWorkShow"></div>
            <followWorkShow
              v-if="isView == 'show'"
              :nodeConfig.sync="nodeConfig"
              :flowPermission.sync="flowPermission"
              :isTried.sync="isTried"
              :tableId="tableId"
            ></followWorkShow>
          </div>

          <div v-else-if="isView == 'justnode'">
            <div class="followWorkShowLinkNode"></div>
            <followWorkShowLinkNode
              :nodeConfig.sync="nodeConfig"
              :flowPermission.sync="flowPermission"
              :isTried.sync="isTried"
              :tableId="tableId"
            ></followWorkShowLinkNode>
          </div>

          <div v-else>
            <div class="nodeWrap"></div>
            <nodeWrap
              :nodeConfig.sync="nodeConfig"
              :flowPermission.sync="flowPermission"
              :isTried.sync="isTried"
              :tableId="tableId"
            ></nodeWrap>
          </div>

          <div class="end-node">
            <div class="end-node-circle"></div>
            <div class="end-node-text">流程结束</div>
          </div>
        </div>
        <!-- E  -->
      </section>
    </div>

    <errorDialog :visible.sync="tipVisible" :list="tipList" />
    <promoterDrawer />
    <approverDrawer :directorMaxLevel="directorMaxLevel" />
    <copyerDrawer />
    <conditionDrawer />
  </div>
</template>

<script>
import errorDialog from "@/components/dialog/errorDialog"; //* 操作错误弹窗
import promoterDrawer from "@/components/drawer/promoterDrawer"; //* 发起人
import approverDrawer from "@/components/drawer/approverDrawer"; //* 审批人设置
import copyerDrawer from "@/components/drawer/copyerDrawer"; //* 抄送人设置
import conditionDrawer from "@/components/drawer/conditionDrawer"; //* 条件设置
import { SaveBill } from "@/api/apis/flowPath";
export default {
  components: {
    errorDialog,
    promoterDrawer,
    approverDrawer,
    copyerDrawer,
    conditionDrawer,
  },
  // props: {
  //  openState: ""
  // },
  data() {
    return {
      boxScalePaddingTop: false, //* 主体盒子顶部 padding
      id: null, //* 审批流 ID
      isView: "show", //* 当前页面是否是查看(默认)页面
      isApp: false, //* 当前页面是否是App打开, 如果是, 隐藏返回按钮
      wfJSON: "",
      wfCode: "",
      type: "add", //* 单据类型, add edit show
      workflowData: "", //*
      isTried: false,
      tipList: [],
      tipVisible: false,
      nowVal: 100, //* 缩放比例
      requestObj: {
        //* 请求参数
        wfJSON: "",
        wfName: "",
        wfCode: "",
      },
      processConfig: {},
      nodeConfig: {},
      workFlowDef: {
        name: "",
      },
      flowPermission: [],
      directorMaxLevel: 0,
      tableId: "",
      dataList: {},
      id:''
    };
  },
  created() {},
  mounted() {
    this.BillType = this.getUrlQuery("op");
    this.id = this.getUrlQuery("id");
    let openType = this.getUrlQuery("type");
    if (this.BillType != null) {
      if (this.BillType.toLowerCase().indexOf("show") >= 0) {
        this.isView = "show";
        this.boxScalePaddingTop = true;
      } else if (this.BillType.toLowerCase().indexOf("view") >= 0) {
        this.isView = "show";
      } else if (this.BillType.toLowerCase().indexOf("justnode") >= 0) {
        this.isView = "justnode";
        this.boxScalePaddingTop = true;
      } else if (this.BillType.toLowerCase().indexOf("add") >= 0) {
        this.isView = "add";
      } else if (this.BillType.toLowerCase().indexOf("edit") >= 0) {
        this.isView = "edit";
      }
    } else {
      this.isView = "add";
    }
    if (this.id != "" && this.id != null) {
      this.id = this.id.replace("#", "").replace("/", "").trim();
    } else {
      //* todo
    }
    //* 移动端打开隐藏 navbar 顶部返回按钮
    if (openType && openType.toLowerCase().match("app")) {
      this.isApp = true;
    }
    this.fetch();
  },
  methods: {
    //* 返回上一页
    toReturn() {
      window.history.back();
    },
    setDataList(el){
      this.dataList.data = JSON.parse(el[0].wfJSON)
      this.requestObj.wfCode = el[0].wfCode
      this.requestObj.wfName = el[0].wfName
      this.id = el[0].id
    },
    //************************************************************************ S 不同业务动作分开请求处理
    async fetch() {
      let rdata = {};
      let requestType = "post";
      switch (this.isView) {
        case "add":
          requestType = "get";
          this.workflowData = `${process.env.BASE_URL}/approvalProcess/emptyData.json`;
          break;
        case "edit":
          this.workflowData = "/Workflow/getList";
          break;
        case "show":
        case "view":
          this.workflowData = "/Workflow/getList";
          break;
        case "justnode":
          rdata.billid = this.id;
          this.workflowData = "/Workflow/SowAuditNote";
          break;
        default:
          break;
      }

      let action = {
        //* 分动作
        add: (res) => {
          action.nodeDataFormat(res.data);
        },
        edit: (res) => {
          let data = res.data;
          data.forEach((item, index) => {
            if (item.id == this.id) {
              action.nodeDataFormat(JSON.parse(item.wfJSON));
              this.requestObj.wfCode = item.wfCode;
            }
            if (index) {
              //* TODO
            }
          });
        },
        show: (res) => {
          action.edit(res);
        },
        view: (res) => {
          action.edit(res);
        },
        justnode: (res) => {
          action.nodeDataFormat(res, res.tableId);
        },
        nodeDataFormat: (nodeConfigData, step) => {
          if (this.isView === "justnode") {
            // nodeConfigData = this.formatNodeConfig(nodeConfigData, step);
            let thisNodeConfig = this.formatNodeConfig(
              nodeConfigData.nodeConfig,
              step
            );
            nodeConfigData.nodeConfig = thisNodeConfig;
          }
          this.processConfig = nodeConfigData;
          let {
            nodeConfig,
            flowPermission,
            directorMaxLevel,
            workFlowDef,
            tableId,
          } = nodeConfigData; // 节点data

          this.nodeConfig = nodeConfig;
          this.flowPermission = flowPermission;
          this.directorMaxLevel = directorMaxLevel;
          this.workFlowDef = workFlowDef;
          this.tableId = tableId;
        },
      };

      /* let aaaa = {"tableId":4,"workFlowDef":{"name":"销售合同审批流"},"directorMaxLevel":4,"flowPermission":[],"nodeConfig":{"nodeName":"发起人","type":"0","settype":"","selectMode":"","selectRange":"","directorLevel":"","examineMode":"","noHanderAction":"","examineEndDirectorLevel":"","nodeUserList":[],"childNode":{"nodeName":"审核人","type":"1","settype":"2","selectMode":"0","selectRange":"0","directorLevel":"1","examineMode":"1","noHanderAction":"2","examineEndDirectorLevel":"0","nodeUserList":[{"type":1,"targetId":"7","name":"任广龙"}],"childNode":{"nodeName":"审核人","type":"1","settype":"1","selectMode":"1","selectRange":"1","directorLevel":"1","examineMode":"1","noHanderAction":"2","examineEndDirectorLevel":"0","nodeUserList":[{"type":1,"targetId":"25","name":"财务测试1"}],"childNode":{"nodeName":"审批人（加签）","type":"1","settype":"1","selectMode":"","selectRange":"","directorLevel":"","examineMode":"","noHanderAction":"","examineEndDirectorLevel":"","nodeUserList":[{"type":1,"targetId":"6","name":"系统管理员"},{"type":1,"targetId":"7","name":"任广龙"},{"type":1,"targetId":"25","name":"财务测试1"}],"childNode":{"nodeName":"抄送人","type":"2","settype":"1","selectMode":"","selectRange":"","directorLevel":"","examineMode":"","noHanderAction":"","examineEndDirectorLevel":"","nodeUserList":[{"type":1,"targetId":"6","name":"系统管理员"},{"type":1,"targetId":"7","name":"任广龙"}],"childNode":{"nodeName":"审核人","type":"1","settype":"3","selectMode":"1","selectRange":"1","directorLevel":"1","examineMode":"1","noHanderAction":"2","examineEndDirectorLevel":"0","nodeUserList":[{"type":2,"targetId":"6ae101ab-532b-4331-ab29-a2a801b00d9e","name":"财务"}],"childNode":{"nodeName":"抄送人","type":"2","settype":"1","selectMode":"","selectRange":"","directorLevel":"","examineMode":"","noHanderAction":"","examineEndDirectorLevel":"","nodeUserList":[{"type":1,"targetId":"6","name":"系统管理员"},{"type":1,"targetId":"7","name":"任广龙"}]}}}}}}},"nodeStyle":"pass"}
      action[this.isView](aaaa);
      return; */

      this.$axios[requestType](this.workflowData, rdata, {
        emulateJSON: true,
      })
        .then((res) => {
          if (res == null) {
            parent.layer &&
              parent.layer["msg"]("数据获取失败，请联系管理员处理");
            return;
          }
          //* 走不同的逻辑
          //* 编辑、查看时
          if (JSON.stringify(this.dataList) != "{}") {
            action[this.isView](this.dataList)
          } else {
            action[this.isView](res);
          }
        })
        .catch((error) => {
          parent.layer && parent.layer["msg"](error.Message);
        });
    },

    //************************************************************************ E 不同业务动作分开请求处理
    //* 审批流处理
    reErr({ childNode }) {
      if (childNode) {
        let { type, error, nodeName, conditionNodes } = childNode;
        if (type == 1 || type == 2) {
          if (error) {
            this.tipList.push({
              name: nodeName,
              type: ["", "审核人", "抄送人"][type],
            });
          }
          this.reErr(childNode);
        } else if (type == 3) {
          this.reErr(childNode);
        } else if (type == 4) {
          this.reErr(childNode);
          for (var i = 0; i < conditionNodes.length; i++) {
            if (conditionNodes[i].error) {
              this.tipList.push({
                name: conditionNodes[i].nodeName,
                type: "条件",
              });
            }
            this.reErr(conditionNodes[i]);
          }
        }
      } else {
        childNode = null;
      }
    },
    async saveSet() {
      /* this.requestObj.wfJSON = {
        wfJSON: '',
        wfName: '',
        wfCode: "001"
      }; */
      this.isTried = true;
      this.tipList = [];
      //* 校验当前审批流名称
      if (this.requestObj.wfCode == "") {
        this.$message.error("请输入审批流编码");
        this.$refs["workFlowCode"].focus();
        return;
      }
      //* 校验当前审批流名称
      if (this.workFlowDef.name == "") {
        this.$message.error("请输入审批流名称");
        this.$refs["workFlowName"].focus();
        return;
      }

      this.requestObj.wfName = this.workFlowDef.name;

      this.reErr(this.nodeConfig);
      if (this.tipList.length != 0) {
        this.tipVisible = true;
        return;
      }

      this.processConfig.flowPermission = this.flowPermission;
      // eslint-disable-next-line no-console
      // console.log(JSON.stringify(this.processConfig));
      // eslint-disable-next-line no-console
      this.requestObj.wfJSON = JSON.stringify(this.processConfig);

      if (JSON.stringify(this.dataList) != "{}") {
        this.requestObj.id  = this.id
      }

      // if (this.id != null && this.id != "") {
      //   this.requestObj.id = this.id;
      // }
      //  requestObj = this.queryConversion(requestObj);
      const res = await SaveBill({
        dataMain: {
          ...this.requestObj,
        },
      });
      if (res.success == "true") {
        this.$message({ message: "保存成功", type: "success" });
        this.$emit('close')
      } else {
        this.$message.error("保存失败");
      }
      // this.$axios.post(`/Workflow/SaveData`, this.requestObj, {
      //   emulateJSON: true //这行最关键。题外话：我们是选项体，也就是文档里的[options]
      // }).then(res => {
      //   // eslint-disable-next-line no-
      //   if (res.Result) {
      //     //   this.$message.success("保存成功");
      //     this.layerMsg('保存成功');
      //     setTimeout(function () {
      //       let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
      //       parent.layer && parent.layer.close(index); //再执行关闭
      //     }, 200)
      //   } else {
      //     this.layerMsg(`保存失败，${res.Message}`);
      //     return;
      //   }
      // }).catch((error) => {
      //   this.layerMsg(`保存失败，${error.Message}`);
      // });
    },
    //* layui 消息提醒
    layerMsg(msg = "") {
      parent.layer && parent.layer["msg"](msg);
    },
    //* 页面尺寸修改
    zoomSize(type) {
      if (type == 1) {
        if (this.nowVal == 50) {
          return;
        }
        this.nowVal -= 10;
      } else {
        if (this.nowVal == 300) {
          return;
        }
        this.nowVal += 10;
      }
    },
    /**
     * 将对象转换成 query 格式(临时)
     * @param {object} params 对象
     */
    queryConversion(params) {
      if (params == null || typeof params != "object") {
        // eslint-disable-next-line no-console
        console.error("🚀 ~ file: , line: , 传入对象错误");
        return;
      }
      let str = "";

      for (let i in params) {
        let val = params[i] !== undefined ? params[i] : "";
        str += "&" + i + "=" + encodeURIComponent(val);
      }

      str = str ? "?" + str.substring(1) : "";
      return str;
    },
    /**
     * 获取 url query 传参
     * @param {string} [paramName=''] 参数名
     * @param {string} [url=''] 地址, 选填 默认当前窗口地址
     * @returns
     */
    getUrlQuery: function (paramName = "", url) {
      if (paramName == null) {
        // eslint-disable-next-line no-console
        console.error("paramName is null");
        // eslint-disable-next-line no-console
        console.error("请输入想要获取的参数名");
        return null;
      }
      var pageUrl = url || window.location.href;
      if (pageUrl.indexOf("?") == -1) {
        // 没有参数的情况
        return null;
      } else {
        pageUrl = pageUrl.split("?")[1];
        if (pageUrl.indexOf("&") == -1) {
          /*一个参数的情况*/
          /*判断是一个参数还是1+个参数*/
          if (paramName != pageUrl.split("=")[0]) {
            /*参数名是否是传入的参数名相同*/
            // console.error("参数名不相同！");
            return null;
          } else {
            return pageUrl.split("=")[1];
          }
        } else {
          /*多个参数的情况*/
          let paramArray = pageUrl.split("&");
          if (paramArray == null) {
            // eslint-disable-next-line no-console
            console.error("paramArray is null");
            return;
          }
          for (let i = 0; i < paramArray.length; i++) {
            let param = paramArray[i].split("=")[0];
            let value = paramArray[i].split("=")[1];
            if (param == null || value == null) {
              // eslint-disable-next-line no-console
              console.error("(param||value) is null");
              return;
            }
            if (param == paramName) {
              return value;
            }
          }
        }
        return null;
      }
    },

    /**
     * * 查看时处理节点颜色数据
     *
     * @param {object} nodeTree 节点数据
     * @param {object} nowNodeType 当前节点标识 { xxx: xxx }
     *
     */
    formatNodeConfig(nodeTree, nowNodeStep) {
      let node = JSON.parse(JSON.stringify(nodeTree));
      if (nodeTree == null) {
        this.$message.error("节点数据错误");
        return;
      }

      /**
       * nodeState
       * pass: 节点已通过
       * nopass: 节点终止
       * without: 节点未经过
       * this: 当前节点
       */
      let nodeState = "pass"; //* 节点状态, 默认是已通过, 如果第一个节点为当前节点, 那么该状态会被更改为 without
      let nodeStep = 1; //* 节点步骤
      const getStr = function (nodes) {
        if (nowNodeStep == nodeStep) {
          nodes["nodeStyle"] = "this"; //* 当前节点
          nodeState = "without"; //* 将剩下的节点状态控制
        } else if (nowNodeStep != nodeStep) {
          nodes["nodeStyle"] = nodeState; //* 节点已经过
        }
        nodeStep += 1;
        if (nodes.childNode) {
          getStr(nodes.childNode);
        } else {
          //* TODO
        }
      };
      getStr(node);
      // nowNodeType
      return node;
    },
  },
};
</script>

<style scoped>
/* @import "../../../css/workflow.css"; */
.workflow-content {
  position: relative;
  width: 100%;
  height: 75vh;
  overflow: hidden;
}

.error-modal-list {
  width: 455px;
}

.el-input input {
  padding: 0;
  font-size: 16px;
}

.box-scale-no-padding {
  padding-top: 0 !important;
  top: 10px;
}
</style>
