<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: 101,
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="false"
        :dep-options="categorys"
        @treeSelect="treeSelect"
      >
      </audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            :key="refreshkey"
            ref="list"
            :editnode="editnode"
            form-id="kpiBusinessCategory"
            page-id="kpi/busicategory/kpiBusinessCategory"
            :columns="columns"
            :actions="actions"
            show-selection
            :filter-expressions="filterExpressions"
            :search-fields="['busiName']"
            @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>
              <a-form-model-item
                prop="busiCode"
                label="分类编号"
                :rules="[
                  { required: true, validator: validator, trigger: 'blur', itemId: model.id },
                ]"
              >
                <a-input v-model.trim="model.busiCode" />
              </a-form-model-item>
              <sd-form-item v-if="initParam(model)" name="busiName"></sd-form-item>
              <sd-form-item name="busiDesc">
                <a-textarea v-model="model.busiDesc" :rows="3" />
              </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 { Modal, Message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import auditTree from '../../components/audit-tree.vue'
import components from './_import-components/kpi-busicategory-list-import'
const columns = [
  {
    title: '序号',
    dataIndex: 'sortNum',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  {
    dataIndex: 'parentId',
    sdHidden: true,
  },
  {
    title: '业务名称',
    dataIndex: 'busiName',
    sdClickable: true,
  },
  {
    title: '业务编号',
    dataIndex: 'busiCode',
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sdRender: TableColumnTypes.date,
  },
]

export default {
  name: 'KpiBusicategoryList',
  metaInfo: {
    title: '指标业务分类',
  },
  components: {
    ...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: 0,
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.ex.create,
          permission: 'create',
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch, // 删除按钮，不需要回调，会自动处理
          permission: null,
          callback: (keys) => {
            this.deleteRows(keys)
          },
        },
      ],
    }
  },
  methods: {
    initParam(model) {
      model.parentId = this.parentId

      if (model.choosePicker && model.choosePicker.length > 0) {
        this.chooseoption = model.choosePicker
      }
      return true
    },
    treeSelect(selectedKeys, info) {
      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/kpi-businesscategory/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)
    },
    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, id: rule.itemId }
      axios({
        method: 'post',
        url: 'api/xcoa-mobile/v1/kpi-businesscategory/checkCode',
        data: parentIdAndCode,
      }).then((res) => {
        if (res.data === false) {
          callback('编码已经存在，不能重复创建')
        } else {
          callback()
        }
      })
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          var ids = selectedRowKeys.join(',')
          axios({
            method: 'get',
            url: 'api/xcoa-mobile/v1/kpi-businesscategory/delete?ids=' + ids,
          })
            .then((res) => {
              if (res.data === true) {
                Message.success('删除成功')
                this.onRecordsDeleted()
                this.$refs.list.clearSelection()
                this.refresh()
              }
            })
            .catch((error) => {
              Message.error({ content: error.response.data.message || '删除失败' })
            })
        },
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.btns {
  position: absolute;
  top: 24px;
  right: 99.5px;
  z-index: 100;
}
.buttonSpacing {
  margin-left: 5px;
}
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
