<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <sd-ywlx-tree
        ref="ywlxtree"
        :selected-keys="selectedKeys"
        :is-search="true"
        @treeSelect="treeSelect"
        @initTreeData="afterInitTreeData"
      ></sd-ywlx-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            v-if="showData"
            ref="dataTable"
            form-id="oaBaseBusinessTypeCat"
            page-id="base/businesstype/oaBaseBusinessTypeCat"
            :columns="columns1"
            :show-selection="(item) => isEdit(item)"
            :actions="actions"
            :search-fields="['categoryName']"
            :filter-expressions="computedExpressions"
            @recordSaved="onRecordSaved"
            @recordsDeleted="onRecordsDeleted"
            @formBtnClick="formBtnClick"
          >
            <template slot="categoryName" slot-scope="text, record">
              <a
                v-if="isEdit(record)"
                @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 components from './_import-components/sd-classify-manage-import'
import BusinesstypeService from './businesstype-service'
export default {
  name: 'SdClassifyManage',
  metaInfo: {
    title: '分类管理',
  },
  components,
  data() {
    return {
      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,
        },
        {
          title: '分级机构id',
          dataIndex: 'belongedOrgId',
          sdHidden: true,
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
      ],
      selectedKeys: [],
      parentId: 0,
      parentName: '业务类型',
      parentObj: [{ id: '0', name: '业务类型' }],
      isDocType: '', // 是否公文类
      belongedOrg: undefined,
      showData: false,
    }
  },
  computed: {
    computedExpressions() {
      const expressions = [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: this.parentId,
        },
      ]
      if (this.belongedOrg) {
        expressions.push({
          dataType: 'long',
          name: 'belongedOrgId',
          op: 'eq',
          longValue: Number(this.belongedOrg.id),
        })
      }
      return expressions
    },
  },
  methods: {
    isEdit(record) {
      // 页面上有分级机构时，以页面的分级机构匹配判断；否则以接口返回值中的editAndDeleteAuth判断
      // 原因：页面上有分级时，数据过滤以页面上的选择为准，后端接口判断是否有编辑权限时，比较困难。故改为前端判断
      return this.belongedOrg
        ? Number(record.belongedOrgId) === Number(this.belongedOrg.id)
        : record.editAndDeleteAuth !== 0
    },
    // 获取菜单树数据
    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) {
      const params = {}
      if (this.belongedOrg) {
        params.belongedOrgId = this.belongedOrg.id
      }
      if (id) {
        return BusinesstypeService.getCategoryTree({ ...params, parentId: id }).then((res) => {
          return this.mapCategoryItems(res.data)
        })
      } else {
        return BusinesstypeService.getCategoryTree(params).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', '')
      }
    },
    afterInitTreeData(node, belongedOrg) {
      this.selectedKeys = []
      this.parentName = node.name
      this.parentId = Number(node.id)
      this.parentObj = [{ id: this.parentId, name: this.parentName }]
      this.belongedOrg = belongedOrg
      this.isDocType = ''
      if (!this.showData) {
        this.showData = true
      }
    },
    treeSelect(selectedKeys, info, belongedOrg) {
      this.parentId = Number(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.belongedOrg = belongedOrg
    },
    formBtnClick(evt, btn, { form, recordId }) {
      if (btn.buttonId === 'save') {
        // 新建时的保存
        if (!recordId && this.belongedOrg) {
          form.setFieldValue('belongedOrgId', this.belongedOrg.id)
        }
      }
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.$refs.ywlxtree.refresh()
    },
    // 删除回调
    onRecordsDeleted() {
      this.$refs.ywlxtree.refresh()
    },
    validator(rule, value, callback) {
      debounce(() => {
        axios
          .get(
            `api/framework/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%;
      :global(.ant-card) {
        min-height: 100%;
      }
    }
  }
}
</style>
