<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <!-- 左侧 -->

      <audit-model-tree ref="auditModelTree" @treeSelect="treeSelect" @depChanged="depChanged">
        <div :class="$style.treeWrap">
          <!-- 我的模型 和分类管理并列 -->
          <div :class="$style.treeTitle">我的模型</div>
        </div>
      </audit-model-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            :key="key"
            ref="dataTable"
            :editnode="editnode"
            form-id="iamModelOwnCategory"
            page-id="audit/datacube/iamModelOwnCategory"
            :columns="columns1"
            :actions="actions"
            :search-fields="['categoryName', 'categoryId']"
            :filter-expressions="expressions"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            :custom-delete-fun="deleteRows"
            @recordSaved="onRecordSaved"
          >
            <template slot="categoryName" slot-scope="text, record">
              <a
                v-if="record.editAndDeleteAuth !== 0"
                @click="
                  () => {
                    $refs.dataTable.showDetailModal(record.id, 'audit/datacube/iamModelOwnCategory')
                  }
                "
                >{{ text }}</a
              >
              <span v-else>{{ text }}</span>
            </template>

            <!-- 详情表单 -->
            <template v-slot:form="{ model }" v-sd-watermark="waterMark" @saved="onSaved">
              <!-- 一般字段直接写name即可 -->
              <!-- { validator: validator }, -->
              <!-- <a-form-model-item
                prop="categoryId"
                label="分类编号"
                :rules="[
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                  // 只能是数字
                  {
                    pattern: /^[0-9]*$/,
                    message: '只能输入数字',
                    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="sortNum" :input-props="{ defaultValue: 0 }" />

              <sd-form-item
                :hidden="true"
                name="parentId"
                :input-props="{ defaultValue: parentId, disabled: true }"
              />
              <!-- creatorAccount -->
              <!-- <sd-form-item
                :hidden="true"
                name="creatorAccount"
                :input-props="{ defaultValue: getUserInfo().account, disabled: true }"
              /> -->
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import components from './_import-components/audit-model-class-import'
import TableColumnTypes from '@/common/services/table-column-types'
import auditModelService from './audit-model-service'
import auditModelTree from './audit-model-tree.vue'
import { Modal, message } from 'ant-design-vue'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
export default {
  name: 'AuditModelClass',
  metaInfo: {
    title: '分类管理',
  },
  components: {
    ...components,
    auditModelTree,
  },
  data() {
    return {
      editnode: true, // 列表是否可以新建
      key: 0,
      expressions: [
        // <!--  创建人 -->
        {
          dataType: 'str',
          name: 'creatorAccount',
          op: 'eq',
          stringValue: getUserInfo().account,
        },

        //
      ],
      columns1: [
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          dataIndex: 'parentId',
          sdHidden: true,
        },
        {
          title: '排序号',
          dataIndex: 'sortNum',
          defaultSortOrder: 'ascend',
          width: '100px',
        },
        {
          title: '分类编号',
          dataIndex: 'id',
        },
        {
          title: '分类名称',
          dataIndex: 'categoryName',
          scopedSlots: { customRender: 'categoryName' },
        },

        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
      ],
      actions: [
        {
          label: '新建',
          type: 'primary',
          callback: this.create,
          permission: null,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          type: 'delete',
          callback: this.deleteRows,
        },
      ],
      isEnd: null,
      isroot: true,
      parentId: null,
      auditOrgId: null,
    }
  },
  methods: {
    // 新建分类
    create() {
      if (this.parentId === null) {
        return message.error('请选择分类')
      }
      if (this.isEnd !== '1' && this.isEnd !== 1) {
        this.$refs.dataTable.showDetailModal(null, 'audit/datacube/iamModelOwnCategory')
        // this.$refs.dataTable.$refs.detail.setFieldValue('parentId', this.parentId)
      } else {
        message.error('末级分类下不可再新建分类')
      }
    },
    // 删除分类
    deleteCategory(ids, resolve) {
      auditModelService
        .deleteCategory(ids)
        .then(() => {
          this.onRecordsDeleted()
          this.refresh()
        })
        .finally(resolve)
    },
    // 校验分类
    deleteRows() {
      const ids = this.$refs.dataTable.getSelectedRowKeys()
      // 判断是否有下级
      auditModelService.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)
        }
      })
    },
    refresh() {
      this.$refs.dataTable.refresh()
    },
    // 分类树操作
    // 新建保存回调刷新树
    onRecordSaved() {
      this.$refs.auditModelTree.refreshNode(this.parentId)
    },
    // 删除回调
    onRecordsDeleted() {
      message.success('删除成功')
      this.$refs.auditModelTree.refreshNode(this.parentId)
    },
    // 分类树触发事件
    treeSelect(selectedKeys, info) {
      if (selectedKeys.length === 0) {
        // 未选中节点
        // 清空数据
        this.parentId = null
        this.expressions = this.expressions.filter((item) => item.name !== 'parentId')
        return
      }
      const dataRef = info.node.dataRef

      if (dataRef.isroot) {
        this.parentId = 0
        this.expressions.forEach((item, i) => {
          if (item.name === 'parentId') {
            // 删除当前元素
            this.expressions.splice(i, 1)
          }
        })
      } else {
        this.parentId = dataRef.id
        this.expressions = this.expressions.filter((item) => item.name !== 'parentId')
        this.expressions.push({
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: this.parentId,
        })
      }
      this.key += 1

      // 是否是末尾节点
    },
    depChanged(selectedKeys, info) {},
    // 分类编码校验
    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/iammodelowncate/check-category-code?catalogCode=${value}&parentId=${this.parentId}&id=` +
        id
      debounce(() => {
        axios.get(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在分类编码，不可以重复')
          }
        })
      }, 500)()
    },
  },
}
</script>

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

.tree-wrap {
  display: flex;
  align-items: flex-end;
  // 分散布局 水平居中
  justify-content: space-between;
  padding-bottom: 10px;
  margin-top: 10px;
  border-bottom: 1px solid $black;
}
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
