<script setup name="configEdit">
import { ref, reactive, nextTick, provide, onMounted, getCurrentInstance } from 'vue'
import ChildFlow from './components/childFlow.vue'
import playCircle from '@/assets/images/flowConfig/playCircle.png'
import ApprovalDialog from './components/approvalDialog.vue'
import { procDefRelease, procdefSave } from '@/http/apis/systemManage/flowConfiguration'
import { useRouter, useRoute } from 'vue-router'
import { procdefDetail } from '@/http/apis/unitSet/flowPathConfiguration'
const { proxy } = getCurrentInstance(),
  router = useRouter(),
  route = useRoute(),
  // 添加节点
  addNode = ({ key, type, item }) => {
    let node = {}
    const name =
        type === 'APPROVAL'
          ? '审批'
          : type === 'CONSTRCTION' ? '建设申报审批' : type === 'CC' ? '抄送' : type === 'SEAL' ? '盖章' : ''
    node = {
      name,
      type,
      props: undefined,
      id: ''
    }
    if (key === -1) { // key:-1,开始节点下面
      nodeData.value.splice(0, 0, node)
    } else {
      item.splice(key + 1, 0, node)
    }
  },
  // 删除节点
  removeNode = async (con_index, item, index, nodeData) => {
    item.splice(con_index, 1)
  //   if (item.branchs) {
  //     if (item.branchs.length === 2) {
  //       nodeData.splice(index, 2)
  //     } else {
  //       item.branchs.splice(con_index, 1)
  //     }
  //   } else {
  //     if (item.children === undefined) {
  //       item.splice(con_index, 1)
  //     } else {
  //       item.children.splice(0, 1)
  //     }
  //   }
  },
  // 操作弹窗-审批节点配置
  approvalDialogData = reactive({
    visible: false,
    data: {
      name: undefined
    }
  }),
  showApprovalDialog = ({ key, item }) => {
    approvalDialogData.visible = true
    approvalDialogData.data = item[key]
    approvalDialogData.orgCode = route.query.orgCode || ''
  },
  closeApproval = flag => {
    approvalDialogData.visible = false
  },
  updateApprovalData = (data) => {
    nextTick(() => {
      Object.entries(data).forEach(i => {
        approvalDialogData.data[i[0]] = i[1]
      })
    })
  },
  // 获取数据
  processDefId = ref(),
  processDefName = ref(),
  nodeData = ref([]),
  detailData = ref({}),
  getNodeData = async () => {
    const res = await procdefDetail({ processDefId: route.query.processDefId })
    processDefId.value = res.data.processDefId
    processDefName.value = res.data.processDefName
    detailData.value = res.data
    const process = { children: JSON.parse(res.data.process) }
    nodeData.value = getChildNode([], process, true)
  },
  getChildNode = (arr, item, isNodeId) => {
    if (item.branchs) {
      const branchs = []
      item.branchs.forEach(val => {
        let obj = {}
        obj = {
          name: val.name,
          // displayText: val.displayText,
          type: val.type,
          props: val.props,
          id: isNodeId ? val.id : undefined
        }
        if (val.children && JSON.stringify(val.children) !== '{}') {
          const childArr = []
          if (!val.children.branchs) {
            childArr.push({
              name: val.children.name,
              // displayText: val.children.displayText,
              type: val.children.type,
              props: val.children.props,
              id: isNodeId ? val.children.id : undefined
            })
          }
          getChildNode(childArr, val.children, isNodeId)
          obj.children = childArr
        } else {
          obj.children = []
        }
        branchs.push(obj)
      })
      arr.push({
        type: 'CONDITIONS',
        'props': {},
        branchs
      })
    }
    if (item.children && JSON.stringify(item.children) !== '{}') {
      if (!item.children.branchs) {
        arr.push({
          name: item.children.name,
          // displayText: item.children.displayText,
          type: item.children.type,
          props: item.children.props,
          id: isNodeId ? item.children.id : undefined
        })
      }
      getChildNode(arr, item.children, isNodeId)
    }
    return arr
  },

  // 获取随机id
  uuid = () => {
    const s = []
    const hexDigits = '0123456789abcdef'
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4'
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
    s[8] = s[13] = s[18] = s[23] = '-'

    const uuid = s.join('')
    return uuid
  },
  // 转换数据结构
  formatter = (nodes, preNode) => {
    nodes = nodes.reverse()

    return nodes.reduce((res, cur, index) => {
      const id = cur.id || uuid()

      if (preNode && index === nodes.length - 1) {
        cur.parent = preNode.id
      }

      if (cur.branchs) {
        cur.branchs.forEach(i => {
          i.parentId = id || null
          i.id = i.id || uuid()
          if (i.children && i.children.length) {
            i.children = formatter(i.children, i)
          } else if (i.children && !i.children.length) {
            delete i.children
          }
        })

        if (!index) {
          cur.id = id
          return cur
        }

        res.parentId = id || null

        return {
          type: 'route',
          // conditionType: 'ONE_BY_ONE',
          id,
          // branchs: cur.branchs,
          children: res
        }
      } else {
        if (!index) {
          cur.id = id
          return cur
        }
        res.parentId = id || null

        cur.id = id
        cur.children = res
        return cur
      }
    }, null)
  },
  submit = async () => {
    let resource = {}
    const nodes = JSON.parse(JSON.stringify(nodeData.value))
    // nodes.splice(0, 0, {
    //   name: '发起人',
    //   type: 'start',
    //   id: uuid()
    // })
    resource = resource.children = JSON.parse(
      JSON.stringify(formatter(nodes))
    )
    const postData = {
      ...detailData.value,
      process: resource
    }
    delete postData.created
    delete postData.sort
    delete postData.updated
    delete postData.version
    await procdefSave(postData)
    await procDefRelease(postData)
    proxy.$message.success('发布成功')
  }
onMounted(() => {
  getNodeData()
  processDefId.value = route.query.processDefId
})
// 可以使得孙子组件也能调用父组件的这个方法，适用多层组件嵌套的时候
provide('showApprovalDialog', showApprovalDialog)
provide('addNode', addNode)
provide('removeNode', removeNode)
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between items-center">
        <span>{{ processDefName }}</span>
        <div>
          <el-button @click="router.go(-1)">返回</el-button>
          <el-button
            type="primary"
            @click="submit"
          >发布</el-button>
        </div>
      </div>
    </template>
    <div class="overflow-x-auto flex">
      <div class="node flex flex-1 flex-col items-center justify-center">
        <div class="start_box node_box text-white flex items-center justify-center">
          开始
          <img :src="playCircle" />
        </div>
        <el-popover
          placement="right"
          :width="100"
          trigger="hover"
        >
          <template #reference>
            <el-icon class="add_icon mt-20 mb-20 cursor-pointer">
              <Plus />
            </el-icon>
          </template>
          <div class="flex flex-col">
            <p>
              <el-button
                class="mb-8 w-full"
                @click="addNode({ key: -1, type: 'APPROVAL' })"
              >
                审批人
              </el-button>
            </p>
            <p>
              <el-button
                class="ml-1 mb-8 w-full"
                @click="addNode({ key: -1, type: 'SEAL' })"
              >
                盖章人
              </el-button>
            </p>
            <p>
              <el-button
                class="ml-1 mb-8 w-full"
                @click="addNode({ key: -1, type: 'CC' })"
              >
                抄送人
              </el-button>
            </p>
            <p>
              <el-button
                class="mb-8 w-full"
                @click="addNode({ key: -1, type: 'CONSTRCTION' })"
              >
                建设审批人
              </el-button>
            </p>
          </div>
        </el-popover>
        <child-flow :node-data="nodeData" />
        <div class="end_box node_box text-white flex items-center justify-center">
          流程结束
        </div>
      </div>
    </div>
  </el-card>
  <approval-dialog
    :visible="approvalDialogData.visible"
    :data="approvalDialogData.data"
    :org-code="approvalDialogData.orgCode"
    @close="closeApproval"
    @update:data="updateApprovalData"
  />
</template>

<style lang="less" scoped>
.node{
  .add_icon{
    width: 24px;
    height: 24px;
    background: #ffffff;
    box-shadow: 0px 4px 8px 0px rgb(9 103 253 / 8%), 0px 6px 13px 0px rgb(9 103 253 / 8%);
    border: 1px solid rgba(9, 103, 253, 0.06);
    border-radius: 100%;
    color: #0967fd;
    z-index:2;
    &:after{
      width: 4px;
      height: 20px;
      background: #dcdee2;
      content: '';
      display: block;
      position: absolute;
      left: 50%;
      transform: translate(-50%, 100%);
      bottom: 0;
    }
    &:before{
      width: 4px;
      height: 20px;
      background: #dcdee2;
      content: '';
      display: block;
      position: absolute;
      left: 50%;
      transform: translate(-50%, 0);
      top: -20px;
    }
  }
  .node_box{
    position: relative;
    width: 160px;
    height: 56px;
    border-radius: 4px;
    font-size: 20px;
    &:not(.end_box):after{
      //width: 4px;
      //height: 20px;
      //background: #dcdee2;
      //content: '';
      //display: block;
      //position: absolute;
      //left: 50%;
      //transform: translate(-50%, 100%);
      //bottom: 0;
    }
    &.start_box{
      background: linear-gradient(270deg, #15a1ff 0%, #0967fd 100%);
      box-shadow: 0px 10px 12px -5px rgba(9, 103, 253, 0.2),
      0px 6px 12px 0px rgba(9, 103, 253, 0.2);
      img{
        width: 24px;
        height: 24px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        right: 16px;
      }
    }
    &.end_box{
      background: linear-gradient(270deg, #54dc7d 0%, #29c458 100%);
      box-shadow: 0px 10px 12px -5px rgba(78, 203, 116, 0.2),
      0px 6px 12px 0px rgba(78, 203, 116, 0.2);
    }
  }
}
</style>

