<template>
  <div :class="$style.wrapHeight">
    <a-row :class="$style.rowHeight">
      <a-col :span="5" :class="$style.treeWrap">
        <a-card>
          <a-spin :spinning="spinning" :class="$style.spin" />

          <a-input-search v-if="treeData.length > 0" placeholder="请输入" @change="onChange" />
          <a-empty v-if="empty" />
          <a-tree
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :replace-fields="replaceFields"
            :selected-keys="selectedkey"
            @expand="onExpand"
            @select="onSelect"
          >
            <template slot="title" slot-scope="{ text, props }">
              <span v-if="text.indexOf(searchValue) > -1">
                {{ text.substr(0, text.indexOf(searchValue))
                }}<span :class="$style.searchColor">{{ searchValue }}</span
                >{{ text.substr(text.indexOf(searchValue) + searchValue.length) }}</span
              ><span v-else>{{ text }}</span
              ><a-badge
                v-if="props.flowId !== null && props.flowId !== undefined"
                :class="$style.badge"
                status="error"
              />
            </template>
          </a-tree>
        </a-card>
      </a-col>
      <a-col :class="$style.formHeight" :span="19">
        <a-card :class="$style.form">
          <sd-detail-form
            v-if="showForm"
            ref="docform"
            :record-id="fwId"
            page-id="km/admin/kmApprovalFlow"
            @saved="fwSaved"
          >
            <template v-slot="{ model }">
              <sd-form-item name="name"></sd-form-item>
              <sd-form-item name="categoryName" :input-props="{ defaultValue: categoryName }">
                <a-input v-model="model.categoryName" :disabled="!disabled" />
              </sd-form-item>
              <sd-form-item
                :hidden="true"
                name="categoryId"
                :input-props="{ defaultValue: categoryId }"
              />
              <sd-form-item name="flowField">
                <sd-business-type-picker
                  v-model="model.flowField"
                  parent-code="PROJECT_ZSGL"
                  :single="true"
                />
              </sd-form-item>
              <sd-form-item name="status" />
            </template>
          </sd-detail-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { Message } from 'ant-design-vue'
import KmKnowledageService from '../km-knowledage-service'
import components from './_import-components/km-approval-process-import'
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.id === key)) {
        parentKey = node.id
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}

// 给树的所有对象增加scopedSlots属性
const addSlot = (obj) => {
  for (let i = 0; i < obj.length; i++) {
    Object.assign(obj[i], { scopedSlots: { title: 'title' } })
    if (obj[i].children) {
      addSlot(obj[i].children)
    }
  }
}
export default {
  name: 'KmApprovalProcess',
  metaInfo: {
    title: '审批流程维护',
  },

  components,
  data() {
    return {
      spinning: true,
      empty: false,
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      treeData: [],
      dataList: [],
      fwId: null,
      replaceFields: {
        title: 'text',
        key: 'id',
      },
      selectedkey: [], // 选中的节点
      categoryName: '',
      categoryId: '',
      showForm: false,
      disabled: false,
    }
  },
  created() {
    this.queryKnowledageTree()
  },
  methods: {
    // 获取树数据
    queryKnowledageTree(selectdId) {
      KmKnowledageService.getKnowledgeTree({ pageId: 'KmApprovalFlow' }).then((res) => {
        this.spinning = false
        if (res.data) {
          const newArr = res.data

          addSlot(newArr)
          this.treeData = newArr
          this.generateList(this.treeData)
          // 默认展开
          if (selectdId === null || selectdId === undefined) {
            this.expandedKeys = [res.data[0].id]
            // 没选择节点的时候默认选中根节点
            this.selectedkey = [res.data[0].id]

            if (res.data[0].props.flowId) {
              this.fwId = parseInt(res.data[0].props.flowId)
              this.showForm = true
            } else {
              this.categoryName = res.data[0].text
              this.categoryId = res.data[0].id
              this.fwId = undefined
              this.showForm = true
            }
          }
        } else {
          this.treeData = []
          this.empty = true
        }
      })
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange(e) {
      const value = e.target.value
      const expandedKeys = this.dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.id
        const title = node.text
        this.dataList.push({ key, title: title })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },

    onSelect(selectedKeys, info) {
      this.selectedkey = selectedKeys
      this.categoryName = info.node.dataRef.text
      this.categoryId = info.node.dataRef.id
      if (this.$refs.docform) {
        this.$refs.docform.setFieldValue('categoryName', info.node.dataRef.text)
        this.$refs.docform.setFieldValue('categoryId', info.node.dataRef.id)
      }
      this.fwId =
        info.node.dataRef.props.flowId !== null && info.node.dataRef.props.flowId !== undefined
          ? parseInt(info.node.dataRef.props.flowId)
          : undefined
      this.showForm = true
    },

    fwSaved() {
      Message.success('保存成功')
      this.treeData = []
      this.queryKnowledageTree(this.selectedkey)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.spin {
  width: 100%;
  line-height: 30;
}
.search-color {
  color: $orange-6;
}
.badge {
  margin-left: 5px;
}

.wrap-height {
  height: 100%;
  .row-height {
    height: 100%;
    .tree-wrap {
      height: 100%;
      padding-right: $padding-lg;
      :global(.ant-card) {
        height: 100%;
        overflow: auto;
      }
    }
  }
}

// 隐藏退出按钮
.form-height {
  height: 100%;
  .form {
    height: 100%;
    overflow: auto;
    :global(.sd-form-btns-close) {
      display: none;
    }
  }
}
</style>
