<template lang='pug'>
    el-container(style="padding:0px;height:77.6vh;")
        el-header(style='height:42px;line-height:42px;border: 1px solid rgba(195, 195, 195, 1);background: #f4f4f4;')
            span.title-bold.title-left-color()  用户管理
            el-popover( placement="bottom" width="150")
                    el-button( slot="reference" size='mini' type="primary" icon="el-icon-s-tools" style='float:right;transform:translateY(6px)')  筛选
                    el-checkbox-group( v-model="checkList")
                        el-col( :span="24")
                            el-checkbox( v-for="(item,index) in tableHeader" :label="item" :key="index" )
                              span {{item.label}}
        el-main.box_main
            el-card()
                div.tableCard()
                    el-form(:inline="true" :model="dataForm" size="mini" )
                        el-form-item( label="姓名:" )
                            el-input.input_width(v-model="dataForm.name" placeholder="姓名" clearable)
                        el-form-item(label="账号:")
                            el-input.input_width(v-model="dataForm.username" placeholder="账号" clearable)
                        el-form-item( label="工号:")
                            el-input.input_width(v-model="dataForm.jobNumber" placeholder="工号" clearable)
                        el-form-item( label="性别:")
                            el-select.input_width(v-model="dataForm.gender" placeholder="请选择" clearable)
                                el-option( label="男" value="1")
                                el-option( label="女" value="0")
                        el-form-item( label="账号状态:")
                            el-select.input_width(v-model="dataForm.status" placeholder="请选择"  clearable)
                                el-option( label="正常" value="1")
                                el-option( label="禁用" value="0")
                        el-button(@click="getDataList" size="mini" icon="el-icon-search" type="primary") 查询
                        el-button(@click="reSet()" size="mini" type="primary" icon="el-icon-refresh-right") 重置
                        el-button( v-if="isAuth('sys:user:save')" style="float:right;" size="mini" icon="el-icon-plus" type="primary" @click="addOrUpdateHandle()") 新增
                //- el-table( :data="dataList" @sort-change='sortChange' style="width:100%;" v-loading="dataListLoading" :stripe="true"  @selection-change="selectionChangeHandle"  :header-cell-style="{background:'#EEF8FF',color:'#333333'}")
                //-     el-table-column( type='index', header-align='center', align='center',width=100 label='序号')
                //-       template(scope="scope")
                //-         span {{scope.$index+(pageIndex - 1) * pageSize + 1}}
                //-     el-table-column( prop="name" header-align="center" align="center" label="姓名" sortable='custom')
                //-     el-table-column( prop="username" header-align="center" align="center" label="账号" sortable='custom')
                //-     el-table-column( prop="jobName" header-align="center" align="center" label="用户岗位" sortable='custom' width=120)
                //-     el-table-column( prop="job_number" header-align="center" align="center" label="工号" sortable='custom')
                //-     el-table-column( prop="entry_time" header-align="center" align="center" label="入职时间" sortable='custom' width=120)
                //-     el-table-column( prop="gender" header-align="center" align="center" label="性别" sortable='custom')
                //-         template(slot-scope='scope')
                //-             font(v-if='scope.row.gender===0') 女
                //-             font(v-if='scope.row.gender===1') 男
                //-     el-table-column( prop="nationName" columnKey='nation' header-align="center" align="center" label="民族" sortable='custom')
                //-     el-table-column( prop="politic_countenance" header-align="center" align="center" label="政治面貌" sortable='custom' width=120)
                //-     el-table-column( prop="education" header-align="center" align="center" label="学历" sortable='custom')
                //-     el-table-column( prop="mobile" header-align="center" align="center" label="手机号" sortable='custom' width=120)
                //-     el-table-column( prop="status" header-align="center" align="center" label="账号状态" sortable='custom' width=120)
                //-         template(slot-scope='scope')
                //-             font(v-if='scope.row.status===1') 正常
                //-             font(v-if='scope.row.status===0') 禁用
                //-     el-table-column( prop header-align="center" align="center" label="操作" width='280')
                //-         template( slot-scope="scope")
                //-             //- el-button(type="success" plain size="mini"  @click="queryHandle(scope.row)") 详情
                //-             el-button(type="text"  size="mini"  v-if="isAuth('sys:user:update')" @click="addOrUpdateHandle(scope.row.user_id)") 编辑
                //-             el-button(type="text"  size="mini" v-if="isAuth('sys:user:delete')" @click="deleteHandle(scope.row.user_id)" :disabled="del_disable(scope.row.user_id)") 删除
                //-             el-button(type="text"  size="mini" v-if="isAuth('sys:user:role')"  @click="configHandle(scope.row)" ) 配置角色
                //-             el-button(type="text"  size="mini" v-if="isAuth('sys:user:update')"  @click="resetPassword(scope.row)") 密码重置
                drag-table( :data="dataList" :header="checkList" :isToLine='false' :option="tableOption"  @getDataList="getDataList" v-loading="dataListLoading"  :operationNum="4"  :isShowOperate="true")
                  //- -- 插槽
                  el-table-column(slot="fixed"  fixed  prop=""  label="序号" width="80"  header-align="center" align="center")
                      template( slot-scope="scope")
                        span   {{scope.$index+(pageIndex - 1) * pageSize + 1}}

                  template( slot='gender' slot-scope="scope")
                     font(v-if='scope.row.gender===0') 女
                     font(v-if='scope.row.gender===1') 男
                  template(slot='status' slot-scope='scope')
                    font(v-if='scope.row.status===1') 正常
                    font(v-if='scope.row.status===0') 禁用
                  //- 操作项
                  template( slot-scope="scope" )
                    el-button(type="text"  size="mini"  v-if="isAuth('sys:user:update')" @click="addOrUpdateHandle(scope.row.user_id)") 编辑
                    el-button(type="text"  size="mini" v-if="isAuth('sys:user:delete')" @click="deleteHandle(scope.row.user_id)" :disabled="del_disable(scope.row.user_id)") 删除
                    el-button(type="text"  size="mini" @click="queryHandle(scope.row.user_id)") 详情
                    el-button(type="text"  size="mini" v-if="isAuth('sys:user:role')"  @click="configHandle(scope.row)" ) 配置角色
                    el-button(type="text"  size="mini" v-if="isAuth('sys:user:update')"  @click="resetPassword(scope.row)") 密码重置

        el-footer.box_footer
            el-pagination(@size-change="sizeChangeHandle" background  @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"  :total="totalPage" layout="total, sizes, prev, pager, next, jumper")
            //- 弹窗, 新增 / 修改
            add-or-update(v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshdatalist="getDataList")
            query-detail(v-if="queryDetailVisible" ref="queryView" @refreshdatalist="getDataList")
            config-role(v-if="configRoleVisible" ref="configView" @refreshdatalist="getDataList")
            reset-password(v-if="resetPasswordVisible" ref="resetView" @refreshdatalist="getDataList")
</template>

<script>
import AddOrUpdate from './user-add-or-update'
import queryDetail from './query-detail'
import configRole from './config-role'
import resetPassword from './reset-password'

import dragTable from '../../components/tab'

export default {
  name: 'sys-user',
  filters: {
    ellipsis (value) {
      if (!value) return ''
      if (value.length > 20) {
        return value.slice(0, 20) + '...'
      }
      return value
    }
  },
  data () {
    return {
      checkList: [], //筛选数据
      tableHeader: [
        { label: '姓名', prop: 'name' },
        { label: '账号', prop: 'username' },
        { label: '用户岗位', prop: 'jobName' },
        { label: '工号', prop: 'job_number' },
        { label: '入职时间', prop: 'entry_time' },
        { label: '性别', prop: 'gender', slot: true },
        { label: '民族', prop: 'nationName' },
        { label: '政治面貌', prop: 'politic_countenance' },
        { label: '学历', prop: 'education' },
        { label: '手机号', prop: 'mobile' },
        { label: '账号状态', prop: 'status', slot: true }
      ],
      tableOption: {
        border: false, //是否边框
        maxHeight: 500 //高度
      },
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isCollapse: true,
      dataForm: { name: '', username: '', jobNumber: '', gender: '', status: '' },
      sysOrgList: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      resetPasswordVisible: false,
      addOrUpdateVisible: false,
      queryDetailVisible: false,
      configRoleVisible: false,
      allJob: []
    }
  },
  components: {
    AddOrUpdate,
    queryDetail,
    configRole,
    resetPassword,
    dragTable
  },
  watch: {
    totalPage() { //注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      let pages = Math.ceil(this.totalPage / this.pageSize)//新数据总页数
      //总页数小于当前页数则重新加载列表数据
      if (pages < this.pageIndex) {
          this.pageIndex = pages || 1
          this.getDataList()//获取表格数据的方法
      }
    }
  },
  created () {
    // this.getList()
    this.getDataList()
    this.getAllJob()
    this.checkList = [...this.tableHeader]
  },
  methods: {
    //重置
    reSet() {
      this.pageIndex = 1
      this.dataForm = { name: '', username: '', jobNumber: '', gender: '', status: '' }
      this.getDataList()
    },
    //排序
    // sortChange (column) {
    //   if (column.order === 'descending') {
    //     this.order = 'desc'
    //   } else {
    //     this.order = 'asc'
    //   }
    //   if (column.column.columnKey) {
    //     this.sort = column.column.columnKey
    //   } else {
    //     this.sort = column.prop
    //   }
    //   this.getDataList()
    // },
    //修改用户角色
    updateUserRole (userId, roles) {
      // roleIds ：角色ids(多个角色id用逗号隔开)
      //updateRoleList(String userId, String roleIds)
    },
    //查看当前用户角色信息
    queryHandle (id) {
      this.queryDetailVisible = true
      this.$nextTick(() => {
        this.$refs.queryView.init(id)
      })
    },
    //获取职业字典信息
    getAllJob () {
      this.$http({
        url: this.$http.adornUrl('/sysDictionary/getAllJobList'),
        method: 'get',
        params: this.$http.adornParams({
          stationId: localStorage.getItem('stationId')
        })
      }).then(data => {
        if (data && data.code === 0) {
          this.allJob = data.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    //配置角色
    configHandle (row) {
      // console.log('row', row)
      this.configRoleVisible = true
      this.$nextTick(() => {
        this.$refs.configView.init(row)
      })
    },
    // 重置密码
    updatePassword () {
      const ids = this.dataListSelections.map(item => {
        return item.user_id
      })
      let userIds = ''
      ids.forEach(item => {
        userIds = userIds + item + ','
      })
      userIds = userIds.substring(0, userIds.length - 1)
      console.log(userIds)
      this.$http({
        url: this.$http.adornUrl('/sys/user/updatePassword'),
        method: 'POST',
        params: this.$http.adornParams({
          userIds: userIds
        })
      }).then(data => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshdatalist')
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    resetPassword (row) {
      this.resetPasswordVisible = true
      this.$nextTick(() => {
        this.$refs.resetView.init(row)
      })
    },
    //是否可以点击删除
    del_disable (id) {
      return localStorage.getItem('userId') === id
    },
    // handleNodeClick (data) {
    //   this.dataForm.orgId = data.id
    //   this.getDataList()
    // },
    //获取部门列表
    // getList() {
    //     this.$http({
    //         url: this.$http.adornUrl('/sysOrg/orgAllList'),
    //         method: 'GET'
    //     }).then(data => {
    //         if (data) {
    //             this.data = data.list
    //             this.dataForm.orgId = this.data[0].id
    //             this.getDataList()
    //         }
    //         // console.log(this.data)
    //     })
    // },

    // 获取数据列表
    getDataList (sort, order) {
      // console.log(this.sort, this.order)
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sys/user/selectUserByOrgId'),
        method: 'get',
        params: {
          name: this.dataForm.name,
          username: this.dataForm.username,
          jobNumber: this.dataForm.jobNumber,
          gender: this.dataForm.gender,
          status: this.dataForm.status,
          page: this.pageIndex,
          size: this.pageSize,
          sort: sort,
          order: order,
          stationId: localStorage.getItem('stationId')
        }
      }).then(data => {
        // console.log('data', data)
        if (data && data.code === 0) {
          const datas = data.data
          this.dataList = datas.records
          this.totalPage = datas.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var userIds = id
        ? [id]
        : this.dataListSelections.map(item => {
          return item.userId
        })
      this.$confirm(`确认删除该用户?`, '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/user/delete'),
          method: 'post',
          data: this.$http.adornData(userIds, false)
        }).then(data => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang='scss'>
.box_main /deep/.el-table .el-table--fit .el-table--striped .el-table--enable-row-hover .el-table--enable-row-transition{
  border: 1px solid  !important;

}
</style>
