<template>
  <div class="app-container">
    <div class="seetingsDiv" style="">
      <el-button type="primary" @click="dialogClassIVIsible=true">添加
      </el-button>
    </div>
    <el-table :data="userList" id="QuestionTable" border
      style="width: 100%;border-radius: 5px;box-shadow: 0 0 10px #efefef;margin-top: 10px;" :stripe='true'>
      <el-table-column type="index" prop="date" width="50" align="center"></el-table-column>
      <el-table-column prop="date" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.fullName }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="date" label="电话号码">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.phone " placement="top-start">
            <span>{{ scope.row.phone1 }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="登录账号">
      </el-table-column>

      <el-table-column prop="type" label="类型">
        <template slot-scope="scope"> 
            <span>{{ scope.row.type == 0?'超级管理员':'一般管理员' }}</span> 
        </template>
      </el-table-column>


      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-dropdown @command="(e)=>{handleCommand(e,scope.row)}">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="update">编辑</el-dropdown-item>
                 <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
                <el-dropdown-item command="del" v-if="scope.row.username!='admin'">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background @current-change="currentchange"
      style="position:static;bottom: 3px;text-align: center;margin-top: 5px;" :page-size="this.query.PageSize"
      layout="total,prev, pager, next" :total="Count">
    </el-pagination>
    <el-dialog :title="title" :visible.sync="dialogClassIVIsible" @close="closeClassDialog" width="450"
      :close-on-click-modal="false">
      <el-form ref="adminUserInfo" :rules="rules" :model="adminUserInfo" label-width="90px" style="margin-left: 40px;">
        <el-form-item label="名称" prop="fullName">
          <el-input v-model="adminUserInfo.fullName " placeholder="请输入管理员名称" style="width: 40%;"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" >
          <el-input v-model="adminUserInfo.phone " placeholder="请输入联系方式" style="width: 40%;" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" style="margin-top: 40px;" prop="username">
          <el-input v-model="adminUserInfo.username" placeholder="请输入登录账号" style="width: 40%;"></el-input>
        </el-form-item>
        <el-form-item label="类型" style="margin-top: 40px;" prop="type">
          <el-radio-group v-model="adminUserInfo.type">
            <el-radio :label="0">超级管理员</el-radio>
            <el-radio :label="5">一般管理员</el-radio> 
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="title=='添加管理员'">
          <el-input v-model="adminUserInfo.password " placeholder="请输入密码" show-password style="width: 40%;"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right;">
          <el-button @click="dialogClassIVIsible=false">取消</el-button>
          <el-button type="primary" @click="submitForm('adminUserInfo')">{{buttonText}}</el-button>
        </el-form-item>
      </el-form>

      <div style="clear: both;"></div>
    </el-dialog>


    <el-dialog title="修改密码" :visible.sync="dialogClassIVIsibleT" @close="closeClassDialogT" width="450"
      :close-on-click-modal="false">
      <el-form :model="ruleForm" status-icon :rules="rulesT" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="width: 320px;">
        <el-form-item label="密码" prop="Password">
          <el-input type="password" v-model="ruleForm.Password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitFormT('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <div style="clear: both;"></div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    GetUserList,
    UsersCreate,
    UsersUpdate,
    UsersDelete,
    AccountRegister,
    GetUserListByAdmin,
    UpdateCurrentPasswordById
  } from '@/api/user'
  import {
    formatTime
  } from '@/utils/util.js'
  export default {
    data() {
      var checkPhone = (rule, value, callback) => {
        const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
        if (!value) {
          return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(+value)) {
            callback(new Error('请输入数字值'))
          } else {
            if (phoneReg.test(value)) {
              callback()
            } else {
              callback(new Error('电话号码格式不正确'))
            }
          }
        }, 100)
      }


      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.Password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        title: '添加管理员',
        buttonText: '立即创建',
        userList: [],
        dialogClassIVIsible: false,
        dialogClassIVIsibleT:false,
        adminUserInfo: {
          username: "",
          password: "",
          // type: 4,
          fullName: "",
          // remark: "",
          phone: "",
          // sex: "",
          // card: "",
          // address: "",
          // birthday: "",
          status: 1,
        },

        ruleForm: {
          UserId:0,
          Password: '',
          checkPass: '',
        },
        rulesT: {
          Password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
        },
        Count: 0,
        query: {
          UserTypeEnum: 5, //0：管理员，1普通用户
          PageIndex: 1,
          PageSize: 10,

        },
        rules: {
          fullName: [{
            required: true,
            message: '请输入管理员名称',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '请输入联系方式',
            trigger: 'blur'
          }],
          username: [{
            required: true,
            message: '请输入登录账号',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            trigger: 'blur',
            validator: checkPhone
          }],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请输选择用户类型',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.GetUser()
    },
    methods: {

      closeClassDialog() {
        this.title = '添加管理员'
        this.buttonText = '立即创建'
        this.GetUser();
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.title == '添加管理员') {
              this.adminUserInfo.addTime = formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
              AccountRegister(this.adminUserInfo).then(res => {
                this.$notify({
                  title: '成功',
                  message: res.data.message,
                  type: 'success'
                });
                // this.$confirm(res.data.message, '消息')
                this.dialogClassIVIsible = false
              })
            } else {
              this.adminUserInfo.updateTime = formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
              this.adminUserInfo.status = 1
              UsersUpdate(this.adminUserInfo).then(res => {
                this.$notify({
                  title: '成功',
                  message: res.data.message,
                  type: 'success'
                });
                // this.$confirm(res.data.message, '消息')
                this.dialogClassIVIsible = false
              })
            }

          } else {
            return false;
          }
        });
      },

      GetUser() {
        GetUserListByAdmin(this.query).then(res => {
          this.userList = res.data.data.rows.map(t => {
            if (t.phone) {
              t.phone1 = t.phone.replace(t.phone.substring(3, 7), '****')
            }
            return t
          })
          this.Count = res.data.data.total
          console.log(this.userList)
        })
      },
      currentchange(page) {
        this.query.PageIndex = page;
        this.GetUser();
      },
      closeClassDialogT(){
        this.dialogClassIVIsibleT=false
      },


      submitFormT(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            UpdateCurrentPasswordById({UserId:this.ruleForm.UserId,Password:this.ruleForm.Password}).then(res=>{
              if (res.data.code==200) {
                this.$notify({
                  title: 'Success',
                  message: res.data.message,
                  type: 'success',
                  duration: 1000
                })
                this.dialogClassIVIsibleT=false
                // setTimeout(()=>{
                //   this.$store.dispatch('user/logout')
                //   this.$router.push(`/login?redirect=${this.$route.fullPath}`)
                // },1000)

              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleCommand(value, val) {
        let that = this;
        if (value == "update") {
          this.dialogClassIVIsible = true;
          this.adminUserInfo = val
          this.title = '编辑信息'
          this.buttonText = '保存'
        }
        if(value=='updatePassword'){
          this.ruleForm.UserId=val.id
          this.dialogClassIVIsibleT=true
        }
        if (value == "del") {
          this.$confirm('确定删除该管理员？', '消息', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            callback: (action) => {
              if (action == "confirm") {
                UsersDelete({
                  ids: val.id
                }).then(res => {
                  if (res.data.code == 200) {
                    this.$notify({
                      title: '成功',
                      message: res.data.message,
                      type: 'success'
                    });
                    this.GetUser();
                  }
                });
              }
            },
          })

        }
      },
    }
  }
</script>

<style scoped>
  .seetingsDiv {
    width: 100%;
    height: 60px;
    background: #efefef;
    border-radius: 5px;
    box-shadow: 0 0 5px #cdcdcd;
  }

 .seetingsDiv button {
    background-color: #304156;
    border: 0px;
    margin-left: 10px;
    box-shadow: 0 0 5px #cdcdcd;
    float: left;
    margin-top: 12px;
    margin-right: 10px;
  }
</style>
