<template>
  <div :class="$style.wrap">
    <a-spin v-if="spinning" :spinning="spinning" :class="$style.spin" />
    <div :class="$style.tree">
      <a-tree
        v-if="treeData.length > 0"
        :key="updateKey"
        :block-node="true"
        :tree-data="treeData"
        :default-expanded-keys="defaultExpandedKeys"
        :load-data="onLoadTreeData"
      >
        <template slot="root" slot-scope="record">
          {{ record.title }}
          <a-button @click="hieraFlowaction('root')">下放流程 </a-button>
        </template>
        <template slot="title" slot-scope="record">
          <div
            :data-vars="(actionInfo = getActionInfo(record))"
            @mouseenter.prevent="onMouseover(record)"
            @mouseleave.prevent="onMouseout(record)"
          >
            <span>{{ actionInfo.nodeName }}</span>
            <span>
              <a-button
                v-show="actionInfo.actName !== '' && record.showAction"
                size="small"
                @click="hieraFlowaction(record)"
              >
                {{ actionInfo.actName }}
              </a-button>
            </span>
          </div>
        </template>
      </a-tree>
    </div>
    <div :class="$style.list">
      <sd-table
        :columns="columns"
        sortable
        :data-source.sync="allHieraFlows"
        row-key="nodeId"
        :pagination="false"
      >
        <template slot="dispType" slot-scope="text, record">
          {{ record.nodeType === 'flowCat' ? '流程分类' : '流程' }}
        </template>
      </sd-table>
    </div>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import OrgService from './org-service'
import components from './_import-components/sd-org-hiera-flow-import'

export default {
  name: 'SdOrgHieraFlow',
  metaInfo: {
    title: 'SdOrgHieraFlow',
  },
  components,
  props: {
    unid: {
      type: String,
      default: function() {
        return null
      },
    },
  },
  data() {
    return {
      treeData: [],
      defaultExpandedKeys: [],
      columns: [
        {
          title: '节点名称',
          dataIndex: 'nodeName',
        },
        {
          title: '类型',
          dataIndex: 'code',
          scopedSlots: {
            customRender: 'dispType',
          },
        },
      ],
      allHieraFlows: [],
      updateKey: 0,
      spinning: true,
    }
  },

  methods: {
    onMouseover(record) {
      // console.log(record)
      if (
        record.key.indexOf('sysCreateFlow') > -1 ||
        record.key === 'CX' ||
        record.key === 'C__SYS_VIRTUAL_COMMON_DIR'
      ) {
        return
      }

      record.showAction = true
      record.dataRef.showAction = true
    },
    onMouseout(record) {
      record.showAction = false
      record.dataRef.showAction = false
    },
    getActionInfo(record) {
      const actionInfo = this.getActionInfos(record)
      actionInfo.name = actionInfo.actName
      return actionInfo
    },
    getActionInfos(record) {
      // console.log(record)
      const actionInfo = {}
      if (
        record.key.indexOf('sysCreateFlow') > -1 ||
        record.key === 'CX' ||
        record.key === 'C__SYS_VIRTUAL_COMMON_DIR'
      ) {
        return {
          nodeName: record.title,
          actName: '',
        }
      }

      const permType = record.backendAttr.props.permType
      const subPermType = record.backendAttr.props.subPermType

      if (permType === 'VIEW') {
        actionInfo.nodeName = record.title + '(已下放)'
      } else if (permType === 'REJECT') {
        actionInfo.nodeName = record.title + '(已排除)'
      } else {
        actionInfo.nodeName = record.title
      }

      if (['VIEW', 'REJECT'].includes(permType)) {
        actionInfo.actName = '取消'
        actionInfo.actPermType = 'CANCEL'
      } else if (subPermType === 'SUB_VIEW') {
        actionInfo.actName = ''
      } else {
        const parentPermType = this.getParentPermType(record)

        if (parentPermType === 'VIEW') {
          actionInfo.actName = '排除'
          actionInfo.actPermType = 'REJECT'
        } else if (parentPermType === 'REJECT') {
          actionInfo.actName = ''
        } else if (
          parentPermType === null ||
          parentPermType === undefined ||
          parentPermType === ''
        ) {
          actionInfo.actName = '下放'
          actionInfo.actPermType = 'VIEW'
        }
      }

      if (['VIEW', 'REJECT'].includes(actionInfo.actPermType)) {
        actionInfo.newPermType = actionInfo.actPermType
      } else {
        actionInfo.newPermType = ''
      }

      return actionInfo
    },
    // 获取父节点属性
    getParentPermType(record) {
      let treeNodeParent = this.treeData[0]
      record.fullpath.forEach((item, index) => {
        if (index !== 0 && index !== record.fullpath.length - 1)
          treeNodeParent = treeNodeParent.children[item]
      })

      if (
        treeNodeParent.key.indexOf('sysCreateFlow') > -1 ||
        treeNodeParent.key === 'CX' ||
        treeNodeParent.key === 'C__SYS_VIRTUAL_COMMON_DIR'
      ) {
        return null
      }

      let permType
      try {
        permType = treeNodeParent.backendAttr.props.permType
      } catch (ex) {}

      if (treeNodeParent && (permType === null || permType === undefined || permType === '')) {
        return this.getParentPermType(treeNodeParent)
      }
      return permType
    },
    hieraFlowaction(record) {
      let actionInfo = {}
      let xhrPost
      if (record === 'root') {
        actionInfo.actName = '下放流程'
        xhrPost = OrgService.saveOrgHieraAllFlow({
          groupId: parseInt(this.unid, 10),
        })
      } else {
        actionInfo = this.getActionInfos(record)
        xhrPost = OrgService.saveOrgHieraFlow({
          groupId: parseInt(this.unid, 10),
          nodeId: record.key,
          permType: actionInfo.actPermType,
        })
      }
      this.spinning = true
      xhrPost
        .then((res) => {
          if (res.status === 200) {
            message.success(actionInfo.actName + '成功')
            if (record === 'root') {
              this.init()
              return
            }
            if (actionInfo.newPermType === '') {
              delete record.backendAttr.props.permType
              delete record.dataRef.backendAttr.props.permType
            } else {
              record.backendAttr.props.permType = actionInfo.newPermType
              record.dataRef.backendAttr.props.permType = actionInfo.newPermType
            }

            if (actionInfo.actPermType === 'CANCEL') {
              record.backendAttr.props.permType = ''
              record.dataRef.backendAttr.props.permType = ''
              record.backendAttr.props.subPermType = ''
              record.dataRef.backendAttr.props.subPermType = ''
            }
            this.setParentAttr(record)
            if (actionInfo.actPermType === 'CANCEL') {
              this.setChildAttr(record)
            }
            this.getOrgHieraFlowList()
          } else {
            message.error(res.data?.message || actionInfo.actName + '失败')
          }
        })
        .catch(() => message.error(actionInfo.actName + '失败'))
        .finally(() => {
          this.spinning = false
        })
    },
    setChildAttr(record) {
      if (record.children) {
        record.children.forEach((item) => {
          const permType = item.backendAttr.props.permType
          if (permType === 'REJECT') {
            item.backendAttr.props.permType = ''
          }
          this.setChildAttr(item)
        })
      }
    },
    setParentAttr(record) {
      // 当子节点没有view时，级联更新上层阶段的subPermType属性
      let treeNodeParent = this.treeData[0]
      record.fullpath.forEach((item, index) => {
        if (index !== 0 && index !== record.fullpath.length - 1)
          treeNodeParent = treeNodeParent.children[item]
      })
      if (treeNodeParent) {
        if (
          treeNodeParent.key.indexOf('sysCreateFlow') > -1 ||
          treeNodeParent.key === 'CX' ||
          treeNodeParent.key === 'C__SYS_VIRTUAL_COMMON_DIR'
        ) {
          return
        }

        treeNodeParent.backendAttr.props.subPermType = ''
        treeNodeParent.children.some((item) => {
          if (item.backendAttr.props.permType === 'VIEW') {
            treeNodeParent.backendAttr.props.subPermType = 'SUB_VIEW'
            return true
          }
          return false
        })
        if (treeNodeParent?.backendAttr?.props?.subPermType === '') {
          delete treeNodeParent.backendAttr.props.subPermType
        }
        this.setParentAttr(treeNodeParent)
      }
    },
    init() {
      Promise.all([this.getOrgHieraFlowList(), this.onLoadTreeData()]).then(() => {
        this.updateKey++
        this.spinning = false
      })
    },

    getOrgHieraFlowList() {
      return new Promise((resolve) => {
        OrgService.getOrgHieraFlowList({ id: this.unid }).then((res) => {
          this.allHieraFlows = res.data
          resolve()
        })
      })
    },
    onLoadTreeData(treeNode) {
      return new Promise((resolve) => {
        if (treeNode) {
          if (treeNode.dataRef.children) {
            resolve()
            return
          }
          OrgService.getOrgHieraFlowTree({
            groupId: parseInt(this.unid, 10),
            hieraRootId: treeNode.dataRef.backendAttr
              ? treeNode.dataRef.backendAttr.props.hieraRootId
              : '',
            id: treeNode.dataRef.key,
          }).then((deps) => {
            treeNode.dataRef.children = this.parseTreeData(deps.data, treeNode.dataRef.fullpath)
            this.treeData = [...this.treeData]
            this.spinning = false
            resolve()
          })
        } else {
          OrgService.getOrgHieraFlowTree({
            groupId: parseInt(this.unid, 10),
            id: 'CX',
            hieraRootId: '',
          }).then((deps) => {
            this.treeData = [
              {
                key: 'CX',
                title: '流程管理',
                isLeaf: false,
                backendAttr: {},
                showAction: false,
                scopedSlots: {
                  title: 'root',
                },
                fullpath: [0],
                children: deps.data.map((dep, index) => {
                  return {
                    key: dep.id,
                    title: dep.text,
                    isLeaf: dep.leaf,
                    fullpath: [0, index],
                    backendAttr: { ...dep },
                  }
                }),
              },
            ]

            this.defaultExpandedKeys = [].concat(
              this.treeData[0].children.map((item) => {
                return item.key
              })
            )
            this.spinning = false
            resolve()
          })
        }
      })
    },
    parseTreeData(deps, fullpath) {
      return deps.map((dep, index) => {
        return {
          key: dep.id,
          title: dep.text,
          isLeaf: dep.leaf,
          backendAttr: {
            ...dep,
          },
          showAction: false,
          fullpath: [...fullpath, index],
          scopedSlots: {
            title: 'title',
          },
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.spin {
  position: absolute;
  width: 100%;
  line-height: 10;
}
.wrap {
  display: flex;

  .tree {
    width: 300px;
    height: 100%;
    max-height: calc(100vh - 360px);
    overflow: scroll;
    :global(.ant-tree) {
      // 防止流程名过长，下放按钮被隐藏
      width: 999px;
    }
    :global(.ant-btn-sm) {
      font-size: $font-size-sm;
    }
  }
  .list {
    width: calc(100% - 300px);
  }
}
</style>
