<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-maintain-classify-tree
        ref="auditMaintainCatalogTree"
        show-line
        top-node-text="审计模型"
        :is-select-dep="true"
        :draggable="true"
        :cate="true"
        @treeSelect="treeSelect"
        @depChanged="depChanged"
      ></audit-maintain-classify-tree>

      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            :key="key"
            ref="dataTable"
            :editnode="editnode"
            form-id="iamModelCategory"
            page-id="audit/maintain/iamModelCategory"
            :columns="columns1"
            :actions="actions"
            :search-fields="['categoryName']"
            :filter-expressions="expressions"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            :custom-delete-fun="deleteRows"
            @recordSaved="onRecordSaved"
            @formBtnClick="formBtnClick"
          >
            <template slot="categoryName" slot-scope="text, record">
              <a
                v-if="record.editAndDeleteAuth !== 0"
                @click="
                  () => {
                    $refs.dataTable.showDetailModal(record.id, 'audit/maintain/iamModelCategory')
                  }
                "
                >{{ 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="id"
                label="分类编号"
                :rules="[
                  { validator: validator },
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                ]"
              >
                <a-input v-model.trim="model.categoryId" />
              </a-form-model-item>

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

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

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

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

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

              <sd-form-item
                :hidden="true"
                name="auditOrgId"
                :input-props="{ defaultValue: auditOrgId, 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 auditMaintainClassifyTree from './audit-maintain-classify-tree'
import auditMaintainService from './audit-maintain-service'
import components from './_import-components/audit-maintain-catalog-import'

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

        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '是否末级分类',
          dataIndex: 'isLeaf',
        },
      ],
      actions: [],
      actionscsh: [
        {
          label: '新建',
          type: 'primary',
          callback: this.create,
          permission: null,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: 'delete',
          callback: this.deleteRows,
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'parentId',
          op: 'eq',
          longValue: null,
        },
        // {
        //   dataType: 'long',
        //   name: 'auditOrgId',
        //   op: 'eq',
        //   longValue: null,
        // },
      ],
      parentId: null,
      auditOrgId: null,
      parentName: '业务类型',
      catalogPath: null,
      isEnd: null,
      isroot: true,
    }
  },
  created() {},
  methods: {
    treeSelect(selectedKeys, info) {
      this.parentId = null
      if (selectedKeys.length === 0) return
      this.catalogPath = null
      // 父级id
      if (info != null && info.selectedNodes[0]) {
        if (info.node.dataRef.props.isroot) {
          this.isroot = true
          this.parentId = 0
        } else {
          this.isroot = false
          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.auditMaintainCatalogTree.depvalue) {
          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.auditOrgId = this.parentId
    },

    // 部门下拉框选择事件
    depChanged(value, info) {
      // this.auditOrgId = this.$refs.auditMaintainCatalogTree.depvalue
      // this.auditOrgId = value
      // 获取当前节点权限 判断按钮是否显示
      // if (typeof this.auditOrgId !== 'number' && this.auditOrgId.indexOf('o_') > -1) {
      //   this.showeditbutton(this.auditOrgId.replaceAll('o_', ''))
      // } else {
      // this.showeditbutton(this.auditOrgId)
      this.showeditbutton()
      // }
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.$refs.auditMaintainCatalogTree.refreshNode(this.parentId)
    },
    // 删除回调
    onRecordsDeleted() {
      message.success('删除成功')
      this.$refs.auditMaintainCatalogTree.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/iammodelcategory/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()
      // 判断是否有下级
      auditMaintainService.deleteCheckCategory(ids).then((res) => {
        if (!res) {
          return new Promise((resolve) => {
            Modal.confirm({
              title: '您确定删除这项内容吗？',
              content: '该层级下存在子分类或模型数据，是否全部删除？',
              cancelText: '取消',
              okText: '删除',
              okType: 'danger',
              onOk: () => {
                this.deleteCategory(ids, resolve)
              },
              onCancel: () => {
                resolve()
              },
            })
          })
        } else {
          this.deleteCategory(ids, null)
        }
      })
    },

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

    refresh() {
      this.$refs.dataTable.refresh()
    },
    // 判断按钮显示
    showeditbutton(deptId) {
      // axios({
      //   url: 'api/xcoa-mobile/v1/iammodelmaintain/getRole?selectOrgId=' + deptId,
      //   method: 'get',
      // }).then((res) => {
      //   if (res.data === true) {
      //     if (this.actions.length === 0) {
      // todo暂时放开权限
      // this.actionscsh.forEach((a) => {
      //   this.actions.push(a)
      // })
      //   }
      // } else {
      //   this.actions = []
      // }
      // })
      this.actions = this.actionscsh
    },
  },
}
</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>
