<template>
  <div class="dashboard-container">
    <div class="search-content">
      <el-input style="width: 220px;" placeholder="请输入姓名" v-model="data.nickName" clearable></el-input>
      <el-input style="width: 220px;" placeholder="请输入电话号码" v-model="data.phoneNum" clearable></el-input>
      <el-select style="width: 220px;" v-model="data.status" clearable placeholder="请选择状态">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <div class="search-btn">
        <div class="search" @click="searchUser">查询</div>
        <div class="reset" @click="reset()">重置</div>
      </div>
    </div>
    <div class="table-content">
      <div class="leftTree" :style="styleObj">
        <el-input placeholder="请输入部门" v-model="filterText">
        </el-input>
        <el-tree class="filter-tree" :data="treeData" :props="defaultProps" default-expand-all
          @node-click="handleNodeClick" :filter-node-method="filterNode" ref="tree">
        </el-tree>
      </div>
      <div class="rightTable">
        <div class="btn" @click="addUserBtn">
          <span class="icon font_family">&#xe604;</span>
          新增
        </div>
        <div class="btn" @click="batchDelUser">
          <span class="icon font_family">&#xe607;</span>
          批量删除
        </div>
        <div class="btn" @click="importLoadIn">
          <span class="icon font_family">&#xe606;</span>
          导入
        </div>
        <div class="btn" @click="expotrUser">
          <span class="icon font_family">&#xe605;</span>
          <a>导出</a>
        </div>
        <div class="btn" @click="downExcel()">
          <span class="icon font_family">&#xe603;</span>
          <a>下载模板</a>
        </div>
        <el-dialog center :visible.sync="uploadDialog" title="用户导入" width="620px">
          <el-upload ref="uploadFile" class="upload-demo" style="margin-left:110px" drag action="#"
            :http-request="uploadHttpRequest" :auto-upload="false" :file-list="fileList" :on-change="uploadFileList">
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <div class="el-upload__tip">只能上传xls/xlsx文件,且不超过500kb</div> -->
          </el-upload>
          <div class="hxj">支持扩展名: xls/xlsx</div>
          <div class="hxj">请先下载模板，根据模板内容填写，再上传文件 <span class="xzmba" @click="downExcel">下载模板</span> </div>
          <div slot="footer" class="dialog-footer">
            <div class="search" @click="httpRequest">保 存</div>
            <div class="reset" @click="uploadDialog = false">取 消</div>
          </div>
        </el-dialog>
        <el-table ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column fixed type="selection" width="55">
          </el-table-column>
          <!-- <el-table-column fixed type="index" label="序号" width="70">
          </el-table-column> -->
          <el-table-column fixed prop="userName" label="账号" width="100">
          </el-table-column>
          <el-table-column property="nickName" label="真实姓名" width="100">
          </el-table-column>
          <el-table-column property="deptName" label="部门名称" show-overflow-tooltip width="220">
          </el-table-column>
          <el-table-column property="roleName" label="所属角色" width="120" show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ returnRoleNames(scope.row.roleNames) }}
            </template>
          </el-table-column>
          <el-table-column property="phoneNum" label="联系电话" width="120">
          </el-table-column>
          <!-- <el-table-column property="email" label="联系邮箱" width="190">
          </el-table-column> -->
          <el-table-column label="状态">
            <template slot-scope="scope">
              <div class="startUsing" v-if="scope.row.status == 1">启用</div>
              <div class="Deactivate" v-else>停用</div>
            </template>
          </el-table-column>
          <el-table-column property="createTime" sortable label="创建时间" width="160">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="250">
            <template slot-scope="scope">
              <div class="operateBtn">
                <div v-if="scope.row.id !== 1" @click="updateUser(scope.row, true)">修改</div>
                <div v-if="scope.row.id !== 1" @click="delUser(scope.row)">删除</div>
                <div v-if="scope.row.id !== 1" @click="authorityBtn(scope.row)">数据权限</div>
                <!-- <div @click="viewDetails(scope.row)">详情查看</div> -->
                <div @click="updateUser(scope.row, false)">详情查看</div>
                <div @click="resetPwd(scope.row)">重置密码</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <detaileDialog class="detaileDialog" :detaileData="detaileData"></detaileDialog>
        <addUserDialog v-if="addUserData.dialogVisible" :addUserData="addUserData" @addUser="addUser"></addUserDialog>
        <updateUserDialog v-if="updateUserData.dialogVisible" :updateUserData="updateUserData"
          @updateUserBtn="updateUserBtn"></updateUserDialog>
        <authorityDialog v-if="authorityData.dialogVisible" :authorityData="authorityData"
          @updateAuthority="updateAuthority"></authorityDialog>
        <div class="pagination">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 15, 20]"
            :page-size="this.data.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getList, getDeptTree, userInformation, delUser, addUser, updateUser, getExcel, exportUserList, importUser, dictionaryList, dataPermission, resetPwd } from '@/api/sysManage'
import detaileDialog from './compontens/detaileDialog.vue'
import addUserDialog from './compontens/addUserDialog.vue'
import updateUserDialog from './compontens/updateUserDialog.vue'
import authorityDialog from './compontens/authorityDialog.vue'
import { is } from '@babel/types'
export default {
  name: 'home',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  components: {
    detaileDialog,
    addUserDialog,
    updateUserDialog,
    authorityDialog
  },
  created() {
    this.getList(this.data)
    this.getDeptTree()
    this.getAllAuthority()
  },
  mounted() {
    // let height = document.getElementsByClassName('leftTree')    
    // this.leftTreeHeight = height[0].clientHeight
    const height = document.documentElement.clientHeight - 200 + "px";
    this.styleObj.height = height
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      leftTreeHeight: 0,
      styleObj: {
        height: ''
      },
      uploadDialog: false,
      fileList: [],
      authorityData: {
        dialogVisible: false,
        id: '',
        dictValue: '',
        data: []
      },
      // 导入
      dataForm: {
        name: "",
        file: null,
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableData: [],
      data: {
        pageNum: 1,
        pageSize: 10,
        nickName: '',
        phoneNum: '',
        status: '',
        deptId: ''
      },
      total: 0,
      treeData: [],
      statusOptions: [
        {
          label: '启用',
          value: '1'
        },
        {
          label: '停用',
          value: '2'
        }
      ],
      detaileData: {
        dialogVisible: false,
        remark: '',
        data: {}
      },
      addUserData: {
        dialogVisible: false,
        data: {}
      },
      updateUserData: {
        dialogVisible: false,
        data: {
        },
        isEdit: null
      },
      delUserList: '',
      ids: []
    }
  },
  methods: {
    returnRoleNames(arr) {
      let roleNames = ''
      arr.forEach(item => {
        roleNames+=item+' '
      })
      return roleNames
    },
    importLoadIn: function () {
      this.uploadDialog = true
    },
    uploadFileList(file) {
      if (file.status === 'ready') {
        this.fileList.push(file)
        if (this.fileList.length > 1) {
          this.fileList.splice(0, 1)
        }
      }
    },
    //下载模板
    downExcel() {
      getExcel('/system/user/downloaExcel').then(res => {
        const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '新增用户模板.xlsx';
        a.click();
        window.URL.revokeObjectURL(url);
      })
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getList(data) {
      getList(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.records
          this.total = res.data.total
          // this.$nextTick(() => {
          //   let heightMsg = document.getElementsByClassName('rightTable')
          //   this.styleObj.height = heightMsg[0].clientHeight + 'px'
          // })
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    handleNodeClick(v) {
      this.data.pageNum = 1
      this.data.deptId = v.id
      this.getList(this.data)
    },
    getDeptTree() {
      getDeptTree().then(res => {
        this.treeData = res.data
      })
    },
    handleSizeChange(val) {
      this.data.pageSize = val
      this.getList(this.data)
    },
    handleCurrentChange(val) {
      this.data.pageNum = val
      this.getList(this.data)
    },
    searchUser() {
      this.data.deptId = ''
      this.getList(this.data)
    },
    //查看详情
    viewDetails(scope) {
      userInformation(scope.id).then(res => {
        this.detaileData.data = res.data
        this.detaileData.remark = res.roles[0].remark
      })
      this.detaileData.dialogVisible = true
    },
    //重置
    reset() {
      this.data = {
        pageNum: 1,
        pageSize: 10,
        nickName: '',
        phoneNum: '',
        status: '',
        deptId: ''
      }
      this.getList(this.data)
    },
    //修改用户
    updateUserBtn(payload) {
      let params = {
        id: payload.id,
        userName: payload.userName,
        password: payload.password,
        nickName: payload.nickName,
        sex: payload.sex,
        deptId: payload.deptId,
        roleIds: payload.roleIds,
        phoneNum: payload.phoneNum,
        email: payload.email,
        status: payload.status ? 1 : 2
      }
      updateUser(params).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.getList(this.data)
          this.updateUserData.dialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    delUser(scope) {
      this.$confirm('确定要删除吗?', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(scope.id).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });

            const totalPage = Math.ceil((this.total - 1) / this.data.pageSize)
            const pageNum = this.data.pageNum > totalPage ? totalPage : this.data.pageNum
            this.data.pageNum = pageNum < 1 ? 1 : pageNum
            this.getList(this.data)

          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //新增用户按钮
    addUserBtn() {
      this.addUserData.dialogVisible = true
    },
    updateUser(scope, isEdit) {
      let newScope = { ...scope }
      if (newScope.status == 1) {
        newScope.status = true
      } else {
        newScope.status = false
      }
      newScope.sex = newScope.sex.toString()
      this.updateUserData.isEdit = !isEdit
      this.updateUserData.data = newScope
      this.updateUserData.dialogVisible = true
    },
    addUser(payload) {
      if (payload.status) {
        payload.status = 1
      } else {
        payload.status = 2
      }
      addUser(payload).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '新增成功！'
          });
          this.addUserData.dialogVisible = false
          this.getList(this.data)
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      }).catch(err => {

      })
    },
    //多选用户
    handleSelectionChange(v) {
      let ids = []
      let delUserList = ''
      v.forEach(element => {
        delUserList += element.id + ','
        ids.push(element.id)
      });
      this.ids = ids
      delUserList = delUserList.slice(0, delUserList.length - 1)
      this.delUserList = delUserList
    },
    //批量删除用户
    batchDelUser() {
      if (this.delUserList.length == 0) {
        return this.$message({
          type: 'error',
          message: '请选择要删除的用户!'
        });
      }
      this.$confirm('确定要删除吗?', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(this.delUserList).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            const totalPage = Math.ceil((this.total - 1) / this.data.pageSize)
            const pageNum = this.data.pageNum > totalPage ? totalPage : this.data.pageNum
            this.data.pageNum = pageNum < 1 ? 1 : pageNum
            this.getList(this.data)
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //导出用户
    expotrUser() {
      if (this.ids.length == 0) {
        return this.$message({
          type: 'error',
          message: '请选择要导出的用户信息!'
        });
      } else {
        let params = {
          nickName: this.data.nickName,
          phoneNum: this.data.phoneNum,
          status: this.data.status,
          ids: this.ids
        }
        exportUserList(params).then(res => {
          // const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
          // const url = window.URL.createObjectURL(blob);
          // const a = document.createElement('a');
          // a.href = url;
          // a.download = '用户信息.xlsx';
          // a.click();
          // window.URL.revokeObjectURL(url);

          if (res.type == "application/json") {
            const reader = new FileReader(); 
            reader.readAsText(res, 'utf-8'); 
            reader.onload = function () {
              const msg = JSON.parse(reader.result);
              if(msg.code == 200){
                const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = '用户信息.xlsx';
                a.click();
                window.URL.revokeObjectURL(url);
              } else{
                Message({
                  type: 'error',
                  message: msg.msg
                });
              }      
            }
          }else{
            const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '用户信息.xlsx';
            a.click();
            window.URL.revokeObjectURL(url);
          }


        })
      }
    },
    // 判断文件个数
    handleChange(file, fileList) {
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
    },
    // 导入
    httpRequest(param) {
      let formData = new FormData();
      // formData.append('file', this.dataForm.file.raw);
      formData.append('file', this.fileList[0].raw)
      let configHeaders = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      let isHttpRequest = this.fileList[0].raw.name.split('.')
      if (isHttpRequest[isHttpRequest.length - 1] == 'xlsx' || isHttpRequest[isHttpRequest.length - 1] == 'xls') {
        importUser(formData).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '导入成功!'
            });
            let uid = this.fileList[0].raw.uid
            let idx = this.$refs.uploadFile.uploadFiles.findIndex(item => item.uid === uid)
            this.$refs.uploadFile.uploadFiles.splice(idx, 1)
            this.getList(this.data)
            this.uploadDialog = false
          }else{
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: '上传的文件只能是xls以及xlsx格式!'
        });
        let uid = this.fileList[0].raw.uid
        let idx = this.$refs.uploadFile.uploadFiles.findIndex(item => item.uid === uid)
        this.$refs.uploadFile.uploadFiles.splice(idx, 1)
      }
    },
    //获取全部权限信息
    getAllAuthority() {
      dictionaryList('data_permission').then(res => {
        if (res.code == 200) {
          this.authorityData.data = res.data
        }
      })
    },
    authorityBtn(scope) {
      this.authorityData.dictValue = scope.dataPermission.toString()
      this.authorityData.id = scope.id
      this.authorityData.dialogVisible = true
    },
    updateAuthority(payload) {
      dataPermission(payload.id, payload.dataPermission).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.getList(this.data)
          this.authorityData.dialogVisible = false
        }
      })
    },
    resetPwd(row) {
      this.$confirm('是否重置密码?', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd(row.id).then(res => {
          if (res.code == 200) {
            this.getList(this.data)
            this.$message({
              type: 'success',
              message: '重置成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-container {
  .search-content {
    width: 100%;
    height: 74px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-left: 10px;

    .el-input {
      margin: 0 10px;
    }

    .el-select {
      margin: 0 10px;
    }

    .search-btn {
      // display: inline-block;
      display: flex;
      align-items: center;
      height: 100%;
      margin-left: 10px;

      div {
        // margin: 0 6px;
        display: inline-block;
        width: 80px;
        height: 40px;
        border-radius: 2px;
        font-size: 14px;
        line-height: 40px;
        text-align: center;
      }

      div:hover {
        cursor: pointer;
      }

      .search {
        margin-right: 10px;
        background-color: #2766DD;
        color: #F7F8FB;
      }

      .search:hover {
        background-color: #4D85F4;
      }

      .reset {
        color: #333334;
        border: 1px solid #D7D7D7;
      }

      .reset:hover {
        color: #1F9FFF;
        border: 1px solid #1F9FFF;
      }
    }
  }

  .table-content {
    margin-top: 15px;
    width: 100%;
    background-color: #fff;

    .leftTree {
      float: left;
      width: 14.2%;
      padding: 20px 10px 20px;
      // height: 100%;
      // height: document.documentElement.clientHeight - 100 + "px";
      background-color: #fff;
      overflow: auto;
    }

    .rightTable {
      float: right;
      width: 85%;
      background-color: #fff;
      padding: 0 20px;

      .btn {
        margin: 15px 20px 15px 0;
        cursor: pointer;
        float: left;
        text-align: center;
        width: 98px;
        height: 34px;
        border-radius: 2px;
        border: 1px solid #ABC7FD;
        line-height: 34px;
        font-weight: 400;
        font-size: 14px;
        color: #2250C8;
        background-color: #E7EEFF;
      }

      .btn:hover {
        color: #FFFFFF;
        background-color: #2250C8;
        border: 1px solid #2250C8;
      }

      .btn:active {
        color: #FFFFFF;
        background-color: #194DA4;
        border: 1px solid #194DA4;
      }

      .startUsing {
        width: 54px;
        height: 24px;
        margin: 14.5px auto 0;
        line-height: 24px;
        text-align: center;
        font-size: 12px;
        color: #00974D;
        border-radius: 4px;
        background-color: #E7FAF0;
        border: 1px solid #BEFDDD;
      }

      .Deactivate {
        width: 54px;
        height: 24px;
        margin: 14.5px auto 0;
        line-height: 24px;
        text-align: center;
        font-size: 12px;
        color: #FF9933;
        border-radius: 4px;
        background-color: #FFF3E8;
        border: 1px solid #FDE6CF;
      }

      .operateBtn {
        display: flex;
        justify-content: center;
        color: #2866DD;

        div {
          font-size: 12px;
          margin: 0 5px;
          cursor: pointer;
        }
      }

      .pagination {
        float: right;
        margin: 10px 0;
      }
    }
  }

  .xzmba {
    color: #2766DD;
    text-decoration: underline;
    cursor: pointer;
  }

  .hxj {
    height: 46px;
    line-height: 46px;
    text-align: center;
  }

  .search_btn {
    background-color: #2766DD;
    color: #F7F8FB;
    font-size: 14px;
  }

  .search_btn:hover {
    background-color: #4D85F4;
  }

  .reset_btn {
    color: #565656;
    font-size: 14px;
    border: 1px solid #D7D7D7;
  }

  .reset_btn:hover {
    color: #1F9FFF;
    border: 1px solid #1F9FFF;
    background: none;
  }
}

.dialog-footer {
  div {
    display: inline-block;
    width: 80px;
    height: 40px;
    border-radius: 2px;
    font-size: 14px;
    line-height: 40px;
    text-align: center;
  }

  div:hover {
    cursor: pointer;
  }

  .search {
    margin: 0 12px;
    background-color: #2766DD;
    color: #fff;
  }

  .search:hover {
    background-color: #4D85F4;
  }

  .reset {
    color: #333334;
    border: 1px solid #D7D7D7;
  }

  .reset:hover {
    color: #1F9FFF;
    border: 1px solid #1F9FFF;
  }
}
</style>
