<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <AuditArchivesListTree
        :key="key"
        :checkable="checkable"
        :draggable="draggable"
        :is-search="isSearch"
        :show-line="showLine"
        :selected-keys="defaultSelectedKeys"
        :top-node-text="topNodeText"
        :treeparams="treeparams"
        :default-expanded-keys="defaultSelectedKeys"
        :is-select-dep="isSelectDep"
        :dep-options="depOptions"
        @treeSelect="treeSelect"
        @depChanged="depChanged"
      ></AuditArchivesListTree>
      <div :class="$style.rightcard">
        <a-card :class="$style.acard">
          <sd-data-table-ex
            :key="key"
            ref="dataTable"
            :data-url="_computedDataUrl"
            :process-req="processReq"
            :form-id="formId"
            :page-id="pageId"
            :columns="columns"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            :actions="actions"
            :search-fields="searchFields"
            :filter-expressions="expressions"
            @onChange="onChange"
            @recordSaved="onRecordSaved"
            @recordsDeleted="onRecordsDeleted"
          >
            <!-- 点击列插槽 -->
            <template slot="customCell" slot-scope="text, record">
              <slot name="customCell" :text="text" :record="record"></slot>
            </template>

            <template slot="islink" slot-scope="text, record">
              <a :title="text" @click="rowClick(record)">{{ text }}</a>
            </template>
            <!-- 详情表单 -->
            <template v-slot:form="{ model }" @saved="onRecordSaved">
              <slot :model="model" :parentId="parentId"></slot>
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import AuditArchivesListTree from './audit-archives-list-tree.vue'
import components from './_import-components/audit-archives-tree-import'

export default {
  name: 'AuditArchivesTree',
  metaInfo: {
    title: 'AuditArchivesTree',
  },
  components: {
    ...components,
    AuditArchivesListTree,
  },
  props: {
    // table展示列
    columns: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 按钮信息
    actions: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 默认选中节点
    selectedKeys: {
      type: Array,
      default: function() {
        return []
      },
    },
    // 是否开启搜索
    isSearch: {
      type: Boolean,
      default: false,
    },
    // 是否显示复选框
    checkable: {
      type: Boolean,
      default: false,
    },
    // 是否可以拖拽
    draggable: {
      type: Boolean,
      default: false,
    },
    // 是否显示连线
    showLine: {
      type: Boolean,
      default: false,
    },
    // 根节点名称
    topNodeText: {
      type: String,
      default: '案卷信息',
    },
    // 地址树接口数据源
    treeparams: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 默认展开节点id
    defaultExpandedKeys: {
      type: Array,
      default: () => {
        return ['0']
      },
    },
    // 是否显示部门选择下拉框
    isSelectDep: {
      type: Boolean,
      default: false,
    },
    // 部门下拉框列表值
    depOptions: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 部门下拉框默认值
    defaultDepValue: {
      type: Array,
      default: () => {
        return []
      },
    },
    // table搜索key
    searchFields: {
      type: Array,
      default: () => {
        return []
      },
    },
    // table formID
    formId: {
      type: String,
      default: '',
    },
    // table pageId
    pageId: {
      type: String,
      default: '',
    },
    change: {
      type: Function,
      defult: null,
    },
    code: {
      type: String,
      default: '',
    },
    status: {
      type: String,
      default: null,
    },
    fromflag: {
      type: String,
      default: null,
    },
    userinfoname: {
      type: String,
      default: null,
    },
    archivesType: {
      type: String,
      default: null,
    },
    /**
     * 主表ID
     */
    recordId: {
      type: Number,
      default: 0,
    },
    dossierId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      key: 0,
      treeData: [],
      parentId: 0,
      parentName: '业务类型',
      parentObj: [{ id: '0', name: '业务类型' }],
      defaultSelectedKeys: ['0'],
      pageSize: 10, // 分页数量
      startPosition: 0, // 分页起始数
      expressions: [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: 0,
        },
        {
          dataType: 'str',
          name: 'code',
          op: 'eq',
          stringValue: null,
        },
      ],
    }
  },
  computed: {
    _computedDataUrl() {
      const dossierId = this.dossierId
      let archivesId = this.$route.query.record
      if (archivesId === undefined) {
        archivesId = this.recordId
      }
      const parentId = this.parentId
      if (dossierId === undefined && parentId !== 0 && archivesId !== undefined) {
        const dataurl =
          'api/xcoa-mobile/v1/iamdossierdata/factor-list?archivesId=' +
          archivesId +
          '&parentId=' +
          parentId
        return dataurl
      } else if (dossierId !== undefined && parentId !== 0 && archivesId !== undefined) {
        const dataurl =
          'api/xcoa-mobile/v1/iamdossierdata/factor-list?dossierId=' +
          dossierId +
          '&archivesId=' +
          archivesId +
          '&parentId=' +
          parentId
        return dataurl
      } else if (dossierId === undefined && archivesId === undefined) {
        const dataurl = 'api/xcoa-mobile/v1/iamdossierdata/factor-list?parentId=' + 0
        return dataurl
      } else {
        const dataurl = 'api/xcoa-mobile/v1/iamdossierdata/factor-list?parentId=' + parentId
        return dataurl
      }
    },
  },
  methods: {
    rowClick(record) {
      let archivesId = this.$route.query.record
      if (archivesId === undefined) {
        archivesId = this.recordId
      }
      const parentId = this.parentId
      const fileState = this.status
      const fromFlag = this.fromflag
      const archivesType = this.archivesType
      const userInfo = getUserInfo()
      const userInfoName = this.userinfoname
      let url = null
      if (
        archivesType === 'SYSTEM_FILE' &&
        record.url !== '' &&
        record.url != null &&
        record.url !== 'undefined'
      ) {
        url = record.url
      } else {
        url =
          '/audit-dossier-form?record=' +
          record.id +
          '&archivesId=' +
          archivesId +
          '&parentId=' +
          parentId +
          '&fileState=' +
          fileState +
          '&fromFlag=' +
          fromFlag +
          '&userInfoName=' +
          userInfo.name
      }
      // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
    refresh() {
      this.$refs.dataTable.refresh()
    },
    // 获取菜单树数据
    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
      })
    },

    // 选择上级分类后给对应的域赋值
    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.startPosition = 0
      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.defaultSelectedKeys = selectedKeys
      this.expressions.forEach((item) => {
        if (item.name === 'parentId') {
          item.stringValue = Number(info.node.dataRef.id)
        }
      })
      this.expressions = [...this.expressions]
      this.defaultSelectedKeys = selectedKeys
      this.parentId = Number(info.node.dataRef.id)
      this.unableselect = info.node.dataRef.unableselect
      if (this.change !== null) {
        this.change(this.unableselect, this.parentId)
      }
    },
    // 部门下拉框选择事件
    depChanged(value, info) {
      // console.log(value) // 选中的值
      // console.log(info.data.props) // 选中的下拉json
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.key = this.key + 1
    },
    // 删除回调
    onRecordsDeleted() {
      this.key = this.key + 1
    },
    // 设置请求内容
    processReq(req) {
      // 获取查询内容
      const searchExp = req.data.expressions.find((item) => {
        return item.dataType === 'exps'
      })
      const searchText = searchExp?.expressionsValue[0]?.stringValue.replaceAll(/%/g, '')
      req.data = {
        configId: this.treeparams.configId,
        parentId: this.parentId,
        key: searchText ?? '',
        maxResults: this.pageSize,
        startPosition: this.startPosition,
      }
      return req
    },
    // 翻页操作
    onChange(pagination, filters, sorter) {
      this.pageSize = pagination.pageSize
      this.startPosition = (pagination.current - 1) * pagination.pageSize
    },
  },
}
</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%;
      .acard {
        min-height: 100%;
      }
    }
  }
}
</style>
