<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-matters-catalog-tree
        ref="auditMattersCatalogTree"
        show-line
        top-node-text="指引库"
        :is-select-dep="true"
        :draggable="true"
        manager-type="view"
        @treeSelect="treeSelect"
        @depChanged="depChanged"
        @dragNodeOk="dragNodeOk"
      ></audit-matters-catalog-tree>

      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            :key="key"
            ref="dataTable"
            :editnode="editnode"
            form-id="iamAuditMattersCatalog"
            page-id="audit/matters/iamAuditMattersCatalog"
            :columns="columns1"
            :actions="actions"
            :search-fields="['catalogName']"
            :filter-expressions="expressions"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            :custom-delete-fun="deleteRows"
            @recordSaved="onRecordSaved"
            @formBtnClick="formBtnClick"
          >
            <template slot="catalogName" slot-scope="text, record">
              <a
                v-if="record.editAndDeleteAuth !== 0"
                @click="
                  () => {
                    $refs.dataTable.showDetailModal(
                      record.id,
                      'audit/matters/iamAuditMattersCatalog'
                    )
                  }
                "
                >{{ text }}</a
              >
              <span v-else>{{ text }}</span>
            </template>

            <!-- 详情表单 -->
            <template v-slot:form="{ model }" v-sd-watermark="waterMark" @saved="onSaved">
              <!-- 一般字段直接写name即可 -->

              <a-form-model-item
                prop="catalogCode"
                label="分类编号"
                :rules="[
                  { validator: validator },
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                ]"
              >
                <a-input v-model.trim="model.catalogCode" />
              </a-form-model-item>
              <!-- <sd-form-item name="catalogCode" /> -->

              <sd-form-item name="catalogName" />

              <sd-form-item name="catalogDesc">
                <a-textarea v-model="model.catalogDesc" :rows="3" />
              </sd-form-item>

              <sd-form-item name="isEnd" />

              <sd-form-item name="sortNumber" />

              <sd-form-item
                :hidden="true"
                name="parentId"
                :input-props="{ defaultValue: parentId, disabled: true }"
              />

              <sd-form-item
                :hidden="true"
                name="orgId"
                :input-props="{ defaultValue: orgId, disabled: true }"
              />

              <sd-form-item
                :hidden="true"
                name="catalogPath"
                :input-props="{ defaultValue: catalogPath, disabled: true }"
              />
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import TableColumnTypes from '@/common/services/table-column-types'
import systemManage from '@/system-manage/system-manage'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import TableActionTypes from '@/common/services/table-action-types'
import auditMattersCatalogTree from './audit-matters-catalog-tree'
import auditMattersService from './audit-matters-service'
import components from './_import-components/audit-matters-catalog-import'

export default {
  name: 'AuditMattersCatalog',
  metaInfo: {
    title: '指引分类配置',
  },
  components: {
    ...components,
    auditMattersCatalogTree,
  },
  data() {
    return {
      editnode: true, // 列表是否可以新建
      key: 0,
      waterMark: systemManage.getFormWaterMark(),
      treeData: [],
      columns1: [
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          dataIndex: 'parentId',
          sdHidden: true,
        },
        {
          title: '排序号',
          dataIndex: 'sortNumber',
          defaultSortOrder: 'ascend',
          width: '100px',
        },
        {
          title: '分类编号',
          dataIndex: 'catalogCode',
        },
        {
          title: '分类名称',
          dataIndex: 'catalogName',
          scopedSlots: { customRender: 'catalogName' },
        },

        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '是否末级分类',
          dataIndex: 'isEnd',
        },
      ],
      actions: [
        {
          label: '新建',
          type: 'primary',
          callback: this.create,
          permission: 'iamAuditMatters-create',
        },
        {
          label: '删除',
          id: 'delete',
          permission: 'iamAuditMatters-delete',
          type: 'delete',
          callback: this.deleteRows,
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'parentId',
          op: 'eq',
          longValue: null,
        },
      ],
      parentId: 0,
      orgId: null,
      parentName: '业务类型',
      catalogPath: null,
      isEnd: null,
    }
  },
  created() {},
  methods: {
    // 节点拖拽完成
    dragNodeOk() {
      this.$refs.dataTable.clearSelection()
      this.$refs.dataTable.refresh()
    },
    treeSelect(selectedKeys, info) {
      this.catalogPath = null
      // 父级id
      if (info != null && info.selectedNodes[0]) {
        this.parentId = Number(info.selectedNodes[0].data.props.id)
        this.parentName = info.selectedNodes[0].data.props.text // 父级名称
        //  this.orgId = Number(info.selectedNodes[0].data.props.id)
        this.editnode = info.selectedNodes[0].data.props.edit
        if (info.selectedNodes[0].data.props.props) {
          this.isEnd = info.selectedNodes[0].data.props.props.isEnd
        }

        // 判断父节点不为根节点
        if (this.parentId !== this.$refs.auditMattersCatalogTree.depvalue) {
          if (info.selectedNodes[0].data.props.props.catalogPath) {
            this.catalogPath =
              info.selectedNodes[0].data.props.props.catalogPath + ',' + this.parentId
          } else {
            this.catalogPath = this.parentId
          }
        }
      } else {
        if (selectedKeys.id) {
          this.parentId = Number(selectedKeys.id)
          this.parentName = selectedKeys.text // 父级名称
        } else {
          this.parentId = 0
        }
      }
      // 如果是末级，则隐藏新建按钮

      this.expressions.forEach((item) => {
        if (item.name === 'parentId') {
          item.longValue = this.parentId
        }
      })
      this.expressions = [...this.expressions]
      this.orgId = this.$refs.auditMattersCatalogTree.depvalue
    },

    // 部门下拉框选择事件
    depChanged(value, info) {
      this.orgId = this.$refs.auditMattersCatalogTree.depvalue
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.$refs.auditMattersCatalogTree.refreshNode(this.parentId)
    },
    // 删除回调
    onRecordsDeleted() {
      message.success('删除成功')
      this.$refs.auditMattersCatalogTree.refreshNode(this.parentId)
    },
    formBtnClick(evt, btn) {},
    validator(rule, value, callback) {
      let id = -1
      if (this.$refs.dataTable.recordId) {
        id = this.$refs.dataTable.recordId
      }
      value = encodeURIComponent(value)
      const url =
        `api/xcoa-mobile/v1/iam-audit-matters-catalog/check-category-code?catalogCode=${value}&parentId=${this.parentId}&id=` +
        id
      debounce(() => {
        axios.get(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在分类编码，不可以重复')
          }
        })
      }, 500)()
    },

    deleteRows() {
      const ids = this.$refs.dataTable.getSelectedRowKeys()
      if (ids.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      // 判断是否有下级
      auditMattersService.deleteCheckCategory(ids).then((res) => {
        if (!res) {
          return new Promise((resolve) => {
            Modal.confirm({
              title: '您确定删除这项内容吗？',
              content: '该层级下有子节点，是否全部删除？',
              okText: '删除',
              okType: 'danger',
              onOk: () => {
                this.deleteCategory(ids, resolve)
              },
              onCancel: () => {
                resolve()
              },
            })
          })
        } else {
          this.deleteCategory(ids, null)
        }
      })
    },

    create() {
      if (this.parentId === 0) {
        message.error('请选择上级节点！')
      } else {
        if (this.isEnd !== '1') {
          this.$refs.dataTable.showDetailModal(null, 'audit/matters/iamAuditMattersCatalog')
        } else {
          message.error('末级分类下不可再新建分类')
        }
      }
    },
    deleteCategory(ids, resolve) {
      auditMattersService
        .deleteCategory(ids)
        .then(() => {
          this.$refs.dataTable.clearSelection()
          this.onRecordsDeleted()
          this.refresh()
        })
        .finally(resolve)
    },

    refresh() {
      this.$refs.dataTable.refresh()
    },
  },
}
</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>
