<template>
  <section class="AiProcess">
    <ai-flow ref="AiFlow" v-model="detail.nowNodeId" :config="detail.workflowConfig" readonly :process.sync="process" height="200px"/>
    <ai-wrapper border :title="currentNodeName" v-if="!!detail.id &&!isFinished">
      <template v-if="currentNode.type=='task'">
        <ai-info-item label="当前审批" :value="currentNode.properties.userName"/>
        <ai-info-item label="操作时间" :value="currentNode.properties.updateTime"/>
        <ai-info-item label="审批意见" isLine>
          <el-input v-if="canAudit" type="textarea" rows="3" v-model="currentNode.properties.remark"/>
          <span v-else v-text="currentNode.properties.remark"/>
        </ai-info-item>
      </template>
      <template v-else-if="currentNode.type=='start'">
        <ai-info-item label="开始时间" :value="currentNode.properties.updateTime" isLine/>
      </template>
      <template v-else-if="currentNode.type=='end'">
        <ai-info-item label="结束时间" :value="currentNode.properties.updateTime" isLine/>
      </template>
    </ai-wrapper>
    <el-row class="processOptions mar-t16" type="flex" justify="center" v-if="canAudit">
      <el-button @click="handleReject" type="danger">拒绝</el-button>
      <el-button @click="handleReturn" v-if="!incomingIsStart">驳回</el-button>
      <el-button type="primary" @click="handlePass">同意</el-button>
    </el-row>
  </section>
</template>

<script>
import AiFlow from "./AiFlow";
import request from "../../meta/js/request";
import AiWrapper from "../basic/AiWrapper";
import AiInfoItem from "../basic/AiInfoItem";
import {mapState, mapActions} from "vuex"

export default {
  name: "AiProcess",
  props: {
    bid: String
  },
  components: {AiInfoItem, AiWrapper, AiFlow},
  data() {
    return {
      instance: request,
      detail: {},
      currentNode: {properties: {}},
      process: null
    }
  },
  computed: {
    ...mapState(['user']),
    currentNodeName: v => v.currentNode?.text?.value || "当前节点",
    canAudit: v => v.user.info.id == v.currentNode?.properties.userId && v.currentNode?.id == v.detail.nowNodeId && !v.isFinished,
    incomingIsStart: v => v.process?.getNodeIncomingNode(v.detail.nowNodeId)?.[0]?.type == "start",
    isFinished: v => v.detail.nowNodeId == "finished"
  },
  methods: {
    ...mapActions(['endFlow']),
    getProcess() {
      const {bid: id} = this.$props
      id ? this.instance.post("/app/appworkflowlog/queryDetailById", null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          const {workflowConfig = null, nowNodeId} = res.data
          this.detail = {...res.data, workflowConfig: JSON.parse(workflowConfig)}
          this.currentNode = this.detail.workflowConfig.nodes.find(e => e.id == nowNodeId) || this.currentNode
        }
      }) : console.error("无法获取bid")
    },
    initEvents() {
      this.process.on("node:click", res => {
        if (res?.data) {
          this.currentNode = res.data
        }
      })
      this.process.on("blank:click", () => {
        this.currentNode = this.process.getNodeModelById(this.detail.nowNodeId)
      })
    },
    handleReject() {
      this.$confirm("是否要拒绝该申请?").then(() => {
        this.currentNode.properties = {
          remark: "拒绝申请", ...this.currentNode.properties,
          status: "reject",
          updateTime: this.$moment().format("YYYY-MM-DD HH:mm:ss")
        }
        this.process.setProperties(this.detail.nowNodeId, {
          ...this.currentNode.properties,
        })
        const form = {...this.detail, workflowConfig: this.process.getGraphData()}
        this.saveProcess(form)
      }).catch(() => 0)
    },
    handleReturn() {
      this.$confirm("是否要驳回该申请返回到前次审批?").then(() => {
        this.currentNode.properties = {
          remark: "驳回申请", ...this.currentNode.properties,
          status: "reject",
          updateTime: this.$moment().format("YYYY-MM-DD HH:mm:ss")
        }
        let {nowNodeId} = this.detail
        this.process.setProperties(nowNodeId, {
          ...this.currentNode.properties,
        })
        const next = this.process.getNodeIncomingNode(nowNodeId)
        const form = {...this.detail, workflowConfig: this.process.getGraphData()}
        nowNodeId = []
        next?.map(e => {
          nowNodeId.push(e.id)
          this.process.setProperties(e.id, {status: 'current'})
        })
        this.saveProcess({...form, nowNodeId: nowNodeId.toString()})
      }).catch(() => 0)
    },
    handlePass() {
      this.$confirm("是否要同意该申请?").then(() => {
        this.currentNode.properties = {
          remark: "同意申请", ...this.currentNode.properties,
          status: "pass",
          updateTime: this.$moment().format("YYYY-MM-DD HH:mm:ss")
        }
        let {nowNodeId} = this.detail
        this.process.setProperties(nowNodeId, {
          ...this.currentNode.properties,
        })
        const next = this.process.getNodeOutgoingNode(nowNodeId)
        const form = {...this.detail, workflowConfig: this.process.getGraphData()}
        if (next?.[0].type == "end") this.endFlow(form).then(res => {
          if (res?.code == 0) {
            this.$message.success("提交成功!")
            this.getProcess()
          }
        })
        else {
          nowNodeId = []
          next?.map(e => {
            nowNodeId.push(e.id)
            this.process.setProperties(e.id, {status: 'current'})
          })
          this.saveProcess({...form, nowNodeId: nowNodeId.toString()})
        }
      }).catch(() => 0)
    },
    saveProcess(form) {
      const {workflowConfig} = form
      this.instance.post("/app/appworkflowlog/addOrUpdate", {...form, workflowConfig: JSON.stringify(workflowConfig)}).then(res => {
        if (res?.code == 0) {
          this.$message.success("提交成功!")
          this.$emit("submit")
        }
      })
    }
  },
  watch: {
    process: {
      immediate: true,
      handler(v) {
        if (!!v) {
          this.initEvents()
        }
      }
    }
  },
  created() {
    this.getProcess()
  }
}
</script>

<style lang="scss" scoped>
.AiProcess {
  .processOptions {
    .el-button {
      min-width: 72px;
    }
  }
}
</style>
