<template>
  <div class="userManagement branchMana"
    v-loading.body="dialogLoading"
    element-loading-text="拼命加载中">
    <bread-crumb :bread-crumb-list="breadCrumbList"></bread-crumb>
    <div class="con">
      <div class="nav">
        <div class="navBtn">
          <el-button size="mini" type="info" @click="addOrgan" :disabled="dType !== '0'">添加</el-button>
          <el-button size="mini" @click="editOrgan" :disabled="organformId === ''">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteOrgan" :disabled="organformId === ''">删除</el-button>
        </div>
        <async-navigation @treeClick="treeClickHandler" @searchSelect="searchSelectHandler" :operate-onoff="operateOnoff"></async-navigation>
      </div>
      <div class="tableCon" ref="tableDataRef">
        <!-- 搜索 -->
        <div class="tableTop">
          <el-form :inline="true" class="searchFormu searchCommon">
            <el-form-item label="登录名称">
              <el-input v-model="logName" placeholder="请输入登录名称" @keyup.enter.native="handleEnter"></el-input>
            </el-form-item>

            <el-form-item label="所属部门">
              <el-select class="typeSelect" v-model="statusValue" @change="selectChange" placeholder="请所属部门" style="width: 160px;">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item style="margin-right:0;">
              <el-button type="primary" icon="search" :loading="isQuery" @click="searchHandler">查询</el-button>
            </el-form-item>
          </el-form>
          <div class="btnHandle">
            <el-button type="info" size="small" @click="addUser">添加用户</el-button>
            <!-- <el-button type="primary" style="background: #41b883;" @click="editUser">修改用户</el-button> -->
            <el-button type="danger" size="small" @click="deleteUser">批量删除用户</el-button>
            <el-button type="info" size="small" style="margin-left: 40px;" @click="assignRoles">
              <i class="iconfont" style="font-size: 18px;line-height: 0;display: inline-block;vertical-align: middle;">&#xe617;</i> 批量分配角色
            </el-button>
          </div>
        </div>
        <!-- 表格 -->
        <table-form
          v-loading.body="isLoadingTableData"
          :selectionIsChear="isChecked"
          :colData="colData" 
          :data="tableData" 
          :colWidth="120" 
          :row-key="rowKey" 
          :max-height="height" 
          :submiting="submiting" 
          :isShowOper="isShowOper" 
          border 
          :sortable="sortable"
          @selection-change="handleSelectChange"     
          @clear-selection="handleClearSelection">
          <el-table-column 
            v-if="reserveSelection" 
            :reserve-selection="reserveSelection" 
            type="selection" 
            width="55">
          </el-table-column>
          <el-table-column 
            v-for="item in colData" 
            :key="item.prop" 
            :prop="item.prop" 
            :label="item.label" 
            :width="item.width" 
            :align="item.align" 
            :sortable="item.sortable || sortable">
            <template slot-scope="scope">
              <div v-if="item.prop == 'status'">
                {{ scope.row[item.prop] === 'enable' ? '启用' : '禁用' }}
              </div>
              <div v-else-if="item.prop == 'type'">
                {{ scope.row[item.prop] === '0' ? '超级管理员' : scope.row[item.prop] === '1' ? '普通管理员' :'普通用户' }}
              </div>
              <div v-else>
                {{ scope.row[item.prop] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column slot="fixedColumn" label="操作" fixed="right" width="260" align="center">
            <template slot-scope="scope">
              <el-button style="display:inline-block;margin-left:4px;"
                size="mini"
                plain
                @click="handleEdit($event, scope.row)">
                修改
              </el-button>
              <el-popover style="display:inline-block;margin-left:2px;"
                ref="popover"
                trigger="click"
                placement="top"
                width="160"
                v-model="scope.row.visible">
                <p style="font-size:14px;padding: 6px 0;">确定删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" @click="scope.row.visible = false">取消</el-button>
                  <el-button type="primary" size="mini" :loading="submiting" @click="handleDelete(scope.row, scope.$index)">确定</el-button>
                </div>
          
                <div slot="reference">
                  <el-button
                    size="mini"
                    type="danger"
                    plain
                    :disabled="scope.row.type === '0'"
                    @click.stop.prevent="scope.row.visible = true">
                    删除
                  </el-button>
                </div>
              </el-popover>
              <el-button
                type="info"
                plain
                style="display:inline-block;margin-left:8px;"
                size="mini"
                @click="handleRole($event, scope)">
                分配角色
              </el-button>
            </template>
          </el-table-column>
        </table-form>
        <!-- 分页 -->
        <el-row type="flex" justify="end" class="tableBottom">
          <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" 
            :current-page="currentPage" 
            :page-sizes="pageSizes" 
            :page-size="pageSize" 
            layout="total, sizes, prev, pager, next, jumper" 
            :total="total">
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!-- 添加机构 -->
    <addedit-organ-dialog 
      v-if="addOrganOnoff"
      :dialog-form-visible="addOrganOnoff" 
      :organform-id="organformId" 
      :row-organ-onoff="rowOrganOnoff"
      :organ-title="organTitle"
      @dialog-sure="sureAddOrgan"
      @dialog-cancel="cancelAddOrgan">
    </addedit-organ-dialog>
    <!-- 添加用户 -->
    <addedit-user-dialog 
      v-if="addUserOnoff" 
      :dialog-form-visible="addUserOnoff" 
      :form-id="formId"
      :user-title="userTitle" 
      :row-edit-onoff="rowOnoff" 
      @dialog-sure="sureRegister"
       @dialog-cancel="cancelRegister">
    </addedit-user-dialog>
    <!-- 判断是否选择了数据 -->
    <!-- <el-dialog 
      title="信息" 
      :visible.sync="isUserDialogVisible" 
      top="10%" 
      width="400px">
      <span>请选择用户</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isUserDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog> -->
    <!-- 删除用户 -->
    <el-dialog title="信息" 
      :visible.sync="deleteOrganDialog" 
      top="10%" 
      width="400px">
      <span>是否删除所选中的机构</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteOrganDialog = false">取 消</el-button>
        <el-button type="primary" @click="sureOrganDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除用户 -->
    <el-dialog title="信息" 
      :visible.sync="deleteDialogVisible" 
      top="10%" 
      width="400px">
      <span>是否删除所选中的用户</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureDeleteDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <assign-roles-dialog 
      v-if="assignRoleOnoff" 
      :user-selection-data="selectionDataId" 
      :user-len="userLen" 
      :organ-guid="organguid" 
      @dialog-sure="sureAssignRole" 
      @dialog-cancel="cancelAssignRole">
    </assign-roles-dialog>
  </div>
</template>
<script>
import base64 from 'base-64'
import BreadCrumb from '@/components/BreadCrumb.vue'
import TableForm from '@/components/Table.vue'
import AsyncNavigation from './navigation/navigation.vue'
import AddeditOrganDialog from './navigation/addeditOrganDialog.vue'
import AddeditUserDialog from './navigation/addeditUserDialog.vue'
import AssignRolesDialog from './navigation/assignRolesDialog.vue'

import Api from '@/api/index.js'

export default {
  name: 'UserManagement',
  components: {
    AsyncNavigation,
    BreadCrumb,
    TableForm,
    AddeditOrganDialog,
    AddeditUserDialog,
    AssignRolesDialog
  },
  data () {
    return {
      // 机构
      addOrganOnoff: false,
      rowOrganOnoff: false,
      organformId: '',
      organparentId: '',
      deleteOrganDialog: false,
      operateOnoff: false,
      dType: '0',

      dialogLoading: false,
      breadCrumbList: [], // 面包屑
      logName: '',
      statusValue: '', // 所选分类
      typeOptions: [{ // 类型选择列表
        value: '',
        label: '所有'
      }, {
        value: 'enable',
        label: '有部门'
      }, {
        value: 'disable',
        label: '无部门'
      }],
      userguid: '', 
      loginduserguid: '',
      organguid: '1', // 当前选中的分公司     
      organguids: '', // 当前选中公司子集所有
      grade: '0',
      parentId: '0',
      isLoadingTableData: false,
      userId: '', // id
      selectIds: '', // 选择的角色id

      addUserOnoff: false,
      rowOnoff: false,
      formId: '',
      userLen: true, // 选中了一个还是多个用户（1个为true,多个为false）

      deleteDialogVisible: false, // 删除开关
      // isUserDialogVisible: false, // 选择一个用户
      assignRoleOnoff: false, // 分配角色
      selectData: {}, // 选中的节点
      selectTreeIds: [], // 选中节点的id

      // 列表
      isChecked: false,
      isQuery: false,
      colData: [], // 表格信息
      tableData: [],
      rowKey: 'id',
      submiting: false,
      sortable: true,
      isShowOper: false,
      reserveSelection: true,
      selectionData: [],
      selectionDataId: '',
      pageSize: 15,
      pageSizes: [15, 30, 50, 100],
      currentPage: 1,
      total: null,
      height: '330',
      userTitle: '添加用户',
      organTitle: '添加机构'
    }
  },
  computed: {
    gisopUserInfo () {
      return this.$store.state.gisopUserInfo
    }
  },
  destroyed () {
    window.removeEventListener('resize', this.handleFn)
  },
  mounted () {
    this.breadCrumbList = [
      { title: '系统安全' },
      { title: '用户管理' }
    ]
    this.colData = [
      {prop: 'loginname', label: '登录名称', sortable: true, align: 'center'},
      {prop: 'username', label: '用户名称', sortable: true, align: 'center'},
      {prop: 'organguname', label: '部门', sortable: true, align: 'center'},
      {prop: 'usersType', label: '岗位', sortable: true, align: 'center'},
      {prop: 'roleids', label: '角色', sortable: true, align: 'center'},
      {prop: 'email', label: '邮箱', width: 180, sortable: true, align: 'center'},
      {prop: 'phone', label: '电话', width: 124, sortable: true, align: 'center'},
      {prop: 'usersex', label: '性别', width: 88, sortable: true, align: 'center'},
      {prop: 'status', label: '状态', width: 88, sortable: true, align: 'center'}
    ]
    this.loginduserguid = this.gisopUserInfo.userguid
    
    if (this.loginduserguid === undefined) {
      return false
    } else {
      this.loginduserguid = this.loginduserguid.trim()

      this.organguids = this.gisopUserInfo.organguid
      this.organguid = this.gisopUserInfo.organguid
    }
    // 钩子
    this.$nextTick(() => {
      this.handleFn()
    })

    window.addEventListener('resize', this.handleFn)
  },
  watch: {
    gisopUserInfo (val) {
      if (val.userguid === undefined) {
        return false
      } else {
        this.loginduserguid = val.userguid.trim()

        this.organguids = val.organguid
        this.organguid = val.organguid
      }

      this.getUserServiceList()
    }
  },
  methods: {
    // 清空选中
    handleClearSelection() {
      this.isChecked = false
      this.selectionData = []
    },
    // resize的函数
    handleFn () {
      let _this = this
      _this.height = _this.$refs.tableDataRef.clientHeight - 133
    },
    // 添加机构树
    addOrgan () {
      this.organTitle = '添加机构'
      this.addOrganOnoff = true
      this.rowOrganOnoff = false
    },
    // 修改机构
    editOrgan () {
      this.organTitle = '修改机构'
      this.addOrganOnoff = true
      this.rowOrganOnoff = true
    },
    // 确定添加或修改机构
    sureAddOrgan (datas) {
      this.dialogLoading = true
      var formData = new FormData()
      formData.append('organname', datas[0].organname)
      formData.append('organdescription', datas[0].organdescription)
      formData.append('organzipcode', datas[0].organzipcode)
      formData.append('contactemail', datas[0].contactemail)
      formData.append('contactfax', datas[0].contactfax)
      formData.append('contactname', datas[0].contactname)
      formData.append('contactphone', datas[0].contactphone)
      formData.append('status', datas[0].status)
      formData.append('sort', datas[0].sort)
      formData.append('organtype', datas[0].organtype)

      if (datas[1]) { // 修改机构
        formData.append('organguid', this.organformId)
        Api.updateOrganData(formData)
          .then(data => {
            if (data.status === 0) {
              this.dialogLoading = false
              this.addOrganOnoff = false
              this.operateOnoff = !this.operateOnoff
              this.$message({
                type: 'success',
                message: '修改机构成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '修改机构失败'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      } else { // 添加机构
        formData.append('parentguid', this.organformId)
        Api.saveOrganInfo(formData)
          .then(data => {
            if (data.status === 0) {
              this.dialogLoading = false
              this.addOrganOnoff = false
              this.operateOnoff = !this.operateOnoff
              this.$message({
                type: 'success',
                message: '添加机构成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '添加机构失败'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      }
    },
    // 关闭机构弹窗
    cancelAddOrgan () {
      this.addOrganOnoff = false
    },
    // 删除机构
    deleteOrgan () {
      this.deleteOrganDialog = true
    },
    // 确认删除机构
    sureOrganDelete () {
      this.selectTreeIds = []    
      // 测试
      this.getChilds(this.selectData, 'childOrganinfoinfos')
      let ids = this.selectTreeIds.join(',')
      this.deleteOrganDialog = false
      Api.deleteOrganData(ids)
        .then(data => {
          this.operateOnoff = !this.operateOnoff
          if (data.status === 0) {
            this.$message({
              type: 'success',
              message: '删除机构成功'
            })
          } else {
            this.$message({
              type: 'warning',
              message: '删除机构失败,请检查数据是否有误'
            })
          }
        })
        .catch(res => {
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
    },
    // 递归遍历获取该级及子级的id
    getChilds (data, children) {
      this.selectTreeIds.push(data.organguid)
      let childs = []
      childs = data[children]
      if (childs === null || childs === 0) {
        return data
      } else { 
      for (var i = 0; i < childs.length; i++) {
        this.getChilds(childs[i], children)
      }
      }
      return data
    },
    // 导航树点击处理
    treeClickHandler (data) {
      this.selectData = data
      this.organguid = data.id
      this.organformId = data.organguid
      this.dType = data.organtype
      this.currentPage = 1

      this.getUserServiceList()
      
      this.handleClearSelection()
    },
    // 导航查询下拉选择
    searchSelectHandler (data) {
      this.organguid = data.id
      this.organguids = data.id
      this.grade = data.grade
      this.parentId = data.parentId

      this.getUserServiceList()
    },
    // 列表
    getUserServiceList () {
      this.isLoadingTableData = true
      Api.getUserServiceList(this.currentPage, this.pageSize, this.organformId, this.logName, this.statusValue)
        .then(data => {
          this.isLoadingTableData = false
          let datas = data.data
          if (data.status === 0) {
            this.tableData = datas.result
            this.total = datas.total
          } else {
            this.$message({
              type: 'error',
              message: '获取数据失败！'
            })
          }
        })
        .catch(res => {
          this.isLoadingTableData = false

          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
    },
    // 当选项发生
    handleSelectChange (selection) {
      if (selection.length !== 0) {
        this.isChecked = true
        this.selectionData = selection
      } else {
        this.isChecked = false
        this.selectionData = []
      }
    },
    // 选择部门
    selectChange (val) {
      this.statusValue = val
    },
    // 查询
    searchHandler () {
      this.currentPage = 1
      this.getUserServiceList()
    },
    handleEnter () {
      this.searchHandler()
    },
    // 添加用户
    addUser() {
      this.userTitle = '添加用户'
      this.addUserOnoff = true
      this.rowOnoff = false
    },
    // 修改用户
    handleEdit (e, scope) {
      this.userTitle = '修改用户'
      e.preventDefault()
      e.stopPropagation()

      this.addUserOnoff = true
      this.rowOnoff = true
      this.formId = scope.userguid
      this.userguid = scope.userguid
    },
    // 确定添加用户或修改用户
    sureRegister (datas) {
      this.dialogLoading = true
      var formData = new FormData()

      formData.append('loginname', datas[0].loginName)
      formData.append('username', datas[0].userName)
      formData.append('address', datas[0].address)
      formData.append('email', datas[0].email)
      formData.append('phone', datas[0].phone)
      formData.append('status', datas[0].status)
      formData.append('usersex', datas[0].userSex)
      // formData.append('organguname', datas[0].organguname)
      formData.append('organguid', datas[0].organguid)
      formData.append('type', datas[0].type)

      if (datas[1]) { // 修改用户
        formData.append('userguid', this.userguid)
        if (datas[0].resetPassword !== '') {
          formData.append('userpassword', base64.encode(datas[0].resetPassword))
        }

        Api.editUserService(formData)
          .then(data => {
            this.dialogLoading = false
            this.addUserOnoff = false
            if (data.status === 0) {
              this.getUserServiceList()
              this.$message({
                type: 'success',
                message: '修改用户成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '修改用户失败,请检查数据是否有误'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      } else { // 添加用户
        formData.append('userpassword', base64.encode(datas[0].userPassword))
        Api.addUserService(formData)
          .then(data => {
            this.dialogLoading = false
            this.addUserOnoff = false
            if (data.status === 0) {
              this.getUserServiceList()
              this.$message({
                type: 'success',
                message: '添加用户成功'
              })
            } else {
              this.$message({
                type: 'warning',
                message: '添加用户失败,请检查数据是否有误'
              })
            }
          })
          .catch(res => {
            this.$message({
              type: 'error',
              message: '请求数据失败'
            })
          })
      }
    },
    // 关闭弹窗
    cancelRegister() {
      this.addUserOnoff = false
    },
    // 批量删除用户
    deleteUser () {
      if (this.selectionData.length !== 0) {
        for (let i = 0; i < this.selectionData.length; i++) {
          if (this.selectionData[i].type === 0) {
            this.$message({
              type: 'warning',
              message: '不能删除管理员，请重新选择'
            })
            return false
          }
        }
        this.deleteDialogVisible = true
      } else {
        this.$message({
          type: 'warning',
          message: '请选择需要删除的用户'
        })
      }
    },
    // 单个删除用户
    handleDelete (scope) {
      this.deleteUserService(scope.userguid)
    },
    // 确定删除
    sureDeleteDialog () {
      this.deleteDialogVisible = false

      var deleteArr = []
      this.selectionData.forEach(item => {
        deleteArr.push(item.userguid)
      })
      this.userguid = deleteArr.join(',')

      this.deleteUserService(this.userguid)
    },
    // 删除API
    deleteUserService (userguid) {
      Api.deleteUserService(userguid)
        .then(data => {
          if (data.status === 0) {
            this.getUserServiceList()
            this.$message({
              type: 'success',
              message: '删除用户成功'
            })
          } else {
            this.$message({
              type: 'warning',
              message: '删除用户失败,请检查数据是否有误'
            })
          }
        })
        .catch(res => {
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
    },
    // 批量分配角色
    assignRoles () {
      if (this.selectionData.length !== 0) {
        this.assignRoleOnoff = true
        var chooseArr = []
        this.selectionData.forEach(item => {
          chooseArr.push(item.userguid)
        })
        this.selectionDataId = chooseArr.join(',')

        if (this.selectionData.length > 1) {
          this.userLen = false
        } else {
          this.userLen = true
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请选择用户'
        })
      }
    },
    // 分配角色
    handleRole (e, scope) {
      e.preventDefault()
      e.stopPropagation()

      this.assignRoleOnoff = true
      this.userLen = true
      this.selectionDataId = scope.row.userguid.trim()
    },
    // 保存用户或机构与角色关系 
    saveRoleRelaOpr () {
      this.dialogLoading = true
      Api.saveRoleRelaOpr(this.selectionDataId, this.selectIds)
        .then(data => {
          this.dialogLoading = false
          if (data.status === 0) {
            this.getUserServiceList()
            this.$message({
              type: 'success',
              message: '保存角色分配成功'
            })
          }    
        })
        .catch(res => {
          this.$message({
            type: 'error',
            message: '请求数据失败'
          })
        })
    },
    // 确定分配角色
    sureAssignRole (data) {
      let selectIdArr = []
      for (let i = 0; i < data[0].length; i++) {
        selectIdArr.push(data[0][i].roleguid)
      }
      for (let i = 0; i < data[1].length; i++) {
        selectIdArr.push(data[1][i].roleguid)
      }
      this.selectIds = selectIdArr.join(',')

      /* let selectUerId = [],
          selectUerIds = ''
      for (let i = 0; i < this.selectionData.length; i++) {
        selectUerId.push(this.selectionData[i].userguid)
      }
      selectUerIds = selectUerId.join(',') */
      // console.log(this.selectionDataId)
      this.saveRoleRelaOpr(this.selectionDataId, this.selectIds)
  
      this.assignRoleOnoff = false
    },
    // 取消分配角色
    cancelAssignRole() {
      this.assignRoleOnoff = false
    },
    // 分页操作
    handleSizeChange(val) {
      this.pageSize = val
      if (this.tableData !== null) {
        this.getUserServiceList()
      }
    },
    handleCurrentChange (currentPage) {
      this.currentPage = currentPage
      if (this.tableData !== null) {
        this.getUserServiceList()
      }
    }
  }
}
</script>
<style lang="scss">
.userManagement {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;

  .con {
    flex: 1;
    display: flex;
    flex-direction: row;

    .nav {
      width: 230px;
      background: #fafdfd;
      box-shadow: 1px 2px 8px rgba(32, 34, 42, .2);
      
      display: flex;
      flex-direction: column;
    }

    .navBtn {
      width: 100%;
      background: rgba(8, 139, 134, 0.1);
      box-shadow: 1px 2px 8px rgba(32, 34, 42, .2);
      text-align: center;
      padding: 10px 0;

      i {
        display: inline-block;
        vertical-align: middle;
        line-height: 0;
      }
    }

    .tableCon {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: hidden;
    }
    .tableTop {  
      padding: 20px 10px 0px;

      .searchFormu {
        float: left;
        padding: 0;
      }
      .btnHandle {
        float: right;
        padding: 0px 10px 10px;
      }
    }
    .tableBottom {
      padding: 15px 10px 15px;
      height: 51px;
    }
  }

  .el-input-group__prepend {
    padding: 0 12px;
  }
}
</style>
