<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-tree
        :key="refreshkey"
        ref="tree"
        :checkable="false"
        :draggable="true"
        :is-search="false"
        :show-line="true"
        :top-node-text="'内部制度分类'"
        :treeparams="{
          configId: 71,
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="true"
        :dep-options="categorys"
        manager-type="view"
        @treeSelect="treeSelect"
        @dragNodeOk="dragNodeOk"
      >
      </audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            :key="refreshkey"
            ref="list"
            :editnode="editnode"
            form-id="iamInstitutionCategory"
            page-id="core/institution/iamInstitutionCategory"
            :columns="columns"
            :actions="actions"
            show-selection
            :filter-expressions="filterExpressions"
            :search-fields="['categoryCode', 'categoryName']"
            :custom-delete-fun="deleteRows"
            @recordSaved="onRecordSaved"
            @recordsDeleted="onRecordsDeleted"
          >
            <template v-slot:form="{ model, fields, pageId }">
              <sd-form-item :hidden="true" name="id"></sd-form-item>
              <sd-form-item :hidden="true" name="parentId"></sd-form-item>
              <!-- 上级分类，做成树的样子 -->
              <!-- <sd-form-item label="上级分类" name="choosePicker">
                <sd-value-picker
                  v-model="chooseoption"
                  single
                  option-value="code"
                  option-label="name"
                  @change="startchoose(model)"
                >
                  <template v-slot="scope">
                    <sd-picker-source-tree
                      title="内部制度分类"
                      :load-tree-data="loadTreeData"
                      :search-tree-data="searchTreeData"
                      v-bind="scope"
                    />
                  </template>
                </sd-value-picker>
              </sd-form-item> -->
              <!-- <sd-form-item name="categoryCode"></sd-form-item> -->
              <a-form-model-item
                prop="categoryCode"
                label="分类编号"
                :rules="[
                  { required: true, validator: validator, trigger: 'blur', itemId: model.id },
                ]"
              >
                <a-input v-model.trim="model.categoryCode" />
              </a-form-model-item>
              <sd-form-item v-if="initParam(model)" name="categoryName"></sd-form-item>
              <sd-form-item name="categoryContent">
                <a-textarea v-model="model.categoryContent" :rows="3" />
              </sd-form-item>
              <sd-form-item name="whether"></sd-form-item>
              <sd-form-item name="sortNum"></sd-form-item>
              <sd-form-item :hidden="true" name="creationTime"></sd-form-item>
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { message, Modal } from '@/common/one-ui'
import axios from '@/common/services/axios-instance'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import auditTree from '../../components/audit-tree.vue'
import components from './_import-components/iam-audit-auditsource-institutioncategory-form-import'
const columns = [
  {
    title: '排序号',
    align: 'center',
    dataIndex: 'sortNum',
    defaultSortOrder: 'asc',
    sdHidden: true,
  },
  {
    title: '序号',
    dataIndex: 'xh',
    width: '70px',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '分类编码',
    dataIndex: 'categoryCode',
  },
  {
    title: '分类名称',
    dataIndex: 'categoryName',
    sdClickable: true,
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sdRender: TableColumnTypes.date,
  },
  {
    title: '是否是末级分类',
    dataIndex: 'whether',
    // width: '128px',
  },
]
export default {
  name: 'IamAuditAuditsourceInstitutioncategoryForm',
  metaInfo: {
    title: '内部制度分类',
  },
  components: {
    // SdDataTableEx,
    // sd-form-item,
    // SdPickerSourceTree,
    // SdValuePicker,
    ...components,
    auditTree,
  },
  data() {
    return {
      refreshkey: 0,
      editnode: true, // 列表是否可编辑
      columns,
      // 树的数据
      categorys: [],
      // 父id
      parentId: 0,
      // 是否是根节点
      isRoot: true,
      req: true,
      // 选择器绑定
      chooseoption: [
        {
          code: '',
          name: '内部制度分类',
          type: 'collection',
        },
      ],
      filterExpressions: [
        {
          dataType: 'long',
          name: 'parentId',
          op: 'eq',
          longValue: -1,
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
          permission: 'create',
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
          permission: 'delete',
        },
      ],
    }
  },
  methods: {
    // 节点拖拽完成
    dragNodeOk() {
      this.$refs.list.clearSelection()
      this.$refs.list.refresh()
    },
    deleteRows(selectedRowKeys) {
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            axios({
              url: 'api/framework/v1/page/iamInstitutionCategory',
              method: 'delete',
              params: {
                ids: selectedRowKeys.join(','),
              },
            })
              .then(() => {
                this.$refs.list.clearSelection()
                this.$refs.list.refresh()
                message.success('删除成功')
              })
              .finally(resolve)
              .catch(() => {
                message.error('此分类下有其他内部制度信息，或内部制度分类信息，无法删除')
              })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    loadTreeData(parentCatId) {
      if (!parentCatId) {
        // parentCatId = '0'
        parentCatId = this.parentId
      }
      return axios({
        url: 'api/xcoa-mobile/v1/iam-institution-category/categoryParentId?parentId=' + parentCatId,
        method: 'get',
      }).then((res) => {
        if (res.status) {
          return res.data
        }
      })
    },
    initParam(model) {
      model.parentId = this.parentId

      if (model.choosePicker && model.choosePicker.length > 0) {
        this.chooseoption = model.choosePicker
      }
      return true
    },
    treeSelect(selectedKeys, info) {
      debugger
      const props = info.selectedNodes[0].data.props.props
      if (props) {
        const flag = props.isroot
        if (flag !== undefined && flag === true) {
          this.isRoot = flag
        } else {
          this.isRoot = false
        }
      }
      if (this.isRoot === true) {
        axios({
          url:
            'api/xcoa-mobile/v1/iam-institution-category/rootCateId?orgId=' +
            info.selectedNodes[0].data.props.id,
          method: 'get',
        })
      }
      if (info.selectedNodes && info.selectedNodes.length > 0) {
        this.filterExpressions[0].longValue = info.selectedNodes[0].data.props.id
        this.parentId = info.selectedNodes[0].data.props.id
        // 设置默认选项
        this.refresh()
      }

      const datas = info.selectedNodes
      if (datas && datas.length > 0) {
        const data = datas[0].data.props
        this.editnode = data.edit
        this.chooseoption = []
        this.chooseoption.push({
          code: data.id,
          name: data.text,
          type: 'collection',
        })
      } else {
        this.editnode = false
        this.filterExpressions[0].longValue = -1
      }
    },
    refresh() {
      return this.$refs.list.refresh(true)
    },
    startchoose(model) {
      model.choosePicker = this.chooseoption
      model.parentId = this.chooseoption[0].code
    },
    searchTreeData(text) {
      // 查询数据
      return axios({
        url: 'api/xcoa-mobile/v1/iam-institution-category/categoryNameOrCode?nameOrCode=' + text,
        method: 'get',
      }).then((res) => {
        if (res.status) {
          return res.data
        }
      })
    },
    onRecordSaved() {
      this.$refs.tree.refreshNode(this.parentId)
    },
    onRecordsDeleted() {
      this.$refs.tree.refreshNode(this.parentId)
    },
    validator(rule, value, callback) {
      if (value === undefined || value === '') {
        callback('不能为空')
        return
      }
      const parentIdAndCode = { parentId: this.parentId, code: value, itemId: rule.itemId }
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/iam-institution-category/checkCode',
        data: parentIdAndCode,
      }).then((res) => {
        if (res.data === false) {
          callback('编码已经存在，不能重复创建')
        } else {
          callback('')
        }
      })
    },
  },
}
</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>
