<template>
  <div class="design_contain">
    <el-breadcrumb separator="/" class="bread_crumb1">
      <el-breadcrumb-item :to="{ path: '/workplace' }">{{
        $t("lang.online_component_tool")
      }}</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/progress/designer' }">{{
        $t("lang.process_design")
      }}</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/progress/designer' }">{{
        $t("lang.process_management")
      }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t("lang.edit") }}</el-breadcrumb-item>
    </el-breadcrumb>
    <BlockRadius class="block_item">
      <steps :active-step="step" :show-done="true" class="apaas_steps">
        <step
          title="基本信息"
          :step="0"
          :active-icon="require('@/assets/imgs/progress_ic_xinxitx.png')"
          class="apaas_step"
        >
          <div class="step_in" ref="stepInProcess">
            <el-form
              :model="basic_form"
              :rules="rules"
              ref="basicInformation"
              class="form_left"
            >
              <el-form-item prop="name">
                <p class="formname">流程名称：</p>
                <el-input
                  v-model="basic_form.name"
                  placeholder="请输入流程名称"
                ></el-input>
              </el-form-item>
              <el-form-item prop="workplace">
                <p class="formname">工作区域：</p>
                <el-select
                  v-model="basic_form.workplace"
                  @change="changeWorkPlace"
                  placeholder="请选择工作区域"
                >
                  <el-option
                    v-for="(item, index) in workplace_list"
                    :label="item.name"
                    :value="item.id"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="desc">
                <p class="formname">流程描述：</p>
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 6, maxRows: 10 }"
                  v-model="basic_form.desc"
                  placeholder="请输入流程描述"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="btn_footer">
              <el-button class="cancel" @click="cancel">取消</el-button>
              <el-button class="next" @click="next">下一步</el-button>
            </div>
          </div>
        </step>
        <step
          title="流程设计"
          :step="1"
          :active-icon="require('@/assets/imgs/progress_ic_liucheng.png')"
          class="apaas_step"
        >
          <div class="step_in">
            <WorkFlow
              ref="workFlow"
              :node_list="node_list"
              :link_list="link_list"
              :node_params_list="node_params_list"
              :origin="origin"
              class="work_flow"
            />
            <div class="btn_footer">
              <el-button class="cancel" @click="cancel">取消</el-button>
              <div>
                <el-button class="cancel" @click="back">上一步</el-button>
                <el-button class="next" @click="complete">完成</el-button>
              </div>
            </div>
          </div>
        </step>
        <step
          title
          step-title="完成"
          :step="2"
          :active-icon="require('@/assets/imgs/progress_ic_wancheng.png')"
          class="apaas_step"
        >
          <div class="steps_container steps_done">
            <div class="steps_done_info">
              <div class="left_container">
                <img
                  :src="require('@/assets/imgs/steps_done.png')"
                  width="100%"
                />
              </div>
              <div class="right_container">
                <p>保存成功</p>
                <p>可返回流程管理列表查看该流程，并进行流程的部署和发布。</p>
              </div>
            </div>
            <div class="done_action apaas_button">
              <slot name="action"></slot>
            </div>
            <div class="btn_footer_1">
              <div>
                <el-button class="next" @click="backToList">返回列表</el-button>
              </div>
            </div>
          </div>
        </step>
      </steps>
    </BlockRadius>
  </div>
</template>

<script>
import WorkFlow from "@/components/work-flow/super-flow";
import BlockRadius from "@/components/general/block-radius";
import Steps from "@/components/app-build-steps/app-build-steps";
import Step from "@/components/app-build-steps/app-build-step";

export default {
  components: {
    WorkFlow,
    BlockRadius,
    Steps,
    Step,
  },
  data: () => {
    return {
      step: 0,
      done: false,
      basic_form: {
        name: "",
        workplace: "",
        desc: "",
      },
      node_list: [],
      link_list: [],
      node_params_list: [],
      rules: {
        name: [
          { required: true, message: "请输入流程名称", trigger: "blur" },
          { max: 100, message: "不能超过100个字符", trigger: "blur" },
        ],
        workplace: [
          { required: true, message: "请选择工作区域", trigger: "blur" },
        ],
        desc: [
          { required: true, message: "请输入流程描述", trigger: "blur" },
          { max: 400, message: "不能超过400个字符", trigger: "blur" },
        ],
      },
      workplace_list: [],
      origin: [],
      params: {
        workflows_id: "",
        sector: 0,
      },
      loop: 0,
    };
  },
  methods: {
    verification() {
      let self = this;
      let data = { ...self.$refs.workFlow.getData() };
      let start_num = 0;
      let end_num = 0;
      let start_id = "";
      let end_id = "";
      let start_before = 0;
      let end_after = 0;
      let in_edge = 0;
      let out_edge = 0;
      let judge_nodes = [];
      let in_judge_edges = 0;
      let datas = { ...data.obj };
      datas.nodeList.forEach((item) => {
        let da = data.params.find((nodep) => {
          return nodep.id == item.meta.id;
        });
        item.meta = da;
        item.node_code = da.node_code;
        if (item.meta.type == 1) {
          start_num++;
          start_id = item.id;
        }
        if (item.meta.type == 2) {
          end_num++;
          end_id = item.id;
        }
        if (item.meta.type == 4) {
          judge_nodes.push(item.id);
        }
        if (
          datas.linkList.findIndex((el) => {
            return el.startId == item.id;
          }) == -1 &&
          item.id != end_id
        ) {
          in_edge++;
        } else if (
          datas.linkList.findIndex((el) => {
            return el.endId == item.id;
          }) == -1 &&
          item.id != start_id
        ) {
          out_edge++;
        }
      });
      this.loop = 0;
      datas.nodeList.forEach((item) => {
        this.checkClosedLoop(datas.linkList, item.id, item.id, end_id);
      });
      datas.linkList.forEach((item) => {
        if (start_id == item.endId) {
          start_before++;
        }
        if (end_id == item.startId) {
          end_after++;
        }
        if (judge_nodes.indexOf(item.endId) != -1) {
          in_judge_edges++;
        }
      });
      if (start_num != 1 || end_num != 1) {
        this.$message({
          message: "开始节点与结束节点均应有且只有一个",
          type: "warning",
        });
        return false;
      } else if (start_before != 0) {
        this.$message({
          message: "开始节点前面不应连接其它节点",
          type: "warning",
        });
        return false;
      } else if (end_after != 0) {
        this.$message({
          message: "结束节点后面不应连接其它节点",
          type: "warning",
        });
        return false;
      } else if (in_edge != 0 || out_edge != 0) {
        this.$message({
          message: "请保证每个节点都被连接",
          type: "warning",
        });
        return false;
      } else if (this.loop != 0) {
        this.$message({
          message: "不能连接本节点之前的节点",
          type: "warning",
        });
      } else if (judge_nodes.length != in_judge_edges) {
        this.$message({
          message: "条件节点应当有且只有一条入边",
          type: "warning",
        });
      } else {
        return datas;
      }
    },
    checkClosedLoop(arr, now_id, id, endding_id) {
      let self = this;
      if (self.loop == 0) {
        arr.forEach((item) => {
          if (item.startId == now_id) {
            if (item.endId == endding_id) {
              return false;
            } else if (item.endId == id) {
              console.log("has loop");
              self.loop++;
            } else {
              this.checkClosedLoop(arr, item.endId, id, endding_id);
            }
          } else {
            return false;
          }
        });
      } else {
        return false;
      }
    },
    backToList() {
      this.$router.push("/progress/designer");
    },
    changeWorkPlace() {},
    cancel() {
      this.$router.go(-1);
    },
    next() {
      this.$refs["basicInformation"].validate((valid) => {
        if (valid) {
          this.step++;
        } else {
        }
      });
    },
    back() {
      this.step--;
    },
    complete() {
      let self = this;
      let res = self.verification();
      if (res) {
        let query = {
          workflows_id: self.params.workflows_id,
          sector: self.params.sector,
          name: self.basic_form.name,
          workarea: self.basic_form.workplace,
          describe: self.basic_form.desc,
          ...res,
        };
        this.$api.workbench.editProcess(query).then((response) => {
          if (response.data.success == 1) {
            this.step = 2;
          } else {
            this.$message.error(response.data.errMsg);
          }
        });
      }
    },
    getNameSpaceList() {
      this.$api.workbench.getProcessNamespaceList().then((response) => {
        if (response.data.success == 1) {
          this.workplace_list = response.data.data.workareas;
        }
      });
    },
    getProcessDetail() {
      this.$api.workbench
        .getProcessDetail({ id: this.$route.params.id })
        .then((response) => {
          if (response.data.success == 1) {
            let data = response.data.data;
            this.basic_form.name = data.name;
            this.basic_form.workplace = data.workarea;
            this.basic_form.desc = data.describe;
            this.node_list = data.nodeList;
            this.link_list = data.linkList;
            this.node_params_list = [];
            this.params.workflows_id = data.workflows_id;
            this.params.sector = data.sector;
            this.node_list.forEach((item) => {
              item.meta.id =
                parseInt(Math.random() * 1000 * 1000) +
                "a" +
                parseInt(Math.random() * 1000 * 1000);
              item.meta.node_code = item.node_code;
              this.node_params_list.push(item.meta);
            });
          }
        });
    },
    setOrigin() {
      let width = this.$refs.stepInProcess.clientWidth;
      let href_width = width / 2 - 20;
      this.origin = [href_width, 0];
    },
  },
  mounted() {
    this.getNameSpaceList();
    this.getProcessDetail();
    this.setOrigin();
  },
};
</script>

<style scoped>
.design_contain {
  width: 100%;
  height: calc(100% - 20px);
  padding: 0 20px;
}
.block_item {
  height: calc(100% - 56px);
}
.step_in {
  height: 100%;
}
.form_left {
  width: 55%;
  height: calc(100% - 70px);
}
.btn_footer {
  width: calc(100% - 20px);
  height: 40px;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
}
.cancel {
  background-color: #e3e5ef;
  color: #0f2683;
}
.next {
  background-color: #0f2683;
  color: #f8f9fd;
}
.work_flow {
  height: calc(100% - 70px);
}
.steps_container {
  flex-grow: 1;
}
.steps_done {
  position: relative;
  height: 100%;
}
.steps_done_info {
  position: absolute;
  top: calc(50% - 40px);
  left: 50%;
  transform: translate(-50%, -50%);
}
.steps_done_info > * {
  display: inline-block;
  vertical-align: middle;
}
.steps_done_info > .left_container {
  width: 70px;
  font-size: 0;
  margin-right: 10px;
}
.steps_done_info > .right_container > p:nth-child(1) {
  font-size: 18px;
  font-weight: 700;
  line-height: 24px;
  color: #242c43;
}
.steps_done_info > .right_container > p:nth-child(2) {
  font-size: 14px;
  line-height: 20px;
  color: #8890a7;
  margin-top: 5px;
}
.btn_footer_1 {
  position: absolute;
  bottom: 0;
  padding: 15px;
  width: 100%;
  text-align: right;
}
</style>
<style>
.block_item .el-textarea__inner {
  border-radius: 8px;
  background-color: #f7f8f9;
  border: solid 1px #e3e5ef;
}
.block_item .el-input__inner {
  background-color: #f7f8f9;
  border: solid 1px #e3e5ef;
}
.block_item .el-select {
  width: 100%;
}
</style>
