1. 程式人生 > >element ui tree 高亮預設顯示,this.$nextTick(() => { this.$refs.tree.setCurrentKey(value);}

element ui tree 高亮預設顯示,this.$nextTick(() => { this.$refs.tree.setCurrentKey(value);}

 <!-- Unit.vue -->
<template>
  <div>
    <div class="container">
      <el-row :gutter="20">
        <!-- 左側內容 -->
        <el-col :span="6">
          <el-card class="height">
            <!-- 單位組樹 -->
            <el-row :span="24">
              <el-col>
                <el-tabs v-model="activeName" @tab-click="handleClick" :stretch="stretchable">
                  <el-tab-pane label="內部單位" name="first"></el-tab-pane>
                  <el-tab-pane label="外部單位" name="second"></el-tab-pane>
                </el-tabs>
                <el-row class="btn" :span="24">
                  <el-col :span="8">
                    <el-button type="primary" @click="add">新增</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button plain :disabled="editDisabled" @click="edit">編輯</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button plain :disabled="editDisabled" @click="deletes">刪除</el-button>
                  </el-col>
                </el-row>
                <!-- 單位組樹列表 -->
                <el-tree ref="tree" :data="roleGroupData" :default-expanded-keys="keys" :default-checked-keys="key" @node-expand="changeNode" node-key="id" :props="defaultProps" @node-click="handleNodeClick" :highlight-current="highlight" accordion></el-tree>
                <!-- 新建單位彈框 -->
                <!-- 新建單位彈框 -->
                <el-dialog :title="title" :visible.sync="dialog.dialogFormVisible" :width="DIALOG.width" :id="fileId" :before-close="cancel">
                  <!-- 新增單位 -->
                  <el-form label-width="80px" :model="formLabelAlign" ref="formLabelAlign" :rules="addUnitRules">
                    <el-form-item label="單位名稱" prop="unitName">
                      <el-input v-model.trim="formLabelAlign.unitName"></el-input>
                    </el-form-item>
                    <el-form-item label="單位編碼" prop="unitCode">
                      <el-input v-model.trim="formLabelAlign.unitCode"></el-input>
                    </el-form-item>
                    <el-form-item label="單位屬性" prop="type">
                      <el-input v-model="type" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="上級單位" prop="parentName">
                      <el-input v-model="formLabelAlign.parentName" disabled></el-input>
                    </el-form-item>
                    <el-form-item class="dialogConfirm">
                      <el-button type="primary" @click="save('formLabelAlign')">確認</el-button>
                      <el-button @click="cancel">取消</el-button>
                    </el-form-item>
                  </el-form>
                </el-dialog>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <!-- 右側內容 -->
        <el-col :span="18">
          <el-card class="height">
            <el-form :inline="true" :label-position="labelPosition" ref="searchForm" :model="searchForm" label-width="80px" class="topSearchForm" :rules="searchFormRule">
              <el-form-item label="使用者姓名" prop="param.userFullname">
                <el-input v-model.trim="searchForm.param.userFullname" placeholder="請輸入使用者姓名"></el-input>
              </el-form-item>
              <el-form-item label="使用者賬號" prop="param.accountCode">
                <el-input v-model.trim="searchForm.param.accountCode" placeholder="請輸入使用者名稱/手機號碼/郵箱地址" style="min-width:260px"></el-input>
              </el-form-item>
              <el-form-item label="" class="queryReset">
                <el-button type="primary" @click="toView('searchForm')">查詢</el-button>
                <el-button @click="reset('searchForm')">重置</el-button>
              </el-form-item>
              <div class="clearfix"></div>
            </el-form>
            <div>
              <el-row class="btnGroup">
                <el-col :span="24">
                  <el-button type="primary" :disabled="addDisabledUser" @click="addList">新增</el-button>
                  <el-button @click="remove" :disabled="removeRole">刪除</el-button>
                </el-col>
              </el-row>
              <!-- 單位列表 -->
              <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="userFullname" label="使用者姓名">
                  <template slot-scope="scope">{{ scope.row.userFullname }}</template>
                </el-table-column>
                <el-table-column prop="unitName" label="所屬單位">
                  <template slot-scope="scope">{{ scope.row.units[0].unit.unitName }}</template>
                </el-table-column>
                <el-table-column prop="userName" label="使用者名稱">
                  <template slot-scope="scope">{{ scope.row.userName }}</template>
                </el-table-column>
                <el-table-column prop="userMobile" label="手機號碼">
                  <template slot-scope="scope">{{ scope.row.userMobile | conceal }}</template>
                </el-table-column>
                <el-table-column prop="userEmail" label="郵箱地址">
                  <template slot-scope="scope">{{ scope.row.userEmail }}</template>
                </el-table-column>
              </el-table>
              <!-- 分頁 -->
              <div class="page">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="PAGE_CONFIG.pageNum" :page-sizes="PAGE_CONFIG.sizes" :page-size="PAGE_CONFIG.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="PAGE_CONFIG.total" v-if="PAGE_CONFIG.total>0"></el-pagination>
              </div>
              <!-- 新增關聯 -->
              <AddcontentVue ref="addContent" :dialogFormContent="dialog.dialogFormContent" :unitType="unitType" @updataContent="changeContent" @updataTable="changeTablie" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import '@/assets/styles/identity.styl'
import { IDENTITY_CLIENT, PAGE_CONFIG, DIALOG } from '@/utils/identity/constants'
// import { getErrorMessage } from '@/utils/i18n'
import { Message } from 'element-ui'
import { getMessagesFromError } from '@/utils/i18n'
import AddcontentVue from './components/AddContent'
import gql from 'graphql-tag'
export default {
  components: {
    AddcontentVue
  },

  filters: {
    // 隱藏手機號中間四位
    conceal: function (value) {
      if (value) {
        return (value = value.substr(0, 3) + '****' + value.substr(7))
      } else {
        return (value = '')
      }
    }
  },
  // props: {},

  data () {
    return {
      fileId: this.id || 'vue-filesone-' + +new Date() + +Math.random(),
      PAGE_CONFIG,
      DIALOG,
      activeName: 'first',
      unitType: '2',
      parentName: '',
      groupData: [],
      stretchable: true,
      getCurrentItem: {},
      editDisabled: true,
      // addDisabledUser: true,
      // 左側屬性單位列表
      roleGroupData: [],
      defaultProps: {
        children: 'children',
        label: 'unitName'
      },
      tabPosition: 'top',
      labelPosition: 'left',
      multipleSelection: [],
      // 編輯,新增必填
      addUnitRules: {
        unitName: [{ required: true, message: '請輸入名稱', trigger: 'blur' }],
        unitCode: [{ required: true, message: '請選擇編碼', trigger: 'blur' }]
      },
      // 左側新增,編輯單位表單
      formLabelAlign: {
        id: '',
        unitName: '',
        unitCode: '',
        parentId: '',
        parentName: '組織機構'
      },
      // 彈出框標題
      title: '',
      // 右側查詢單位下單位列表
      searchForm: {
        pageNum: PAGE_CONFIG.pageNum,
        pageSize: PAGE_CONFIG.pageSize,
        param: {
          unitId: '',
          userType: '2',
          accountCode: '',
          userFullname: ''
        }
      },
      searchFormRule: {},
      // 右側單位陣列
      tableData: [],
      // 彈框關閉刪除
      dialog: {
        dialogFormVisible: false,
        dialogFormContent: false
      },
      keys: [],
      key: [],
      highlight: true,
      nodeKey: ''
    }
  },
  computed: {
    // 多選刪除是否能用
    removeRole () {
      return this.multipleSelection.length === 0
    },
    // 判斷單位屬性
    type () {
      return this.activeName === 'second' ? '外部單位' : '內部單位'
    },
    addDisabledUser () {
      return !this.getCurrentItem.children || (this.getCurrentItem.children.length > 0)
    }
  },

  // created () {},

  mounted () {
    this.getUnitList(this.unitType)
  },

  methods: {
    addList () {
      this.dialog.dialogFormContent = true
      this.$refs.addContent.searchUserList()
    },
    //  獲取單位列表
    searchUserList () {
      this.$apollo
        .query({
          query: gql`
            query users ($unitUserInput:UnitUserInput, $pageInput:PageInput) {
              users (unitUserInput:$unitUserInput, pageInput:$pageInput) {
                total
                list {
                  id
                  userSex
                  userName
                  userFullname
                  userMobile
                  userEmail
                  units {
                    unit {
                      unitName
                    }
                  }
                }
              }
            }
          `,
          fetchPolicy: 'network-only',
          variables: {
            unitUserInput: {
              userFullname: this.searchForm.param.userFullname,
              accountCode: this.searchForm.param.accountCode,
              userType: this.searchForm.param.userType,
              unitId: this.searchForm.param.unitId
            },
            pageInput: {
              pageNum: this.searchForm.pageNum,
              pageSize: this.searchForm.pageSize
            }
          },
          client: IDENTITY_CLIENT
        })
        .then(res => {
          if (res.data.users) {
            this.tableData = JSON.parse(JSON.stringify(res.data.users.list))
            this.PAGE_CONFIG.total = res.data.users.total
          }
        })
        .catch(err => {
          Message.error(getMessagesFromError(err).join(';'))
        })
    },
    // 點選切換內部使用者外部使用者
    handleClick (tab, event) {
      // 1代表外部,2代表內部
      // this.addDisabledUser = true
      this.getCurrentItem = {}
      if (tab.name === 'first') {
        this.unitType = '2'
        this.getUnitList(this.unitType)
      } else {
        this.unitType = '1'
        this.getUnitList(this.unitType)
      }
      this.searchForm.param.userType = this.unitType
    },
    // 根據type查詢內部機構單位
    getUnitList (type) {
      this.$apollo
        .query({
          query: gql`
            query units ($unitType:String){
              units (unitType: $unitType) {
                id
                parentId
                unitName
                unitCode
                children {
                  id
                  parentId
                  unitName
                  unitCode
                  children {
                    id
                    parentId
                    unitName
                    unitCode
                    children {
                      id
                      parentId
                      unitName
                      unitCode
                      children {
                        id
                        parentId
                        unitName
                        unitCode
                      }
                    }
                  }
                }
              }
            }`,
          fetchPolicy: 'network-only',
          variables: {
            unitType: type
          },
          client: IDENTITY_CLIENT
        }).then(res => {
          if (res.data.units.length) {
            let form = {}
            this.$set(form, 'unitName', '組織機構')
            this.$set(form, 'children', JSON.parse(JSON.stringify(res.data.units)))
            this.roleGroupData = []
            this.roleGroupData.push(form)
            // 暫時保留
            // this.$store.commit('SET_ID', this.roleGroupData[0].id)
            this.$store.commit('SET_ID', this.roleGroupData[0].children[0].id)
            this.keys = []
            this.keys.push(this.roleGroupData[0].children[0].id)
            this.key = []
            this.key.push(this.roleGroupData[0].children[0].id)
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.roleGroupData[0].children[0].id)
            })
            this.searchForm.param.unitId = this.roleGroupData[0].children[0] ? this.roleGroupData[0].children[0].id : ''
            this.searchUserList()
            this.groupData = JSON.parse(JSON.stringify(res.data.units))
            this.groupData.push({ unitName: '組織機構', id: 'ae60506073b14983868c8b752914f027' })
            this.groupData.push({ unitName: '組織機構', id: '1c0acfadb4fa4939b3a25330589de332' })
          }
        }).catch(err => {
          Message.error(getMessagesFromError(err).join(';'))
        })
    },
    // 單位樹點選事件
    handleNodeClick (data, node) {
      this.getCurrentItem = {}
      this.formLabelAlign.parentId = ''
      this.formLabelAlign.parentName = ''
      // 判斷點選結構組織中是不是有id 不呼叫介面
      if (data.id) {
        if (data.parentId) {
          this.editDisabled = false
        } else {
          // 一級組織機構不可編輯,刪除
          this.editDisabled = true
        }
        this.getCurrentItem = data
        this.searchForm.param.unitId = data.id
        this.$store.commit('SET_ID', data.id)
        this.searchUserList()
      }
    },
    // 獲取單位下的使用者列表
    // 關閉彈框事件
    closeDialogHandle () {
      this.dialog.dialogFormVisible = false
    },
    // 展開事件
    changeNode () {
    },
    // 資料庫刪除
    // 刪除
    deleteUnit () {
      this.$apollo
        .mutate({
          mutation: gql`mutation deleteUnit ($id:ID!){
            deleteUnit (id: $id)
          }
          `,
          variables: {
            id: this.getCurrentItem.id
          },
          client: IDENTITY_CLIENT
        })
        .then(res => {
          if (res.data.deleteUnit) {
            this.$message({
              type: 'success',
              message: '刪除成功!'
            })
            this.getUnitList(this.unitType)
            this.editDisabled = true
            this.getCurrentItem = {}
          }
        })
        .catch(err => {
          Message.error(getMessagesFromError(err).join(';'))
        })
    },
    // 刪除事件
    deletes () {
      if (this.getCurrentItem.hasOwnProperty('children')) {
        if (this.tableData.length === 0) {
          this.$confirm('此操作將永久刪除記錄, 是否繼續?', '提示', {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 一級 無二級
            this.roleGroupData = this.roleGroupData.filter(
              item => item.id !== this.getCurrentItem.id
            )
            this.deleteUnit()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消刪除'
            })
          })
        } else {
          this.$message.error('該單位下有使用者,不可刪除')
        }
      } else {
        // 二級
        if (this.tableData.length === 0) {
          this.$confirm('此操作將永久刪除記錄, 是否繼續?', '提示', {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              // 一級 無二級
              this.deleteUnit()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消刪除'
              })
            })
        } else {
          this.$message.error('該單位下有子單位,不可刪除')
        }
      }
    },
    // 新增單位
    add () {
      this.dialog.dialogFormVisible = true
      this.title = '新增單位'
      this.formLabelAlign.id = ''
      this.formLabelAlign.unitName = ''
      this.formLabelAlign.unitCode = ''
      if (this.getCurrentItem.parentId) {
        this.formLabelAlign.parentId = this.getCurrentItem.id
        this.formLabelAlign.parentName = this.getCurrentItem.unitName
      } else {
        this.formLabelAlign.parentName = '組織機構'
      }
    },
    saveParentName (arr) {
      // var self = this
      arr.forEach(item => {
        if (item.id === this.getCurrentItem.parentId) {
          this.formLabelAlign.parentName = item.unitName
        } else {
          if (item.hasOwnProperty('children') && item.children.length !== 0) {
            this.saveParentName(item.children)
          }
        }
      })
    },
    // 編輯單位
    edit () {
      this.title = '編輯單位'
      this.dialog.dialogFormVisible = true
      this.formLabelAlign.id = this.getCurrentItem.id
      this.formLabelAlign.unitCode = this.getCurrentItem.unitCode
      this.formLabelAlign.unitName = this.getCurrentItem.unitName
      // fu 賦值parentId
      this.formLabelAlign.parentId = this.getCurrentItem.parentId
      if (this.getCurrentItem.parentId) {
        this.saveParentName(this.groupData)
      }
    },
    // 列表查詢
    toView (searchForm) {
      this.$refs[searchForm].validate((valid) => {
        if (valid) {
          this.searchForm.pageNum = '1'
          this.searchForm.pageSize = '10'
          this.searchUserList()
        } else {
          return false
        }
      })
    },
    // 取消
    cancel () {
      this.dialog.dialogFormVisible = false
      this.$refs['formLabelAlign'].clearValidate()
    },
    // 重置
    reset (formData) {
      this.$refs[formData].resetFields()
      this.dialog.dialogFormVisible = false
    },
    // table多選
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 接收返回值
    changeContent () {
      this.dialog.dialogFormContent = false
    },
    changeTablie () {
      this.dialog.dialogFormContent = false
      this.searchUserList()
    },
    // 刪除
    remove () {
      let arr = this.multipleSelection.map(value => {
        return value.id
      })
      this.$confirm('此操作將永久刪除記錄, 是否繼續?', '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$apollo
          .mutate({
            mutation: gql`mutation deleteUnitUser($unitId:ID, $userIds:[ID!]){
              deleteUnitUser(unitId: $unitId, userIds: $userIds)
            }`,
            variables: {
              unitId: this.searchForm.param.unitId,
              userIds: arr
            },
            client: IDENTITY_CLIENT
          })
          .then(res => {
            if (res.data.deleteUnitUser) {
              this.$message({
                message: '刪除成功',
                type: 'success'
              })
              this.multipleSelection = []
              this.searchUserList()
            }
          })
          .catch(err => {
            Message.error(getMessagesFromError(err).join(';'))
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消刪除'
        })
      })
    },
    // 編輯新增單位提交事件
    save (ruleForm) {
      // console.log(this.formLabelAlign)
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          this.$apollo
            .mutate({
              mutation: gql`mutation saveUnit($id:ID, $unit:UnitInput){
                saveUnit (id:$id, unit:$unit) {
                  id
                }
              }`,
              variables: {
                id: this.formLabelAlign.id,
                unit: {
                  unitType: this.unitType,
                  parentId: this.formLabelAlign.parentId,
                  unitName: this.formLabelAlign.unitName,
                  unitCode: this.formLabelAlign.unitCode
                }
              },
              client: IDENTITY_CLIENT
            })
            .then(res => {
              if (this.formLabelAlign.id) {
                if (res.data.saveUnit.id) {
                  this.$message({
                    message: '更新成功',
                    type: 'success'
                  })
                } else {
                  this.$message.error('更新失敗')
                }
              } else {
                if (res.data.saveUnit.id) {
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  })
                } else {
                  this.$message.error('新增失敗')
                }
              }
              this.$refs[ruleForm].resetFields()
              this.dialog.dialogFormVisible = false
              this.getCurrentItem = {}
              this.editDisabled = true
              this.getUnitList(this.unitType)
            })
            .catch(err => {
              Message.error(getMessagesFromError(err).join(';'))
            })
        } else {
          return false
        }
      })
    },
    // 一頁幾條查詢事件
    handleSizeChange (val) {
      this.searchForm.pageSize = val
      this.searchUserList()
    },
    // 第幾頁查詢事件
    handleCurrentChange (val) {
      this.searchForm.pageNum = val
      this.searchUserList()
    }
  }
}

</script>
<style lang='stylus'  rel='stylesheet/stylus' scoped>
.btn
  margin-bottom 20px
  .listBtn
    float right
</style>