<template>
 
  <div>
    <!-- <h3>用户列表组件</h3> -->
    <!-- 面包屑导航 -->
    <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb> -->


    <el-card class="box-card">
      <!-- 添加与搜索区域 -->
      <div class="search-bx1">
          <el-select v-model="sendData.pastureId" filterable placeholder="单位" style="width: 240px;" class="g-mr20">
            <el-option   v-for="item in pastureList"  :key="item.id"   :label="item.name"     :value="item.id"
            />
          </el-select>

  
          <el-select v-model="sendData.roleId" filterable placeholder="角色" style="width: 240px;" class="g-mr20">
            <el-option   v-for="item in roleSelectList"  :key="item.roleId"   :label="item.roleName"     :value="item.roleId"
            />
          </el-select>
          
          <el-input v-model="sendData.nameOrLoginName" placeholder="姓名"  style="width: 220px;" class="g-mr20" clearable />
         
          <el-input v-model="sendData.loginName" placeholder="工号"  style="width: 220px;" class="g-mr20" clearable />
           
 
          <el-button type="primary"   @click="form_search">搜索</el-button>
          <!-- <el-button type="primary"   @click="form_add">添加用户</el-button>
          <el-button type="primary"   @click="form_export">导出</el-button> -->
      </div>

 
      <!-- 表格 -->
      <el-table   key="0"  :data="tableList"  v-loading="tableLoading" element-loading-text="给我一点时间"  stripe border fit>
        <el-table-column label="序号"  width="50px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.number }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pastureName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.actualName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工号" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.loginName }}</span>
          </template>
        </el-table-column>
 
        <el-table-column label="电话" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.roleNameList  }}</span>
          </template>
        </el-table-column>
 
        <!-- <el-table-column  label="状态"  min-width="100px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"   />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <!-- <el-button type="primary" size="mini" icon="el-icon-edit" @click="form_edit(scope.row)">修改</el-button>-->
            <!-- 删除按钮 -->
             <!-- <el-button type="danger" size="mini" icon="el-icon-delete" @click="form_delete(scope.row)">删除</el-button> -->
            <!-- 分配角色 -->
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="form_set(scope.row)">分配角色</el-button>
            
            <el-button type="warning" size="mini"   @click="reset_password(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination  @size-change="change_size_page"  @current-change="change_current_page"  :current-page="sendData.pageNum" :page-sizes="[1,5,10,20,30,50]"  :page-size="sendData.pageSize" layout="total, prev, pager, next" :total="sendData.total"/>
    </el-card>


    <!-- 弹窗 新增or修改 -->
    <el-dialog  :title="addFormTxt[addFormStatus]" :visible.sync="addFormShow" @close="add_dialog_close" width="50%">
      <div class="">
        <el-form  ref="addFormRef"  :rules="addFormRules"  :model="addForm"  label-position="right" label-width="70px"  style="width:50%;margin:0 auto 50px">
            <el-form-item label="用户名" prop="username">
                <el-input   v-model="addForm.username"  :disabled="addFormStatus==='edit'"></el-input>  
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input   v-model="addForm.password"></el-input>  
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input   v-model="addForm.email"></el-input>  
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input   v-model="addForm.mobile"></el-input>  
            </el-form-item>
            
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addFormStatus==='create'?add_dialog_save():edit_dialog_save()">确认</el-button>
          <el-button @click="addFormShow = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 弹窗 分配角色 -->
    <el-dialog  title="分配角色" :visible.sync="setFormShow" @close="set_dialog_close" width="50%">
      <div class="">
        <el-form  ref="setFormRef"    :model="setForm"  label-position="right" label-width="70px"  style="width:50%;margin:0 auto 50px">
            <!-- <el-form-item label="用户名" prop="username">
                <el-input   v-model="setForm.username"  disabled ></el-input>  
            </el-form-item> -->
        
            <el-form-item   label="角色" prop="roleList">
            <el-select v-model="setForm.roleIdList" style="width:400px;" multiple placeholder="角色">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
     
            
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="set_dialog_save()">确认</el-button>
          <el-button @click="setFormShow = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    
  </div>


</template> 

<script>
import {  ajaxDataGet, ajaxDataPost } from '@/api/common'
import { parseTime, json2excel } from '@/utils/index.js'
export default {
  data() {


    

    //自定义的验证邮箱规则
    var checkEmail = (rule, value, cb) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

        if(regEmail.test(value)){
          //合法的邮箱
          return cb()
        }

        cb(new Error('请输入合法的邮箱'))
      
    }
    //自定义的验证手机号规则
    var checkMobile = (rule, value, cb) => {
        const regMobile= /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57]|)[0-9]{8}$/
 
        if(regMobile.test(value)){
          return cb()
        }

        cb(new Error('请输入合法的手机号'))
      
    }
    return {

 

      //接口 - 获取 - 表格
      url_get_table:'/role/employee/getRoles',
      //接口 - 新增 - 表格
      url_add_table:'//',  
      //接口 - 修改 - 表格
      url_edit_table:'//', 
      //接口 - 删除 - 表格
      url_delete_table:'//', 
      
      //接口 - 下拉框 列表 
      url_get_select1:'/role/getAll',


      //获取 - 表格数据 - 参数
      sendData:{
        pastureName: "",
        nameOrLoginName: "", 
        loginName: "",
        roleId: "",
      
        pageNum: 1,  //页码
        pageSize: 10,   //每页数量
        total:0,  //总页数
        pastureId: ""
      },

      tableLoading: false,
      //表格内容
      tableList:[
         { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123',roleList:[2,3] },
        { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123',roleList:[] },
        { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
        { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123' },
        { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123' },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
        // { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123' },
        // { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123' },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
        // { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123' },
        // { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123' },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
      ],


      
      pastureList:[
    
      ],

      roleSelectList:[

      ],


 


      addFormShow:false,
      addFormStatus: '',
      addFormTxt: {  edit: '修改用户',  create: '新增用户' },
      addForm:{
        username:'',password:'',email:'',mobile:''
      },

      addFormRules:{
        // username: [
        //   { required: true, message: '用户名必填', trigger: 'blur' },
        //   { min: 3, max: 5, message: '长度3-5个字符之间', trigger: 'blur' },
        // ],
        // password: [
        //   { required: true, message: '密码必填', trigger: 'blur' },
        //   { min: 3, max: 15, message: '长度3-15个字符之间', trigger: 'blur' },
        // ],
        // email: [
        //   { required: true, message: '邮箱必填', trigger: 'blur' },
        //   { validator: checkEmail, trigger: 'blur' },
        // ],
        mobile: [
          { required: true, message: '手机号必填', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],

      },

      setFormShow:false,
      setForm:{
        roleIdList:[]
      },

      roleList:[
        { "roleId": 1,   "roleName": "厂长",   "remark": ""  },
        {  "roleId": 34, "roleName": "副厂长",   "remark": ""  },
        {  "roleId": 35,  "roleName": "设备主管",   "remark": ""  },
        {  "roleId": 36,  "roleName": "维修工",   "remark": ""   },
      ]
       
    }
  },
  created(){
     //表格 - 初始化 
     // this.get_table_data()

      this.get_select_list1()
  },
  methods:{

 
    form_search(){
      var me = this
      console.log('请求表格列表sendData',me.sendData)
      this.get_table_data()

    },
  
    get_select_list1(){
        var me = this
        ajaxDataGet(me.url_get_select1, {"roleName": "",  "pageNum": 1,   "pageSize": 1000}).then(e => {
          console.log("下拉框1：",e)

          //打印请求成功结果
          if(e.data == null || e.data == undefined ||e.data.length == 0   ){
            me.roleList = []
          } else {
            me.roleList = e.data
          }

         
  
        })


        ajaxDataGet('/authdata/pasture', {  "pageNum": 1,   "pageSize": 1000}).then(e => {
          console.log("牧场下拉框1：",e)

          //打印请求成功结果
          if(e.data == null || e.data == undefined ||e.data.length == 0   ){
            me.pastureList = []
          } else {
            me.pastureList = e.data
          }
  
        })

        ajaxDataGet('/role/getAll', { "roleName": "",  "pageNum": 1,   "pageSize": 1000}).then(e => {
          console.log("角色下拉框1：",e)

          //打印请求成功结果
          if(e.data == null || e.data == undefined ||e.data.length == 0   ){
            me.roleSelectList = []
          } else {
            me.roleSelectList = e.data
          }
  
        })
    },

    
    //获取 表格
    get_table_data() {
 
     var me = this

     me.tableLoading = true
     console.log("sendData======>", me.sendData)

      ajaxDataGet(me.url_get_table,  me.sendData).then(e => {
        console.log("表格请求结果：",e)
          //打印请求成功结果
          if(e.data == null || e.data == undefined ||e.data.length == 0   ){
            me.tableList = []
          } else {
            me.tableList = e.data
            me.sendData.total = e.count;	// 总数
            me.sendData.pageNum = e.pageNum;	//页码
            me.sendData.pageSize = e.pageSize;	//每页数量
          }

          setTimeout(() => {
            me.tableLoading = false
          }, 100)
  
        })

       
    },

    //监听 pagesize 改变的事件
    change_size_page(item){
      console.log(item)
     // this.sendData.pageSize = item
      //  this.getUserList()
    },

    //监听 pagenum 改变的事件
    change_current_page(item){
      console.log(item)
       this.sendData.pageNum = item
       this.get_table_data()
    },


    form_add() {
      this.addFormStatus = 'create'
      this.addFormShow = true
      this.$nextTick(() => {
        this.$refs['addFormRef'].clearValidate()
      })
    },


    form_edit(row) {
      console.log('row', row)
      this.addForm = Object.assign({}, row) // copy obj
      this.addFormStatus = 'edit'
      this.addFormShow = true
      this.$nextTick(() => {
        this.$refs['addFormRef'].clearValidate()
      })
    },


    //监听关闭对话框
    add_dialog_close(){
       //内容重置
       this.$refs['addFormRef'].resetFields()
    },


    add_dialog_save() {
      
      this.$refs['addFormRef'].validate(valid => {
        //验证成功
        if (valid) {
          //发起请求

          //关闭弹窗
          this.$message({ type: 'success', message: '请求成功', duration: 2000 })
          this.addFormShow = false
        }
      })
    },

    edit_dialog_save(){
      this.addFormShow = false
    },

    form_delete(row) {
      var me = this

       me.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          me.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          me.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });


       
    },


    form_set(row) {
      var me = this 
      console.log('row', row)
      this.setForm = Object.assign({}, row) // copy obj
      var roleList = row.


      roleIdList
      me.setFormShow = true
      me.$nextTick(() => {
        me.$refs['setFormRef'].clearValidate()
      })
    },



    //监听关闭对话框
    set_dialog_close(){
       //内容重置
       this.$refs['setFormRef'].resetFields()
    },


    set_dialog_save() {
      var me = this
      console.log(me.setForm)




      var send_data = {
          "roleId":  me.setForm.roleIdList,
          "employeeId":  me.setForm.employeeId
      }

        //加载 - 发送编辑保存
        ajaxDataPost("/role/employee/add", send_data).then(e => {
            console.log("权限结果：",e)
              //打印请求成功结果
              if(e.code == 200  ){
                me.$message({ type: 'success', message: '设置成功！'  , duration: 2000 })
                //关闭弹窗
                me.setFormShow = false
                me.get_table_data()
              } else {
                me.$message({ type: 'error', message: '设置失败！' + e.msg, duration: 2000 })
              }
          })
  
    },
    reset_password(row) {
      var me = this

         var send_data = {
    
              "empId":  row.employeeId
          }

       me.$confirm('是否默认密码为Gm@5418#?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

           //加载 - 发送保存
           ajaxDataPost('/employee/password/reset', send_data).then(e => {
            console.log("重置结果：",e)
              //打印请求成功结果
              if(e.code == 200  ){
                me.$message({ type: 'success', message: '重置成功！'  , duration: 2000 })
                //关闭弹窗
                me.addFormShow = false
                me.get_table_data()
              } else {
                me.$message({ type: 'error', message: '重置失败！' + e.msg, duration: 2000 })
              }
          })
          // me.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        }).catch(() => {
          me.$message({
            type: 'info',
            message: '已取消重置'
          });          
        });


       
    },



    form_export() {
    //获取请求表格数据的参数
    //this.download.getdataListParm.parammaps = this.tableObj.getdataListParm.parammaps
    //请求表格
    // GetDataByName(this.download.getdataListParm).then(response => {
    //     if (response.data.list !== null) {
    //       this.download.list = response.data.list
    //     } else {
    //       this.download.list = []
    //     }
    //     var excelDatas = [
    //       {
    //         tHeader: ['表头1', '表头2', '表头3', '表头4',],
    //         filterVal: ['title1', 'title2', 'title3', 'title4'],
    //         tableDatas: this.download.list,
    //         sheetName: 'Sheet1'
    //       }
    //     ]
    //     json2excel(excelDatas, '表格大标题', true, 'xlsx')
    // })

    var excelDatas = [
        {
            tHeader: ['表头1', '表头2', '表头3', '表头4',],
            filterVal: ['title1', 'title2', 'title3', 'title4'],
            tableDatas: [ 
                {title1: "内容1",title2: "内容2",title3: "内容3",title4: "内容4"},
                {title1: "内容11",title2: "内容22",title3: "内容32",title4: "内容44"},
                {title1: "内容111",title2: "内容222",title3: "内容333",title4: "内容444"},
            ],
            sheetName: 'Sheet1'
        }
    ]
    json2excel(excelDatas, '表格大标题', true, 'xlsx')
}

     

  }
}
</script>
<!-- 加了scoped，则是仅在此组件里生效 -->
<style scoped>

</style>
