<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: 111,
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="true"
        manager-type="view"
        @treeSelect="treeSelectd"
      >
      </audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-oa-table
            :key="refreshkey"
            ref="oaTable"
            :editnode="editnode"
            form-id="spicProblemCategory"
            page-id="audit/spicproblem/spicProblemCategory"
            :columns="columns"
            show-selection
            :actions="actions"
            :search-fields="['categoryName']"
            :filter-expressions="expressions"
            @recordSaved="onRecordSaved"
            @recordsDeleted="onRecordsDeleted"
          >
            <template v-slot:form="{ model }">
              <a-form-model-item
                prop="categoryCode"
                label="分类编号"
                :rules="[
                  { validator: validator },
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                ]"
              >
                <a-input v-model.trim="model.categoryCode" />
              </a-form-model-item>
              <sd-form-item name="categoryName"></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
                :hidden="true"
                name="parentId"
                :input-props="{ defaultValue: selectdParentId }"
              ></sd-form-item>
            </template>
          </sd-oa-table>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import auditTree from '@product/iam/components/audit-tree.vue'
import components from './_import-components/xm-spic-problem-category-import'
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: 'categoryCode',
  },
  {
    title: '分类名称',
    dataIndex: 'categoryName',
    sdClickable: true,
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sorter: true,
    sdRender: TableColumnTypes.date,
  },
  {
    title: '是否末级分类',
    dataIndex: 'isEnd',
  },
  // {
  //   title: '分类管理员',
  //   dataIndex: 'adminMember',
  // },
]
export default {
  name: 'XmSpicProblemCategory',
  metaInfo: {
    title: '案例分类维护',
  },
  components: { auditTree, ...components },
  data() {
    return {
      refreshkey: 0,
      editnode: true,
      columns,
      nodeSelect: null,
      actions: [
        {
          label: '新建',
          id: 'new',
          permission: null,
          type: TableActionTypes.oa.create,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null, // 纯前端操作，不需要权限控制
          // type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
          callback: () => {
            this.deleteRows()
          },
        },
      ],

      selectdParentId: 0,
      selectdParentName: null,
      expressions: [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: -1,
        },
      ],
    }
  },
  methods: {
    validator(rule, value, callback) {
      let id = -1
      if (this.$refs.oaTable.recordId) {
        id = this.$refs.oaTable.recordId
      }

      const url =
        `api/xcoa-mobile/v1/spicproblem-category/check-category-code?categoryCode=${value}&parentId=${this.selectdParentId}&id=` +
        id
      debounce(() => {
        axios.get(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在分类编码，不可以重复')
          }
        })
      }, 500)()
    },
    // 保存成功后刷新树
    onRecordSaved() {
      this.refreshkey++
      this.$refs.auditTrees.refreshNode(this.selectdParentId)
    },
    // 列表删除数据
    deleteRows() {
      const selectedRowKeys = this.$refs.oaTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      Modal.confirm({
        title: '你确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          this.loading = true
          const params = {
            ids: selectedRowKeys.join(','),
          }
          // 检查分类下是否还有问题
          axios({
            url: `api/xcoa-mobile/v1/spicproblem-category/delete-check-category?ids=${params.ids}`,
            method: 'GET',
          }).then((res) => {
            if (res.data) {
              // 删除方法
              axios({
                url: `api/xcoa-mobile/v1/spicproblem-category/delete-category?ids=${params.ids}`,
                method: 'DELETE',
              }).then((res) => {
                if (res.status === 200) {
                  this.$refs.oaTable.clearSelection()
                  this.$refs.oaTable.refresh()
                  this.loading = false
                  message.success('删除成功')
                  this.refreshkey++
                }
              })
            } else {
              message.warning('分类下存在未删除问题，删除失败')
            }
          })
        },
      })
    },
    // 删除成功后刷新树
    onRecordsDeleted() {
      this.refreshkey++
      this.$refs.auditTrees.refreshNode(this.selectdParentId)
    },
    // 树选择节点后获取列表数据
    treeSelectd(infos, item) {
      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
          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 = item
        const filter = {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: this.selectdParentId,
        }

        this.expressions = [filter]
      } else {
        // 没有上级分类时parentId传-1
        const filter = {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: -1,
        }

        this.expressions = [filter]
        this.editnode = false
        this.selectdParentId = 0
      }
    },
  },
}
</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>
