<template>
  <div class="admin">
    <el-button @click="add" plain type="success" style="float: right;margin-bottom:10px;" v-if="!$store.state.readonly">新增角色</el-button>
    <el-form ref="searchFrom" :model="searchFrom" inline label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="searchFrom.user_name"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchFrom.status" placeholder="请选择用户状态" @change="getList">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" :value="0"></el-option>
              <el-option label="冻结" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="searchFrom.role_id" placeholder="请选择角色类型" @change="getList">
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="data in roleList"
                :key="data.id"
                :label="data.name"
                :value="data.id" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="getList">搜索</el-button>
          </el-form-item>
    </el-form>
    <!--<div class="head clear-both">-->
      <!---->
    <!--</div>-->
    <el-table
      :data="adminList"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="账号ID">
      </el-table-column>
      <el-table-column
        prop="user_name"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
      <el-table-column
        label="状态">
        <template slot-scope="scope">
          {{scope.row.status | adminStatus}}
        </template>
      </el-table-column>
      <el-table-column
        prop="desc"
        label="备注">
      </el-table-column>
      <el-table-column
        prop="last_login_at"
        label="最后登陆时间" sortable>
      </el-table-column>
      <el-table-column
        v-if="!$store.state.readonly"
        label="操作">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            width="280">
            <div style="text-align: center">
              <el-button size="mini" plain type="primary" @click="edit(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="warning" plain @click="editPW(scope.row)">
                修改密码
              </el-button>
              <el-button size="mini" type="danger" plain @click="del(scope.row)" v-if="$store.state.deletePermission">
                删除
              </el-button>
            </div>
            <el-button slot="reference" size="mini" type="text" >操作</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <page :nowPage="nowPage" :total="total" :limit="limit" @pageChange="onPageChange" @sizeChange="onSizeChange"/>
    <el-dialog
      :title="dialog.title"
      center
      append-to-body
      :visible.sync="dialog.show"
      width="30%">
      <el-form ref="form" :rules="dialog.rules" :model="dialog.form" label-width="80px">
        <el-form-item label="账号" prop="username" v-if="dialog.dialogType === 0">
          <el-input v-model="dialog.form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.dialogType === 2 || dialog.dialogType === 0">
          <el-input type="password" v-model="dialog.form.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="surePassword" v-if="dialog.dialogType === 2 || dialog.dialogType === 0 ">
          <el-input type="password" v-model="dialog.form.surePassword"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id" v-if="dialog.dialogType !== 2">
          <el-select v-model="dialog.form.role_id" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简述" prop="desc" v-if="dialog.dialogType !== 2">
          <el-input v-model="dialog.form.desc"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="dialog.dialogType === 1">
          <el-select v-model="dialog.form.status" placeholder="请选择">
            <el-option
              v-for="item in dialog.select"
              :key="item.code"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" @click="onSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getAdminListApi,editAdminListApi,addAdminListApi,delAdminListApi,editPasswordApi,getRoleListApi} from "../../service/api";
  import {ADMINSTATUS} from "../../util/wordbook";
  import page from '../framework/page'
  import md5 from 'js-md5';
  export default {
    name: "admin",
    components:{
      page
    },
    data(){
      // 表单验证
      let usernameCheck=(rule, value, callback)=>{
        if (value === '' && this.dialog.dialogType === 0) {
          callback(new Error('请输入账号'));
        } else {
          callback();
        }
      };
      let passCheck= (rule, value, callback) => {
        if (value === '' && (this.dialog.dialogType === 0 || this.dialog.dialogType === 2 )) {
          callback(new Error('请输入密码'));
        } else {
          if(this.dialog.form.surePassword !== '' && (this.dialog.dialogType === 0 || this.dialog.dialogType === 2 )){
            this.$refs['form'].validateField('surePassword');
          }
          callback();
        }
      };
      let surePassCheck= (rule, value, callback) => {
        if(this.dialog.dialogType === 0 || this.dialog.dialogType === 2 ){
          if (value === '') {
            callback(new Error('请再次输入密码'));
          } else if (value !== this.dialog.form.password) {
            callback(new Error('两次输入密码不一致!'));
          }else{
            callback();
          }
        } else {
          callback();
        }
      };
      let roleIdCheck= (rule, value, callback) => {
          if(this.dialog.dialogType === 0 || this.dialog.dialogType === 1 ){
            if (value === '') {
              callback(new Error('请输入角色'));
            }
          }else{
            callback()
          }
      };
      let descCheck= (rule, value, callback) => {
        if(this.dialog.dialogType === 0 || this.dialog.dialogType === 1 ){
          if (value === '') {
            callback(new Error('请输入简述'));
          }
        }else{
          callback()
        }
      };
      return {
        nowPage:1,
        total:0,
        limit: 10,
        adminList:[],
        searchFrom:{
          user_name: '',
          status: '',
          role_id:""
        },
        dialog:{
          dialogType:0,
          title:'新增账号',
          show:false,
          select:[{
            code:0,
            value:ADMINSTATUS['0']
          },{
            code:1,
            value:ADMINSTATUS['1']
          }],
          rules:{
            username:[{ validator: usernameCheck, trigger: 'blur' }],
            password:[{ validator: passCheck, trigger: 'blur' }],
            surePassword:[{ validator: surePassCheck, trigger: 'blur' }],
            role_id:[{ validator: roleIdCheck, trigger: 'blur' }],
            desc:[{ validator: descCheck, trigger: 'blur' }],
          },
          form:{
            id:'',
            username:'',
            password:'',
            surePassword:'',
            role_id:'',
            status:0,
            desc:''
          },
        },
        roleList: []
      }
    },
    filters:{
      adminStatus:function (value) {
        return ADMINSTATUS[value]
      },
    },
    created(){
       if(this.$route.query.roleId){
         this.searchFrom.role_id = this.$route.query.roleId
       }
      this.getList();
      this.getRoleList();
    },
    methods:{
      getRoleList(){
        getRoleListApi({page: 1,limit: 100}).then(res=>{
          if (res) {
            this.roleList = res.list;
          }
        })
      },
      onPageChange(val){
        this.nowPage = val;
        this.getList()
      },
      onSizeChange(val){
        this.nowPage = 1;
        this.limit = val;
        this.getList()
      },
      getList(){
        let json = {
          limit: this.limit,
          page: this.nowPage
        }
        if (this.searchFrom.user_name){
          json.user_name = this.searchFrom.user_name
        }
        if (this.searchFrom.status !== ''){
          json.status = this.searchFrom.status
        }
         if (this.searchFrom.role_id !== ''){
          json.role_id = this.searchFrom.role_id
        }
        getAdminListApi(json).then(res=>{
          if(this.searchFrom.role_name !== ''){
            switch(this.searchFrom.role_name){
              case '超级管理员':
              res.list=res.list.filter(function(item,i){
                 return item.role_name == "超级管理员"
              });
              break;
              case '管理员':
              res.list=res.list.filter(function(item,i){
                 return item.role_name == "管理员"
              });
              break;
            }
          }
          this.adminList = res.list;
          this.total=Number(res.total)
          this.$store.commit('mainCanShow')
        })
      },
      editPW(data){
        this.dialog.form.id = data.id;
        this.dialog.dialogType = 2;
        this.dialog.title = '修改密码';
        this.dialog.form.password = '';
        this.dialog.form.surePassword = '';
        this.dialog.show = true;
      },
      edit(data){
        this.dialog.show = true;
        this.dialog.dialogType=1;
        this.dialog.form.id = data.id;
        this.dialog.title = '编辑';
        this.dialog.form.username = data.user_name;
        this.dialog.form.password = '';
        this.dialog.form.status = data.status;
        this.dialog.form.role_id = data.role_id;
        this.dialog.form.desc = data.desc
      },
      add(){
        this.dialog.show = true;
        this.dialog.dialogType=0;
        this.dialog.form.id = '';
        this.dialog.title = '新增';
        this.dialog.form.username = '';
        this.dialog.form.status = 0;
        this.dialog.form.password = '';
        this.dialog.form.role_id = '';
        this.dialog.form.desc = ''
      },
      del(data){
        this.$confirm('此操作将删除该账号?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delAdminListApi(data.id).then(res=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
          this.getList()
        });
      },
      onSub(){
        // this.$refs['form'].validate((valid) => {
        //   if(valid){
            let dia = this.dialog;
            if(dia.dialogType === 1){
              let json = {
                role_id:dia.form.role_id,
                desc:dia.form.desc,
                status:dia.form.status
              };
              this.$confirm('此操作将编辑该账号?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                editAdminListApi(dia.form.id,json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })
            }else if(dia.dialogType === 0){
              let json = {
                role_id:dia.form.role_id,
                desc:dia.form.desc,
                passwd:md5(dia.form.password),
                username:dia.form.username
              };
              this.$confirm('此操作将添加新账号?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                addAdminListApi(json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })
            }else if(dia.dialogType === 2){
              let json = {
                passwd_new:md5(dia.form.password)
              }
              this.$confirm('此操作将修改此账号密码?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                editPasswordApi(dia.form.id,json).then(()=>{
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                  dia.show = false;
                  this.getList()
                })
              })
            }
        //   }
        // })
      }
    }
  }
</script>

<style scoped lang="less">
  .admin{
    .head{
      margin-bottom: 10px;
    }
    width: 100%;
    padding: 20px 0;
    .page-div{
      text-align: center;
      padding-top: 20px
    }
  }
  .clear-both{
  &:after{
     content: '';
     display: block;
     clear: both;
   }
  }
</style>
