<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.name }}</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="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="name">
          <el-input v-model="adminUserInfo.name " placeholder="名称" style="width: 40%;"></el-input>
        </el-form-item>
        <el-form-item label="角色人员">
          <el-transfer v-model="value" filterable :titles="['待选人员', '已选人员']" :data="data"></el-transfer>
        </el-form-item>
        <el-form-item label="权限" style="margin-top: 40px;">
          <el-tree ref="tree" :check-strictly="true" :data="data1" show-checkbox node-key="id" default-expand-all :props="defaultProps">
          </el-tree>
        </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 {
    GetInfo,
    GetUserList,
    UsersCreate,
    UsersUpdate,
    UsersDelete,
    GetMenue
  } from '@/api/role'
  import { GetUserListByAdminSimple } 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 {
        data1: [],
        data: [],
        value: [],

        defaultProps: {
          children: 'children',
          label: 'label'
        },

        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: {
          name: [{
            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()
      this.getadmin()
      this.getmenue()
    },
    methods: {
      getmenue() {
        GetMenue().then(res => {
          this.data1 = res.data || [];
        });
      },
      getadmin() {
        GetUserListByAdminSimple({ PageSize: 9999999, PageIndex: 1, Sort: [{ Field: 'id', Type: 0 }] }).then(res => {
          var data = res.data || [];
          data = data.map(o => {
            return {
              key: o.id,
              label: o.fullName
            }
          });
          this.data = data;
        });

      },
      closeClassDialog() {
        this.title = '添加'
        this.buttonText = '立即创建'
        this.GetUser();
      },
      submitForm(formName) {
        var _this = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.adminUserInfo.users = _this.value || [];
            _this.adminUserInfo.menues = _this.$refs.tree.getCheckedKeys() || [];
            if (_this.title == '添加') {
              _this.adminUserInfo.addTime = formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
              UsersCreate(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() {
        GetUserList(this.query).then(res => {
          this.userList = res.data.data
          this.Count = res.data.total
        })
      },
      currentchange(page) {
        this.query.PageIndex = page;
        this.GetUser();
      },
      closeClassDialogT() {
        this.dialogClassIVIsibleT = false
      },


      submitFormT(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var postdata = Object.assign({}, this.ruleForm);
            if (this.ruleForm.id) {
              UsersUpdate(postdata).then(res => {
                if (res.data.code == 200) {
                  this.$notify({
                    title: 'Success',
                    message: res.data.message,
                    type: 'success',
                    duration: 1000
                  })
                  this.dialogClassIVIsibleT = false

                }
              })
            }
            else {
              UsersCreate(postdata).then(res => {
                if (res.data.code == 200) {
                  this.$notify({
                    title: 'Success',
                    message: res.data.message,
                    type: 'success',
                    duration: 1000
                  })
                  this.dialogClassIVIsibleT = false

                }
              })
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleCommand(value, val) {
        let that = this;
        if (value == "update") {
          GetInfo(val.id).then(res => {
            that.dialogClassIVIsible = true;
            that.$nextTick(function () {

              that.adminUserInfo = res.data.data
              if (res.data.data.users) {
                that.value = res.data.data.users;
              }
              if (res.data.data.menues) {
                that.$refs.tree.setCheckedKeys(res.data.data.menues);
              }
              that.title = '编辑信息'
              that.buttonText = '保存'

            });

          });
        }
        if (value == 'updatePassword') {
          that.ruleForm.UserId = val.id
          ththatis.dialogClassIVIsibleT = true
        }
        if (value == "del") {
          that.$confirm('确定删除该管理员？', '消息', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            callback: (action) => {
              if (action == "confirm") {
                UsersDelete({
                  ids: val.id
                }).then(res => {
                  if (res.data.code == 200) {
                    that.$notify({
                      title: '成功',
                      message: res.data.message,
                      type: 'success'
                    });
                    that.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>