<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-tree
        ref="auditTree"
        :checkable="true"
        :draggable="true"
        :is-search="true"
        :show-line="false"
        :top-node-text="'测试顶节点'"
        :treeparams="{
          configId: '11',
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="true"
        :dep-options="[
          {
            value: '1',
            lable: 'label1',
            key: '1',
            title: '临时组织',
            children: [
              {
                value: '11',
                lable: 'label2',
                key: '1-1',
                title: '临时组织1',
                children: [
                  {
                    value: '111',
                    lable: 'label3',
                    key: '1-1-1',
                    title: '临时组织2',
                    children: [],
                  },
                ],
              },
            ],
          },
        ]"
        @treeSelect="treeSelect"
        @depChanged="depChanged"
      ></audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            ref="dataTable"
            form-id="oaBaseBusinessTypeCat"
            page-id="base/businesstype/oaBaseBusinessTypeCat"
            :columns="columns1"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            :actions="actions"
            :search-fields="['categoryName']"
            :filter-expressions="expressions"
            @recordSaved="onRecordSaved"
            @recordsDeleted="onRecordsDeleted"
          >
            <template slot="categoryName" slot-scope="text, record">
              <a
                v-if="record.editAndDeleteAuth !== 0"
                @click="
                  () => {
                    $refs.dataTable.showDetailModal(
                      record.id,
                      'base/businesstype/oaBaseBusinessTypeCat'
                    )
                  }
                "
                >{{ text }}</a
              >
              <span v-else>{{ text }}</span>
            </template>
            <!-- 详情表单 -->
            <template v-slot:form="{ model }" @saved="onSaved">
              <!-- 一般字段直接写name即可 -->
              <sd-form-item name="categoryName" />
              <sd-form-item
                :hidden="true"
                name="parentId"
                :input-props="{ defaultValue: parentId, disabled: true }"
              />
              <sd-form-item
                :hidden="true"
                name="parentName"
                :input-props="{ defaultValue: parentName, disabled: true }"
              >
              </sd-form-item>
              <a-form-model-item
                label="上级分类"
                :rules="[
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="parentId"
              >
                <sd-tree-picker
                  v-model="parentObj"
                  single
                  :load-tree-data="loadTreeData"
                  @change="fnTreePicker"
                >
                </sd-tree-picker>
              </a-form-model-item>

              <a-form-model-item
                :label="'编\u2003\u2003码'"
                :rules="[
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                  {
                    validator: validator,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="categoryCode"
              >
                <a-input v-model="model.categoryCode">
                  <a-tooltip slot="suffix" title="编码推荐格式：PRODUCT_模块_业务，如PRODUCT_GW_FW">
                    <a-icon type="info-circle" /> </a-tooltip
                ></a-input>
              </a-form-model-item>
              <sd-form-item name="sortNumber" />
              <sd-form-item name="isDoc"> </sd-form-item>
              <sd-form-item name="redheadEnable"> </sd-form-item>
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import auditTree from '../../components/audit-tree.vue'
import BusinesstypeService from '../../../../src/business-type/businesstype-service'
import components from './_import-components/test-tree-import'

export default {
  name: 'TestTree',
  metaInfo: {
    title: '地址树模板',
  },
  components: {
    ...components,
    auditTree,
  },
  data() {
    return {
      key: 0,
      treeData: [],
      columns1: [
        {
          title: '排序号',
          dataIndex: 'sortNumber',
          defaultSortOrder: 'ascend',
          width: '100px',
        },
        {
          title: '分类名称',
          dataIndex: 'categoryName',
          scopedSlots: { customRender: 'categoryName' },
        },
        {
          title: '编码',
          dataIndex: 'categoryCode',
        },
        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.dateTime,
        },
        {
          title: '是否可编辑',
          dataIndex: 'editAndDeleteAuth',
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: 0,
        },
      ],
      selectedKeys: ['0'],
      parentId: 0,
      parentName: '业务类型',
      parentObj: [{ id: '0', name: '业务类型' }],
      isDocType: '', // 是否公文类
    }
  },
  methods: {
    // 获取菜单树数据
    addTreeKey(data) {
      let result
      if (!data) {
        return
      }
      for (var i = 0; i < data.length; i++) {
        const item = data[i]
        item.key = item.id
        if (item.children && item.children.length > 0) {
          result = this.addTreeKey(item.children)
        } else {
          result = this.addTreeKey(item.children)
        }
      }
      return result
    },

    // 处理用户要选择的数据
    mapCategoryItems(items) {
      return (items || []).map((item) => {
        // 不能选择当前节点的下级节点
        let isLeaf = item.leaf
        if (item.id === String(this.$refs.dataTable.getDetailModal().getFieldValue('parentId'))) {
          isLeaf = true
        }
        const result = {
          id: item.id,
          name: item.text,
          checkable: true,
          isLeaf,
        }
        return result
      })
    },

    // 获取用于选择的业务类型分类树
    loadTreeData(id) {
      if (id) {
        return BusinesstypeService.getCategoryTree({ parentId: id }).then((res) => {
          return this.mapCategoryItems(res.data)
        })
      } else {
        return BusinesstypeService.getCategoryTree().then((res) => {
          const treeNode = [
            {
              id: '0',
              name: '业务类型',
              leaf: false,
              children: this.mapCategoryItems(res.data),
            },
          ]
          return treeNode
        })
      }
    },

    // 选择上级分类后给对应的域赋值
    fnTreePicker(value) {
      if (value.length > 0) {
        this.$refs.dataTable.getDetailModal().setFieldValue('parentId', value[0].id)
        this.$refs.dataTable.getDetailModal().setFieldValue('parentName', value[0].name)
      } else {
        this.$refs.dataTable.getDetailModal().setFieldValue('parentId', '')
        this.$refs.dataTable.getDetailModal().setFieldValue('parentName', '')
      }
    },

    treeSelect(selectedKeys, info) {
      this.parentId = info.node.dataRef.id // 父级id
      this.parentName = info.node.dataRef.text // 父级名称
      this.parentObj = [{ id: info.node.dataRef.id, name: info.node.dataRef.text }]
      // 是否公文类
      this.isDocType = info.node.dataRef.props.isDoc
      this.selectedKeys = selectedKeys
      this.expressions.forEach((item) => {
        if (item.name === 'parentId') {
          item.stringValue = Number(info.node.dataRef.id)
        }
      })
      this.expressions = [...this.expressions]
      this.selectedKeys = selectedKeys
      this.parentId = Number(info.node.dataRef.id)
    },
    // 部门下拉框选择事件
    depChanged(value, info) {
      console.log(value) // 选中的值
      console.log(info.data.props) // 选中的下拉json
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.$refs.auditTree.refreshTree()
      this.key = this.key + 1
    },
    // 删除回调
    onRecordsDeleted() {
      this.key = this.key + 1
    },
    validator(rule, value, callback) {
      debounce(() => {
        axios
          .get(
            `api/xcoa-mobile/v1/businesstype-manage/categories/check-code?categoryCode=${value}&id=${this.$refs.dataTable
              .getDetailModal()
              .getFieldValue('id') || ''}`
          )
          .then((res) => {
            if (res?.data?.status === 'success') {
              callback()
            } else {
              callback('已存在分类编码，不可以重复')
            }
          })
      }, 500)()
    },
  },
}
</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>
