<!-- 资料库 -->
<template>
  <div class="app-container"     v-loading="adjustCatalogLoading"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="sidebar" v-clickoutside="adjustCatalogLoading && closeMask">

      <v-jstree ref="tree" :data="data" :item-events="itemEvents" style="width:1000px">

        <template slot-scope="_">
          <div style="display: inherit; width: 200px"
               @dblclick="itemDblClick(_.vm, $event)"
               @click.ctrl="itemCtrlClick(_.vm, $event)"
               @click.exact="itemClick(_.vm, $event)"
               @contextmenu.prevent="onContextmenu(_.vm, $event)"
          >
            <i v-if="!_.model.loading" :class="_.vm.themeIconClasses" role="presentation"></i>
            {{ _.model.text }}
            <!--
                       <button style="border: 0px; background-color: transparent; cursor: pointer;" @click="customItemClick(_.vm, _.model, $event)"><i class="fa fa-remove"></i></button>

            -->
          </div>
        </template>

      </v-jstree>
    </div>

    <div class="content">

      <card-table ref="fileTable" class="custom-table-database" :del-prop="['createTime']" :loading="loading" :modalData="databaseList" :searchParams="queryParams"
                  :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery" @pagination="getList"
                  @resetList="resetQuery" @selection-change="handleSelectionChange"
      >
<!--        <template #operations="{selections}">-->
<!--          <el-button v-hasPermi="['train:database:add']" icon="el-icon-upload2" plain size="mini" type="primary"-->
<!--                     @click="handleUpload"-->
<!--          >{{ $t('import.upload') }}-->
<!--          </el-button>-->
<!--          <el-button  v-hasPermi="['train:database:visibleRange']" icon="el-icon-setting" plain size="mini" type="primary"-->
<!--                     @click="handleVisibleRange(1)"-->
<!--          >{{ $t('database.setVisibleRange') }}-->
<!--          </el-button>-->
<!--        </template>-->

        <template #default="{ list }">
          <el-table-column type="selection" width="50" align="center" class-name="no-header"></el-table-column>
          <el-table-column align="center" label="No" type="index" width="50"/>
          <!--文件名-->
          <Column :label="$t('database.fileName')" :show-overflow-tooltip="true" prop="fileName" width="250" show-search :search-params="queryParams">
            <template #default="{ row }">
              <el-link :underline="false" :href="`${baseUrl}${row.filePath}`" target="_blank">{{ row.fileName }}</el-link>
            </template>
          </Column>
          <!--文件类型-->
          <Column :label="$t('database.fileType')" :show-overflow-tooltip="true" prop="fileTypes" show-search search-type="select"
                  :search-dict="fileTypeOps" value-prop="fileType" label-prop="fileType" :search-params="queryParams" select-more>
            <template #default="{ row }">
              <span>{{ row.fileType }}</span>
            </template>
          </Column>
          <!--可见范围-->
          <Column :label="$t('database.visibleRange')" :show-overflow-tooltip="true" prop="visibleRangeNames" width="250">
            <template #default="{ row }">
              <span>{{ row.visibleRange1Names + ' | ' + row.visibleRange2Names }}</span>
            </template>
          </Column>
          <!--创建时间-->
          <Column :label="$t('common.createTime')" :show-overflow-tooltip="true" prop="createTime"/>
          <!--创建人-->
          <Column :label="$t('common.createBy')" :show-overflow-tooltip="true" prop="createByName"/>
          <!--更新时间-->
          <Column :label="$t('common.updateTime')" :show-overflow-tooltip="true" prop="updateTime"/>
          <!--更新人-->
          <Column :label="$t('common.updateBy')" :show-overflow-tooltip="true" prop="updateByName"/>
          <!--简介-->
          <Column :label="$t('database.briefIntroduction')" :show-overflow-tooltip="true" prop="briefIntroduction"/>
          <!--操作-->
          <Column :label="$t('common.operate')" :min-width="200" :showSearch="true" align="center" fixed="right"
                  search-type="operate"
          >
            <template #default="{ row }">
              <!--查看-->
              <el-button v-hasPermi="['train:database:edit']" icon="el-icon-edit" size="mini" type="text"
                         @click="handleView(row)"
              >{{ $t('common.view') }}
              </el-button>

<!--              <el-dropdown v-hasPermi="['train:database:catalog', 'train:database:remove']" size="mini"-->
<!--                           @command="(command) => handleCommand(command, row)"-->
<!--              >-->
<!--                <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>-->

<!--                <el-dropdown-menu slot="dropdown">-->
<!--                  &lt;!&ndash;修改&ndash;&gt;-->
<!--                  <el-dropdown-item v-hasPermi="['train:database:catalog']" command="handleCatalog"-->
<!--                                    icon="el-icon-edit"-->
<!--                  >{{ $t('database.adjustDir') }}-->
<!--                  </el-dropdown-item>-->
<!--                  &lt;!&ndash;删除&ndash;&gt;-->
<!--                  <el-dropdown-item v-hasPermi="['train:database:remove']" command="handleDelete"-->
<!--                                    icon="el-icon-delete"-->
<!--                  >{{ $t('common.delete') }}-->
<!--                  </el-dropdown-item>-->
<!--                </el-dropdown-menu>-->
<!--              </el-dropdown>-->

            </template>
          </Column>

        </template>

      </card-table>
    </div>

    <!-- 添加或修改资料库对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="40vw" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上传" prop="remark">
          <FileUpload v-model="form.fileList" :buttonText="$t('common.uploadFile')" :class="{ 'upload': false }"
                      :controllerUrl="controllerUrl" :disabled="disabled"
                      :fileSize="500" :fileType="fileType" :isShowTip="false"
          >
          </FileUpload>
        </el-form-item>

        <!--简介-->
        <Input :label="$t('database.briefIntroduction')" prop="briefIntroduction" v-model="form.briefIntroduction"
               type="textarea" :disabled="disabled" :maxlength="2000"/>


        <!--<el-form-item label="简介" prop="briefIntroduction">-->
        <!--  <el-input v-model="form.briefIntroduction" placeholder="briefIntroduction" type="textarea"/>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!disabled" type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="visibleTitle" :visible.sync="visibleRangeOpen" append-to-body width="30vw" :close-on-click-modal="false">
      <div v-loading="rangeLoading">
      <!--<el-form ref="form" :model="visibleRangeForm" label-width="80px">-->
      <!--    <el-form-item :label="$t('user.area')" prop="areaIdList">-->
      <!--      <treeselect v-model="form.areaIdList" :options="areaTree" :show-count="true" multiple flat-->
      <!--                  :placeholder="$t('user.placeholder_area')"/>-->
      <!--    </el-form-item>-->


      <!--  <el-form-item :label="$t('user.role')" prop="roleIds">-->
      <!--    <el-select v-model="form.roleIds" multiple :placeholder="$t('user.placeholder_role')" class="w-100">-->
      <!--      <el-option-->
      <!--        v-for="item in roles"-->
      <!--        :key="item.roleId"-->
      <!--        :label="item.roleName"-->
      <!--        :value="item.roleId"-->
      <!--        :disabled="item.status == 1"-->
      <!--      ></el-option>-->
      <!--    </el-select>-->
      <!--  </el-form-item>-->
      <!--</el-form>-->

        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item :title="$t('user.area')" name="1">

            <!--<treeselect v-model="form.areaIdList" :options="areaTree" :show-count="true" multiple flat-->
            <!--            :placeholder="$t('user.placeholder_area')"/>-->

            <el-tree
              :data="areaTree" check-strictly ref="areaTree"
              show-checkbox highlight-current default-expand-all check-on-click-node :expand-on-click-node="false"
              node-key="id"
            >
            </el-tree>
          </el-collapse-item>
          <el-collapse-item :title="$t('user.role')" name="2">
            <el-table ref="roleTable" :data="roles" highlight-current-row @current-change="handleCurrentChange"
                      @selection-change="handleRoleSelectionChange"
                      style="width: 100%">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column type="index" width="50"> </el-table-column>
              <el-table-column  property="roleName" :label="$t('database.roleName')">
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>

      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibleSubmitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="visibleCancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addDatabase,
  createDirectory,
  delDatabase,
  delDirectoryAndData,
  getDatabase, getDatabaseType,
  getDirectoryTree,
  listDatabase,
  updateDatabase, visibleRange
} from '@/api/train/database'
import VJstree from 'vue-jstree'
import FileUpload from '@/components/FileUpload/index.vue'

import Clickoutside from 'element-ui/src/utils/clickoutside'
import Treeselect from '@riophae/vue-treeselect'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getAreaTree, getUser } from '@/api/system/user'
import CardTable from '@/components/element/table/CardTable.vue'
import { delLead } from '@/api/business/crm/lead'

const RootNodeValue = 'Root'

export default {
  name: 'DatabaseDialog',
  components: {
    CardTable,
    Treeselect,
    VJstree, FileUpload
  },
  directives: { Clickoutside },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      adjustCatalogLoading: false,
      // 遮罩是否可关闭
      maskClosable: true,
      adjustFileId: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 资料库表格数据
      databaseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileType: null,
        directoryId: null,
        visibleRange1: null,
        visibleRange2: null,
        visibleRange3: null,
        briefIntroduction: null,

        curNodeId: null
      },
      // 表单参数
      form: {},
      fileType: ['jpg', 'png', 'jpeg', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'pdf'],
      // 表单校验
      rules: {},
      controllerUrl: '',

      fileIdx: 0,
      filesToAdd: 1,
      folderIdx: 3,
      searchText: '',
      editingItem: {},
      editingNode: null,
      itemEvents: {
        mouseover: function() {
          console.log('mouseover')
        }
      },
      data: [],
      time: null,
      disabled: false,


      activeNames: ['1'],
      // 0: 设置文件可见范围; 1: 设置目录可见范围
      visibleType: 0,
      visibleTitle: '',
      visibleRangeOpen: false,
      visibleRangeForm: {
        visibleRange1: null,
        visibleRange2: null,
        visibleRange3: null
      },
      rangeLoading: false,

      areaTree: [],
      roles: [],

      // 选中角色
      roleSelection: [],
      // 选中区域
      // areaSelection: [],

      // 文件类型 下拉
      fileTypeOps: [],
      // 选择的文件数据
      selectionList:[],
    }
  },

  computed: {
    // 当前选中区域集合
    areaSelection() {
      return this.$refs.areaTree.getCheckedNodes()
    },

    // 当前选中区域id集合
    areaSelectionIds() {
      return this.$refs.areaTree.getCheckedKeys()
    },

    treeSelection() {
      return this.getTreeCheckedNodes();
    }
  },

  created() {
    this.getDirectoryTree()
    this.getList()
    this.getDatabaseType()

    window.addEventListener('keydown', this.keyDownListener)
  },

  destroyed() {
    window.removeEventListener('keydown', this.keyDownListener)
  },

  methods: {
    rowClick(node, event, isRightClick = false) {
      console.log('event:', event)
      console.log('node:', node)
      // 选中和再次点击取消选中
      if (node === this.editingNode && !isRightClick) {
        node.model.selected = false
        this.editingNode = null
        this.editingItem = {}
      } else {
        this.editingNode = node
        this.editingItem = node.model
        this.deselectNodeChildren(this.$refs.tree)
        node.model.selected = true
      }

      event.stopPropagation()
      this.getList()
    },

    onContextmenu(node, event) {
      if (this.adjustCatalogLoading) return ;

      this.rowClick(node, event, true)

      this.$contextmenu({
        items: [
          {
            label: this.$t('import.upload'),
            onClick: () => {
              this.handleUpload()
            },
            divided: true,
            icon: 'el-icon-upload2'
          },
          // {
          //   label: '调整目录权限',
          //   onClick: () => {
          //     this.handleVisibleRange(2)
          //   },
          //   divided: true,
          //   icon: 'el-icon-setting'
          // },
          {
            label: this.$t('database.addFolder'),
            onClick: () => {
              this.addFolder()
            },
            icon: 'el-icon-folder-add'
          },
          {
            label: this.$t('database.deleteFolder'),
            onClick: () => {
              this.removeNodes()
            },
            icon: 'el-icon-delete'
          }
        ],
        event,
        //x: event.clientX,
        //y: event.clientY,
        customClass: 'custom-class',
        zIndex: 2003,
        minWidth: 50
      })
      return false
    },

    keyDownListener: function(event) {
      if (event.keyCode === 46) //del
      {
        this.removeNodes()
      }
    },
    // 单击
    itemClick(node, event) {

      const that = this
      // 开启延时器，300ms的间隔区分单击和双击，解决双击时执行两次单击事件
      clearTimeout(that.time)
      that.time = setTimeout(async() => {
        console.log('单击')

        if (that.adjustCatalogLoading) {
          // 由于使用了element的指令：clickoutside，所以需要设置maskClosable来控制遮罩是否可关闭
          // 防止调整确认时，遮罩关闭
          that.maskClosable = false
          // 先取消之前选中的（点击调整目录之前的选中和此时的选中应该隔离开）
          this.editingItem.selected = false
          // 是否确认调整目录
          try {
            await this.$modal.confirm(this.$t('database.confirmAdjustToHere'))

            const response = await this.adjustCatalog(node.model.value)
            this.$modal.msgSuccess(this.$t('database.setupSuccess'))
            this.adjustCatalogLoading = false
            this.getList()
          } finally {
            // 允许遮罩关闭
            that.maskClosable = true
            // 取消调整目录的选中
            node.model.selected = false

          }


        } else {
          // 写单击事件执行的逻辑代码
          this.rowClick(node, event)
        }
      }, 300)

    },

    // ctrl + 单击
    itemCtrlClick: function(node, e) {
      console.log('ctrl selected')
      node.model.selected ^= true
      if (node.model.selected) {
        node.model.opened = false
        this.deselectNodeChildren(node)
        node.model.selected = true
      }
      e.stopPropagation()
    },

    // 双击展开当前目录
    itemDblClick(node, event) {

      clearTimeout(this.time)
      console.log('双击')
      this.rowClick(node, event)

      // 双击事件执行的逻辑代码

      // this.rowClick(node, event)
      // 同时关闭所有子目录
      // this.$refs.tree.handleRecursionNodeChilds(node, function(nde) {
      //   nde.model.opened = false
      // })
      node.model.opened = !node.model.opened

      event.stopPropagation()
    },

    deselectNodeChildren(parent) {
      this.$refs.tree.handleRecursionNodeChilds(parent, node => {
        // console.log('node:', node)
        if (node.model !== undefined) {
          // console.log('node.model:', node.model)
          let prevsel = node.model.selected
          node.model.selected = false

//         return true
          return node.model.opened || prevsel
        }
      })
    },

    async adjustCatalog(directoryId) {
      const param = {
        id: this.adjustFileId,
        directoryId: directoryId
      }
      return updateDatabase(param)

    },


    sortBy(attr, rev) {
      if (rev == undefined) {
        rev = 1
      } else {
        rev = (rev) ? 1 : -1
      }
      return function(a, b) {
        let bd = b.isfolder
        if (a.isfolder === bd) {
          a = a[attr]
          b = b[attr]
          if (a < b) {
            return rev * -1
          }
          if (a > b) {
            return rev * 1
          }
          return 0
        } else {
          return (bd === true) ? 1 : -1
        }
      }
    },
    async removeNodes() {
      // let cntrFiles = 0
      let cntrFolders = 0
      this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
        if (node.model !== undefined && node.model.selected && node.model.value !== RootNodeValue) {
          // if (node.model.isfolder === true) {
          this.$refs.tree.handleRecursionNodeChilds(node, fnode => {
            // if (fnode.model.isfolder === true)
            //   cntrFolders++
            // else
            //   cntrFiles++
            cntrFolders++
          })
          return false
          // } else {
          //   cntrFiles++
          // }
        }
      })
      if (cntrFolders === 0) {
        return
      }
      try {
        await this.$modal.confirm(this.$t('database.deleteConfirm', this.editingItem.text))

        if (cntrFolders) {

        }
        await delDirectoryAndData(this.editingItem.value)

        this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
          if (node.model !== undefined && node.model.selected) {
            this.removeNode(node)
            return node.model.opened
          }
        })

        // this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'))
      } catch (error) {
      }

    },
    removeNode(node) {
//    alert("RemoveNode")

      if (node !== undefined) {
        let item = node.model
        if (item.id !== undefined) {
          if (item.value !== RootNodeValue) {
            let index = node.parentItem.indexOf(item)
            node.parentItem.splice(index, 1)
          } else {
            item.selected = false
          }
        }
      }
    },
    addNode: function(node, newItemData, notDeselect) {
      if (this.editingItem.id !== undefined) {
        if (notDeselect === undefined) {
          this.deselectNodeChildren(this.$refs.tree)
        }
        newItemData.selected = true
        let item = node.model
        let parentItem
        if (item.isfolder === true) {
          item.addChild(newItemData)
          item.children.sort(this.sortBy('text', true))
        } else {
          item.addBefore(newItemData, node)
          node.parentItem.sort(this.sortBy('text', true))
        }

      }
    },
    getFileData: function() {
      this.fileIdx += 1
      return {
        text: 'File' + this.fileIdx,
        value: 'File' + this.fileIdx,
//           dropDisabled: true,
        icon: 'fa fa-warning icon-state-danger'
      }
    },
    addFolder() {
      if (this.editingItem.id !== undefined) {

        this.$prompt(this.$t('database.pleaseEnterFolderName'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          inputPattern: /^[^\\/?%*:|"<>]+$/,
          inputErrorMessage: this.$t('database.illegalFolderName')
        }).then(async({ value }) => {
          const param = {
            derectoryName: value,
            superDirectory: this.editingItem.value
          }
          await this.createDirectory(param)
          this.getDirectoryTree()

        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // })
        })
      }
    },

    // 添加文件夹
    async createDirectory(param) {
      const response = await createDirectory(param)
    },

    getDirectoryTree() {
      getDirectoryTree().then(response => {
        this.data = response.data
      })
    },

    /** 查询资料库列表 */
    async getList() {
      this.loading = true
      // const param = {
      //   ...this.queryParams,
      //   // directoryId: this.curFolderId,
      //   directoryId: this.editingItem.value
      // }
      this.queryParams.directoryId = this.editingItem.value
      try {
        const response = await listDatabase(this.queryParams)
        this.databaseList = response.rows
        this.queryParams.total = response.total
      } finally {
        this.loading = false
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fileName: null,
        fileType: null,
        directoryId: null,
        visibleRange1: null,
        visibleRange2: null,
        visibleRange3: null,
        briefIntroduction: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileType: null,
        directoryId: null,
        visibleRange1: null,
        visibleRange2: null,
        visibleRange3: null,
        briefIntroduction: null
      }

      // this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 2];
        this.$refs.fileTable.$refs.table.toggleRowSelection(lastSelected, false);
      }
      // 将当前选择的项添加到选中项数组中
      if (selection.length > 0) {
        this.selectionList = [selection[selection.length - 1]];
      } else {
        this.selectionList = [];
      }
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleCatalog':
          this.handleCatalog(row)
          break
        case 'handleDelete':
          this.handleDelete(row)
          break
        default:
          break
      }
    },

    /** 上传操作 */
    handleUpload() {
      if (!this.editingItem.value) {
        this.$modal.msgError(this.$t('database.selectDir'))
        return
      }
      this.disabled = false
      this.controllerUrl = `/train/database/upload/${this.editingItem.value}`

      this.reset()
      this.open = true

      this.form.fileList = []
      this.title = this.$t('database.addLibrary')
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset()
      const id = row.id || this.ids
      getDatabase(id).then(response => {
        this.form = response.data
        this.form.fileList = this.form.filePath
        this.open = true
        this.title = this.$t('database.viewLibrary')
        this.disabled = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDatabase(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = this.$t('database.editLibrary')
        this.disabled = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDatabase(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.updateSuccess'))
              this.open = false
              this.getList()
            })
          } else {
            this.form.directoryId = this.editingItem.value
            addDatabase(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'))
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm(this.$t('common.isDelete')).then(function() {
        return delDatabase(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'))
      }).catch(() => {
      })
    },

    // 调整目录
    handleCatalog(row) {
      this.adjustCatalogLoading = true
      this.$modal.notify(this.$t('database.clicktoadjust'))
      this.adjustFileId = row.id

    },

    closeMask() {
      console.log('closeMask')
      if (this.maskClosable)
      this.adjustCatalogLoading = false

      if (this.editingItem.value) {
        this.editingItem.selected = true
      }
    },

    handleChange() {

    },

    // 设置可见范围: type=1: 设置文件或者选中目录下所哟文件的可见范围; type=2: 设置目录的可见
    handleVisibleRange(type) {
      this.visibleType = type
      const showModal = () => {
        this.visibleRangeOpen = true;
        this.getAreaTree();
        this.getRole();
      };

      if (type === 1) {
        this.visibleTitle = this.$t('database.setFileVisibleRange')
        // 请选择目录或者勾选文件
        // console.log('this.editingItem::', this.editingItem)
        // console.log('this.ids::', this.ids)
        if (!this.editingItem.value && this.ids.length === 0) {
          this.$modal.msgError(this.$t('database.selectDirOrFile'))
          return
        }
        // 未勾选文件，继续操作将设置当前目录下所有文件
        if (this.ids.length === 0) {
          this.$modal.confirm(this.$t('database.checkDirConfirm')).then(showModal);
        } else {
          showModal();
        }
      } else if (type === 2) {
        if (!this.editingNode) {
          this.$modal.msgError(this.$t('database.selectDir'))
          return
        }
        this.visibleTitle = this.$t('database.setDirVisibleRange')
        showModal()
      }

    },

    async visibleSubmitForm() {
      console.log('roleSelection:', this.roleSelection)
      console.log('areaSelection:', this.areaSelection)
      console.log('areaSelectionIds:', this.areaSelectionIds)
      // 获取tree中所有选中的节点
      console.log('treeSelection:', this.treeSelection)

      this.rangeLoading = true
      const p = {
        type: this.visibleType,
        ids: this.ids,
        directoryIds: this.treeSelection.map(item => item.value),
        // visibleRange1: this.roleSelection.map(item => item.roleId).join(','),
        visibleRange1: this.roleSelection.map(item => item.roleKey).join(','),
        visibleRange2: this.areaSelectionIds.join(','),
      }

      try {
        const response = await visibleRange(p)
        this.$modal.msgSuccess(this.$t('database.setupSuccess'))
        this.visibleRangeOpen = false
        this.getList()

      } finally {
        this.rangeLoading = false
      }

    },

    getTreeCheckedNodes() {
      let checkedNodes = []
      this.$refs.tree.handleRecursionNodeChilds(this.$refs.tree, node => {
        if (node.model !== undefined && node.model.selected) {
          checkedNodes.push(node.model)
        }
      })
      return checkedNodes
    },

    visibleCancel() {
      this.visibleRangeOpen = false
    },

    // 获取地区树
    async getAreaTree() {
      const response = await getAreaTree()
      this.areaTree = response.data;
    },

    getRole() {
      // 当前用户id
      getUser(this.$store.getters.userId).then(response => {
        this.roles = response.roles.filter(item => item.status === '0' && !item.admin)
      });
    },

    handleCurrentChange(val) {
      console.log('行选中', val)

      console.log('areaSelection::', this.areaSelection)
      console.log('areaSelectionIds::', this.areaSelectionIds)


      this.currentRow = val;
      this.toggleSelection([val]);
    },


    toggleSelection(rows) {
      if (rows) {
          rows.forEach(row => {
            this.$refs.roleTable.toggleRowSelection(row);
        })

      } else {
        this.$refs.roleTable.clearSelection();
      }
    },

    handleRoleSelectionChange(val) {
      console.log('role:', val)
      this.roleSelection = val;
    },

    getDatabaseType() {
      getDatabaseType().then(response => {
        this.fileTypeOps = response.data
      })
    },

  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__header-wrapper .el-checkbox{
  display:none
}

.app-container {
  display: flex;

  ::v-deep .el-loading-mask .el-loading-spinner {
    display: none;
  }

  // 目录树容器样式
  .sidebar {
    // loading默认z-index为2000
    z-index: 2001;
    flex: 1;
    //max-height: 80vh;
    overflow: auto;
    padding: 20px 5px;
    margin: 10px;
    // 阴影
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    border-radius: 5px;

    border: 1px solid #146173;
    background-color: #fff;
  }

  .content {
    width: 80%;
    padding: 10px;
  }
}


/* 更多 按钮 样式 start */
@import "@/assets/styles/element-variables";

.el-dropdown-menu {
  padding: 8px 0;

  .el-dropdown-menu__item {
    padding: 0 20px;
    color: $--color-primary;
  }

  .el-dropdown-menu__item + .el-dropdown-menu__item {
    margin-top: 5px;
  }
}

::v-deep .el-dropdown-menu__item i {
  margin-right: 12px !important;
}

/* 更多 按钮 样式 end */
</style>
