<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-tree
        :key="refreshkey"
        ref="auditTrees"
        :checkable="false"
        :draggable="true"
        :is-search="false"
        :show-line="true"
        :top-node-text="'审计知识分类'"
        :treeparams="{
          configId: 81,
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="true"
        manager-type="view"
        @treeSelect="treeSelectd"
        @dragNodeOk="dragNodeOk"
      >
      </audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-oa-table
            :key="refreshkey"
            ref="oaTable"
            :editnode="editnode"
            form-id="kmKnowledgeCategory"
            page-id="audit/km/km/admin/kmKnowledgeCategory"
            :columns="columns"
            show-selection
            :actions="actions"
            :search-fields="['name']"
            :filter-expressions="expressions"
            @recordSaved="onRecordSaved"
            @recordsDeleted="onRecordsDeleted"
          >
            <template v-slot:form="{ model }">
              <sd-form-item name="code">
                <template v-slot:read-and-edit="{ editable }">
                  <a-form-model-item
                    v-if="editable"
                    prop="code"
                    :rules="[
                      { validator: validator },
                      {
                        required: true,
                        trigger: ['change', 'blur'],
                      },
                    ]"
                  >
                    <a-input v-model.trim="model.code" />
                  </a-form-model-item>
                  <span v-else>{{ model.code }}</span>
                </template>
              </sd-form-item>
              <sd-form-item name="name"></sd-form-item>
              <sd-form-item name="catalogDesc">
                <a-textarea v-model="model.catalogDesc" :rows="3" />
              </sd-form-item>
              <sd-form-item name="isEnd"></sd-form-item>
              <sd-form-item name="sortNumber"></sd-form-item>
              <sd-form-item name="knowledgeAdminMember"></sd-form-item>
              <sd-form-item
                :hidden="true"
                name="parentId"
                :input-props="{ defaultValue: selectdParentId }"
              ></sd-form-item>
            </template>
          </sd-oa-table>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash.debounce'
import KmKnowledageService from '../km-knowledage-service'
import auditTree from '../../../../components/audit-tree.vue'
import components from './_import-components/km-knowledge-category-import'
import axios from '@/common/services/axios-instance'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
const columns = [
  {
    title: '排序号',
    align: 'center',
    width: '100px',
    dataIndex: 'sortNumber',
    defaultSortOrder: 'asc',
    sdHidden: true,
  },
  {
    title: '序号',
    dataIndex: 'xh',
    width: '70px',
    customRender: (text, record, index) => `${index + 1}`,
  },

  {
    title: '分类编号',
    dataIndex: 'code',
  },
  {
    title: '分类名称',
    dataIndex: 'name',
    sdClickable: true,
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sorter: true,
    sdRender: TableColumnTypes.date,
  },
  {
    title: '是否末级分类',
    dataIndex: 'isEnd',
  },
  // {
  //   title: '分类管理员',
  //   dataIndex: 'adminMember',
  // },
]
export default {
  name: 'KmKnowledgeCategory',
  metaInfo: {
    title: '知识库分类维护',
  },
  components: { auditTree, ...components },
  data() {
    return {
      editnode: true,
      refreshkey: 0,
      columns,
      nodeSelect: null,
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: null, // 纯前端操作，不需要权限控制
          type: TableActionTypes.oa.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
        // {
        //   label: '维护顶结点',
        //   permission: null, // 纯前端操作，不需要权限控制
        //   id: 'editRoot', // 没写type，一般按钮
        //   callback: () => {
        //     this.fnEditRoot()
        //   },
        // },
      ],

      selectdParentId: 0,
      selectdParentName: null,
      expressions: [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: -1,
        },
      ],
    }
  },
  methods: {
    // 节点拖拽完成
    dragNodeOk() {
      this.$refs.oaTable.clearSelection()
      this.$refs.oaTable.refresh()
    },
    validator(rule, value, callback) {
      let id = -1
      if (this.$refs.oaTable.recordId) {
        id = this.$refs.oaTable.recordId
      }

      const url =
        `api/xcoa-mobile/v1/km-knowledge-category/check-category-code?code=${value}&parentId=${this.selectdParentId}&id=` +
        id
      debounce(() => {
        axios.get(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在分类编码，不可以重复')
          }
        })
      }, 500)()
    },
    // 树选择节点后获取列表数据
    treeSelectd(infos, item) {
      debugger
      if (item.selectedNodes?.length > 0) {
        let parentId = ''
        let parentName = ''
        if (item.id !== undefined) {
          parentId = item.id
          parentName = item.text
        } else {
          parentId = item.selectedNodes[0].data.props.id
          parentName = item.selectedNodes[0].data.props.text
          this.editnode = item.selectedNodes[0].data.props.edit
          debugger
          if (item.selectedNodes[0].data.props.props !== undefined) {
            var isEnd = item.selectedNodes[0].data.props.props.IS_END
            if (isEnd === '1') {
              this.editnode = false
            }
          }
        }
        this.selectdParentId = parseInt(parentId)
        this.selectdParentName = parentName
        this.nodeSelect = {
          dataRef: {
            id: parentId,
          },
        }
        const filter = {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: this.selectdParentId,
        }

        this.expressions = [filter]
        const params = {
          parentId: parentId,
        }
        KmKnowledageService.getKnowledgeCategoryParentAdmin(params).then((res) => {
          const datas = res.data
          if (datas) {
            this.editnode = true
          } else {
            this.editnode = false
          }
        })
      } else {
        this.editnode = false
        // 没有上级分类时parentId传-1
        const filter = {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: -1,
        }

        this.expressions = [filter]

        this.selectdParentId = 0
      }
    },

    // 保存成功后刷新树
    onRecordSaved() {
      this.$refs.auditTrees.refreshNode(this.selectdParentId)
    },
    // 删除成功后刷新树
    onRecordsDeleted() {
      this.$refs.auditTrees.refreshNode(this.selectdParentId)
    },

    // 维护树的顶结点（维护的是当前选中的节点的顶结点）
    fnEditRoot() {
      // 先判断是否有树，没有的话新建顶结点
      if (this.$refs.tree.treeData.length === 0) {
        this.selectdParentId = 0
        this.$refs.oaTable.showDetailModal()
      } else {
        // 有的话查找选中节点的顶结点
        const parentId = this.$refs.tree.getRootKey(this.selectdParentId)
        if (parentId) {
          this.$refs.oaTable.showDetailModal(parentId)
        }
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
