<template>
  <el-container>
    <el-main>
   

      <template>
        <el-card style="margin-top:10px" class="box-card">
          <p>用户列表</p>
          <el-table
            :data="allUsers.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase() ))"
            style="width: 100%"
          >
            <el-table-column
              label="ID"
              width="80"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="账号"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="姓名"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
              <el-table-column
              label="状态"
              width="80"
            >
              <template slot-scope="scope">

                <span v-if="!scope.row.locked">启用</span>
                <span v-if="scope.row.locked">禁用</span>
              </template>
            </el-table-column>

            <el-table-column
              label="角色"
              width="180"
            >
              <template slot-scope="scope">
                <el-badge v-for="role in scope.row.sysRoles" :key="role.id">  <el-tag size="small">{{ role.description }}</el-tag></el-badge>
              </template>
            </el-table-column>

            <el-table-column
              label="备注"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="更新时间"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.updateTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">

            <template slot="header" slot-scope="scope">
              <el-input
                v-model="search"
                size="mini"
                placeholder="输入账号搜索"/>
            </template>
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button>
                <el-button
                  size="mini"
                  type="primary"
                  @click="changePass(scope.$index, scope.row)"
                >修改密码</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog
            title="修改账号"
            :visible.sync="changUserDiaVisible"
            width="70%" :close-on-click-modal="false" :show-close="false"
          >
            <el-container>
              <el-main>
                <el-form ref="updateUserForm" style="margin-top:10px" :model="editUser" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">

                  <el-form-item label="账号" prop="username">
                    <el-input :disabled="true" v-model="editUser.username" />
                  </el-form-item>

                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="editUser.name" autocomplete="off" />
                  </el-form-item>
                  
                  <el-form-item label="状态">
                    <el-switch v-model="editUser.locked" inactive-color="#13ce66" active-color="#ff4949" active-text="禁用" inactive-text="正常"> </el-switch>
                  </el-form-item>
                  
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="editUser.remark" autocomplete="off" />
                  </el-form-item>
                  <el-form-item>
                    <el-alert title="角色" type="info" :closable="false">
                      <el-checkbox-group v-model="editUser.sysRoles" size="mini">
                        <el-checkbox v-for="role in roles" :key="role.id" border="" :label="role.name">{{ role.description }}</el-checkbox>
                      </el-checkbox-group>
                    </el-alert>

                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="updateUser('updateUserForm')">确认</el-button>
                    <el-button @click="cancel()">取消</el-button>
                  </el-form-item>
                </el-form>
              </el-main>
            </el-container>
          </el-dialog>

           <el-dialog
            title="修改账号密码"
            :visible.sync="changPassDiaVisible"
            width="70%" :close-on-click-modal="false" :show-close="false"
          >
            <el-container>
              <el-main>
                <el-form ref="updatePassForm" style="margin-top:10px" :model="changePassUser" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">

                  <el-form-item label="账号" prop="username">
                    <el-input :disabled="true" v-model="changePassUser.username" />
                  </el-form-item>

                  <el-form-item label="密码" prop="pass">
                    <el-input type="password" v-model="changePassUser.password" autocomplete="off" />
                  </el-form-item>
                    <el-form-item label="确认密码" prop="checkPass">
                    <el-input type="password" v-model="changePassUser.checkPass" autocomplete="off" />
                  </el-form-item>
                  
                  
                  <el-form-item>
                    <el-button type="primary" @click="updatePass('updatePassForm')">确认</el-button>
                    <el-button @click="cancel()">取消</el-button>
                  </el-form-item>
                </el-form>
              </el-main>
            </el-container>
          </el-dialog>
        </el-card>
      </template>

    </el-main>
  </el-container>

</template>


<script>

export default {
  data() {
    var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.changePassUser.checkPass !== '') {
            this.$refs.updatePassForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.changePassUser.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    return {
      changUserDiaVisible: false,
      changPassDiaVisible:false,
      role: {
        description: '',
        name: '',
        authorities: []
      },
      search:'',
      editUser: {
        description: '',
        name: '',
        sysRoles: []
      },
      changePassUser:{
        username:'',
        password:'',
        checkPass:'',
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 5 个字符之间', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 4, max: 12, message: '账号长度在 4到 12 个字符之间', trigger: 'blur' }
        ],
        remark: [
            { required: false, message: '', trigger: 'blur' },
             { min: 0, max:255, message: '备注不能多于255个字符', trigger: 'blur' } 
          ],
        pass: [
            { validator: validatePass, trigger: 'blur' },
             { min: 4, max: 12, message: '密码长度在4-12个字符之间', trigger: 'blur' }
          ],
        checkPass: [
            { validator: validatePass2, trigger: 'blur' },
            { min: 4, max: 12, message: '密码长度在4-12个字符之间', trigger: 'blur' }
          ],
      }
    }
  },
  computed: {
    allUsers(){
      return this.$store.getters.allUsers
    },
    roles() {
      return this.$store.getters.allRoles
    },
    // authorities() {
    //   return this.$store.getters.allAuthorities
    // }
  },
  created() {
    console.log('created')
    this.$store.dispatch('user/getAllUsers')
    // this.$store.dispatch('authority/getAllAuthorities')
  },
  methods: {
    changePass(index,row){
       console.log(index, row)
       this.changePassUser=row
       this.changPassDiaVisible=true
    },
    handleEdit(index, row) {
      console.log(index, row)
      this.editUser = row

      var roleList = new Array()
      for (var i in row.sysRoles) {
        console.log('role', row.sysRoles[i])
        roleList.push(row.sysRoles[i].name)
      }
      console.log('roleList', roleList)
      this.editUser.sysRoles = roleList
      this.changUserDiaVisible = true
      console.log('editUser',this.editUser)
    },
    updatePass(formName){
      console.log('start to update user password-1',this.changePassUser)
       this.$refs[formName].validate((valid) => {
        if (valid) {
           console.log('start to update user password0',this.changePassUser)
           var user={};
           user.username=this.changePassUser.username
           user.password=this.changePassUser.password
           
            this.$store.dispatch('user/updateUserPassword', user).then(res => {
              if(res.data.success){
                this.$message({ message: '修改用户密码成功', type: 'success' })
              }
            }).catch(err=>{

            })
        }})
    },
    updateUser(formName) {
      console.log('start to update user-1', this.editUser)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('start to update user0', this.editUser)

          this.$store.dispatch('user/updateUser', this.editUser).then(res => {
            if (res.data.success) {
              this.$message({ message: '修改用户信息成功', type: 'success' })
              this.editUser=res.data.data
              var roleList = new Array()
              for (var i in this.editUser.sysRoles) {
                console.log('role', this.editUser.sysRoles[i])
                roleList.push(this.editUser.sysRoles[i].name)
              }
              console.log('roleList', roleList)
              this.editUser.sysRoles = roleList
              this.$store.dispatch('user/getAllUsers')
            } else {
              console.log('修改用户信息失败!', res)
              this.$message({ message: '修改用户信息失败!' + res.data.info, type: 'error' })
            }
          }
          ).catch(err=>{
            this.$message({ message: '修改用户信息失败!' + res.data.info, type: 'error' })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.$store.dispatch('role/getAllRoles')
     this.$store.dispatch('user/getAllUsers')
      this.changUserDiaVisible = false
      this.changPassDiaVisible=false
    },
    handleDelete(index, row) {
      console.log(index, row)
      this.$confirm('即将永久删除账号:' + row.username + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('user/deleteUser', row.username).then(res => {
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.$store.dispatch('user/getAllUsers')
          } else {
            this.$message({ message: '删除失败!' + res.data.info, type: 'error' })
          }
        }).catch(error => {
          this.$message({ message: '删除失败!' + res.data.info, type: 'error' })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '删除失败!'
        })
      })
    },
   
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
