<template>
  <div class="app-container">
    <el-row>
      <!--左半部分-->
      <el-col :span="5">
        <div style="width:90%;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>组织机构</span>
            </div>
            <el-tree
              v-loading = "treeLoading"
              ref="tree2"
              :data="deptTree"
              :props="defaultProps"
              :default-expand-all="expandAllNode"
              :expand-on-click-node="expandNodeClick"
              class="filter-tree"
              @node-click = "handleNodeClick"
            />
          </el-card>
        </div>
      </el-col>
      <!--右半部分-->
      <el-col :span="19">
        <!--筛选条件-->
        <div class="search-div">
          <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container">
            <el-row>
              <el-form-item class="selectForm-container-item" prop="keywords">
                <el-input v-model.trim="listQuery.keywords" placeholder="账号/姓名/手机号" clearable/>
              </el-form-item>
              <el-form-item class="selectForm-container-item" width="370">
                <el-date-picker
                  v-model="registerTime"
                  type="daterange"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="注册开始日期"
                  end-placeholder="注册结束日期"/>
              </el-form-item>
              <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            </el-row>
            <el-row>
              <el-button v-if="hasPerm('/mgr/add')" class="filter-item" type="primary" icon="el-icon-edit" @click="add">新增</el-button>
              <el-button v-if="hasPerm('/mgr/update')" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="edit">修改</el-button>
              <el-button v-if="hasPerm('/mgr/delete')" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="del">删除</el-button>
              <el-button v-if="hasPerm('/mgr/reset')" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="resetPwd">重置密码</el-button>
              <el-button v-if="hasPerm('/mgr/roleAssign')" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="roleAssign">角色分配</el-button>
              <!--<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="add">冻结</el-button>-->
              <!--<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="add">解冻</el-button>-->
            </el-row>
          </el-form>
        </div>
        <!--查询结果Table显示-->
        <el-table v-loading="listLoading" :data="list" class="table" border stripe>
          <!--<el-table-column-->
          <!--type="index"-->
          <!--width="55"/>-->
          <el-table-column label="选择" width="70" header-align="center" align="center">
            <template slot-scope="scope">
              <el-radio v-model="radio" :label="scope.$index" class="radio">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column v-for="column in columns" :key="column.value" :label="column.text" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row[column.value] }}
            </template>
          </el-table-column>
          <!--冻结状态-->
          <el-table-column label="状态" width="80" align="center" >
            <template slot-scope="scope">
              <el-tag :type="tagNames[scope.row.statusName]" size="medium">{{ scope.row.statusName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="hasPerm('/mgr/freeze')" label="操作" width="60">
            <template slot-scope="scope">
              <el-button v-if="hasPerm('/mgr/freeze')" :type="btnStatus[scope.row.statusName]" size="mini" @click="freeze(scope.row)">{{ btnNames[scope.row.statusName] }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="pagination-container">
          <el-pagination
            v-show="total>listQuery.limit"
            :current-page="listQuery.page"
            :page-sizes="[20,30,50,100]"
            :page-size="listQuery.limit"
            :total="total"
            align="center"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </el-col>
    </el-row>
    <!--编辑用户的对话框-->
    <edit-user v-show="editShow" ref="edituser" @watchChild="fetchData"/>
    <role-assign v-show="roleAssignShow" ref="roleassign" @watchChild="fetchData"/>
  </div>
</template>

<script>
import { RSAencrypt } from '@/utils/security'
import editUser from '@/views/system/user/editUser'
import roleAssign from '@/views/system/user/roleAssign'
import { getUserList, delUser, freezeUser, unfreezeUser, resetPwd } from '@/api/user'
import { getDeptTreeList } from '@/api/dept'
import { toTreeList } from '@/utils/structure'

export default {
  name: 'ListUser',
  components: {
    roleAssign,
    editUser
  },
  data() {
    return {
      radio: '',
      password: '111111',
      listQuery: {
        keywords: '',
        beginTime: '',
        endTime: '',
        deptid: '',
        page: 1,
        limit: 20,
        sort: 'id'
      },
      registerTime: [], // 注册时间范围
      tagNames: {
        '已冻结': 'warning',
        '启用': 'success'
      },
      btnNames: {
        '已冻结': '解冻',
        '启用': '冻结'
      },
      btnStatus: {
        '已冻结': 'success',
        '正常': 'danger'
      },
      columns: [
        {
          text: '账户',
          value: 'account'
        },
        {
          text: '所在组织机构',
          value: 'deptName',
          width: 150
        },
        {
          text: '真实姓名',
          value: 'name',
          width: 50
        },
        {
          text: '角色',
          value: 'roleName'
        },
        {
          text: '手机号',
          value: 'phone'
        }
      ],
      list: [],
      total: 0,
      deptTree: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeLoading: false,
      listLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      editShow: false, // 编辑组件是否显示
      roleAssignShow: false, // 角色分配组件是否显示
      expandAllNode: true,
      expandNodeClick: false
    }
  },
  watch: {
    registerTime(val) {
      if (val && val.length > 0) {
        this.listQuery.beginTime = val[0]
        this.listQuery.endTime = val[1]
      } else {
        this.listQuery.beginTime = ''
        this.listQuery.endTime = ''
      }
    }
  },
  created() {
    this.fetchDeptTree()
    this.fetchData()
  },
  methods: {
    // 打开新增对话框
    add() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.edituser.initDialog(this.dialogStatus, this.dialogFormVisible)
    },
    // 打开修改对话框
    edit() {
      if (this.singleCheck()) {
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.editShow = true
        const row = this.list[this.radio]
        this.$refs.edituser.initDialog(this.dialogStatus, this.dialogFormVisible, row)
      } else {
        this.$message.error('必须选中一项')
      }
    },
    // 打开角色分配对话框
    roleAssign() {
      if (this.singleCheck()) {
        this.dialogFormVisible = true
        this.roleAssignShow = true
        const row = this.list[this.radio]
        this.$refs.roleassign.initDialog(this.dialogFormVisible, row)
      } else {
        this.$message.error('必须选中一项')
      }
    },
    // 删除
    del() {
      if (this.singleCheck()) {
        const row = this.list[this.radio]
        this.$confirm(
          '确定要删除' + row.name + '吗？',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          delUser(row.id).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.deleteItem(this.list, row)// 前端删除指定项
            }
          })
        })
      } else {
        this.$message.error('必须选中一项')
      }
    },
    // 重置密码
    resetPwd() {
      if (this.singleCheck()) {
        const row = this.list[this.radio]
        this.$confirm(
          '确定要重置' + row.name + '的密码为' + this.password + '吗？',
          '确认重置密码',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 加密
          const pwd = RSAencrypt(this.password)
          const params = {
            id: row.id,
            newPwd: pwd
          }
          resetPwd(params).then(response => {
            if (response.code === 200) {
              this.$message.success('重置密码成功')
            }
          })
        })
      } else {
        this.$message.error('必须选中一项')
      }
    },
    // 冻结或解冻
    freeze(row) {
      console.log(row.id)
      if (row.statusName === '已冻结') {
        this.$confirm(
          '确定要对' + row.name + '解除冻结吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          unfreezeUser(row.id).then(response => {
            if (response.code === 200) {
              this.$message.success('解除冻结成功')
              row.statusName = '启用'
              console.log('rowStatusName:' + row.statusName)
            }
          })
        })
      } else {
        this.$confirm(
          '确定要冻结' + row.name + '吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          freezeUser(row.id).then(response => {
            if (response.code === 200) {
              this.$message.success('冻结用户成功')
              row.statusName = '已冻结'
            }
          })
        })
      }
    },
    // 查询数据
    search() {
      this.fetchData()
    },
    // 获取用户数据
    fetchData() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
        this.radio = ''
      })
    },
    // 获取组织结构树
    fetchDeptTree() {
      this.treeLoading = true
      getDeptTreeList(this.listQuery).then(response => {
        this.deptTree = toTreeList(response.data.list, '0', true)
        this.treeLoading = false
      })
    },
    // 点击左侧组织结构项触发
    handleNodeClick(data) {
      this.listQuery.deptid = data.id
      this.fetchData()
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchData()
    },
    // 在嵌套列表list中删除指定元素
    deleteItem(list, des) {
      list.forEach((value, index) => {
        if (value.id === des.id) {
          list.splice(index, 1)
          return
        } else {
          if (value.children && value.children.length > 0) {
            this.deleteItem(value.children, des)
          }
        }
      })
    },
    // 检查单选,选中
    singleCheck() {
      if (this.radio === '') {
        return false
      } else {
        return true
      }
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .form-container{
    margin-bottom: 20px;
  }
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .el-date-editor{
    .el-range-separator{
      width: 7% !important;
    }
  }
  .el-range-separator{
    width: 7% !important;
  }
</style>
