<template>
  <div class="mainBox">
    <div class="layerBox">
      <el-form ref="form" :model="form" :rules="loginRules" class="login-form" autocomplete="on" label-position="left" label-width="120px">
        <div class="formDiv">
          <!--选择角色 start------------------------------------------>
          <el-form-item label="所属角色：" :label-width="formLabelWidth" prop="role_id" class="custom-align-right">
            <div class="formLabelFloatBox">
              <el-select v-model="form.role_id" placeholder="请选择..">
                <el-option
                  v-for="item in role_idArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <!--选择角色 end------------------------------------------>
          <el-form-item label="登录账号：" :label-width="formLabelWidth" prop="user_name" class="custom-align-right">
            <el-input v-model="form.user_name" autocomplete="off" placeholder="请输入登录账号.."></el-input>
          </el-form-item>
          <div v-if="editId==''">
            <!--新密码 start------------------------------------------>
            <div class="PasswordBox">
              <el-form-item prop="password" label="登录密码："  class="custom-align-right">
                <div class="PasswordBody">
                  <el-input
                    :key="passwordType1"
                    ref="password1"
                    v-model="form.password"
                    :type="passwordType1"
                    placeholder="请输入密码"
                    name="password"
                    tabindex="2"
                    autocomplete="off"
                    @blur="capsTooltip2 = false"
                  />
                  <span class="show-pwd" @click="showPwd(1)">
                    <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
                  </span>
                </div>
              </el-form-item>
            </div>
            <!--新密码 end------------------------------------------>
            <!--新密码 start------------------------------------------>
            <div class="PasswordBox">
              <el-form-item prop="confirm_password" label="确认密码："  class="custom-align-right">
                <div class="PasswordBody">
                  <el-input
                    :key="passwordType2"
                    ref="password2"
                    v-model="form.confirm_password"
                    :type="passwordType2"
                    placeholder="请输入密码"
                    name="password"
                    tabindex="2"
                    autocomplete="off"
                    @blur="capsTooltip2 = false"
                  />
                  <span class="show-pwd" @click="showPwd(2)">
                    <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
                  </span>
                </div>
              </el-form-item>
            </div>
            <!--新密码 end------------------------------------------>
          </div>
          <el-form-item label="真实姓名：" :label-width="formLabelWidth" prop="real_name" class="custom-align-right">
            <el-input v-model="form.real_name" autocomplete="off" placeholder="请输入真实姓名.."></el-input>
          </el-form-item>
          <el-form-item label="手机号：" :label-width="formLabelWidth" class="custom-align-right">
            <el-input v-model="form.mobile" autocomplete="off" placeholder="请输入手机号.."></el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>  

    <div class="bottomBtnBox">
      <el-button type="info" @click="goList">返回</el-button>
      <el-button type="primary" @click="addData" v-if="editId==''">提交</el-button>
      <el-button type="primary" @click="editData" v-else>修改</el-button>
    </div>
  </div>
</template>

<script>
// 引入公用样式
import '@/styles/global.less';

export default {
  data() {
    // 配置验证规则：用于表单验证
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能低于6位！'))
      } else {
        callback()
      }
    }
    const validateEmpty = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    return {
      formLabelWidth:"120px",
      editId:"",
      form:{
        type_id:10000,//10000管理员
        user_name:"",//登录账号
        role_id:"",//角色id 查询角色列表获取
        password:"",//密码
        confirm_password:"",//确认密码
        real_name:"",//真实姓名
        mobile:"",//手机号
      },
      role_idArr:[],//角色id池
      //密码验证
      capsTooltip1: false,
      capsTooltip2: false,
      passwordType1: 'password',
      passwordType2: 'password',
      //配置from表单验证规则
      loginRules: { 
        user_name: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        role_id: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        confirm_password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        real_name: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //mobile: [{ required: true, trigger: 'blur', validator: validateEmpty }],
      }
    };
  },
  methods: {
    //1.表单收集 start ------------------------------------------------------------>
    // 切换密码框的显示与隐藏
    showPwd(num) {
      const passwordTypeKey = 'passwordType' + num; //动态生成 passwordType 的键
      const passwordRefKey = 'password' + num; //动态生成 password 的引用
      // 切换密码类型
      if (this[passwordTypeKey] === 'password') {
        this[passwordTypeKey] = ''; //显示密码
      } else {
        this[passwordTypeKey] = 'password'; //隐藏密码
      }
      // 使用 $nextTick 聚焦到对应的密码输入框
      this.$nextTick(() => {
        this.$refs[passwordRefKey].focus(); //聚焦到对应的密码输入框
      });
    },
    //获得角色列表池
    getRoleList(){
      let data = {
        page:1,
        pageSize:100
      }
      this.$store.dispatch('userRole/roleList',data).then(res=>{
        this.role_idArr = res.data.rows.map(item => ({
          value: item.id,
          label: item.role_name 
        }));
      }).catch(error=>{
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //重置表单
    clearData(){
      
    },
    //表单收集 end ------------------------------------------------------------>
    //2.提交表单 start ------------------------------------------------------------>
    //提交表单
    addData(){
      console.log(this.form);
      //1.先验证用户是否已经存在
      this.$store.dispatch('userMember/verifyUserInfo',{user_name:this.form.user_name}).then(res=>{
        if(res.code==0){
          //如果code为0表示用户不存在，提交表单
          this.$store.dispatch('userMember/createUser',this.form).then(res=>{
            console.log(res);
            this.$message({
              type: 'success',
              message: '用户添加成功！'
            });
            this.goList();
          })
        }else if(res.code==200){
          //如果code==200 表示用户存在，阻止进一步提交
          this.$message({
            type: 'warning',
            message: '该账号已被注册，请更换其他账号！'
          });
        }
      }).catch(error=>{
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //提交表单 start ------------------------------------------------------------>
    //3.编辑表单 start ------------------------------------------------------------>
    //获得用户信息
    getUserInfo(){
      this.$store.dispatch('userMember/getUser',{id:this.editId}).then(res=>{
        console.log(res);
        //回显数据
        this.form.type_id = res.data.type_id;
        this.form.user_name = res.data.user_name;
        this.form.role_id = res.data.role_id;
        this.form.real_name = res.data.real_name;
        this.form.mobile = res.data.mobile;

      }).catch(error=>{
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //修改用户
    editData(){
      this.$store.dispatch('userMember/verifyUserInfo',{id:this.editId,user_name:this.form.user_name}).then(res=>{
        if(res.code==0){
          this.form.id = this.editId;
          delete this.form.password;
          delete this.form.confirm_password;
          //如果code为0表示用户不存在，提交表单
          this.$store.dispatch('userMember/updateUser',this.form).then(res=>{
            console.log(res);
            this.$message({
              type: 'success',
              message: '用户添加成功！'
            });
            this.goList();
          })
        }else if(res.code==200){
          //如果code==200 表示用户存在，阻止进一步提交
          this.$message({
            type: 'warning',
            message: '该账号已被注册，请更换其他账号！'
          });
        }
      }).catch(error=>{
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //编辑表单 end ------------------------------------------------------------>
    goList(){
      this.$router.push({
        path: '/userList',
      });
    },
  },
  mounted(){
    this.getRoleList();
    //判断是新建还是回显
    if(this.$route.query.id!=undefined){
      this.editId = this.$route.query.id;
      console.log("编辑用户！")
      this.getUserInfo();
    }else{
      console.log("添加用户！")
    }
    
  }
};
</script>

<style scoped lang="less">
  .PasswordBox {
    display: flex;
    align-items: center;
    .el-form-item {
      flex: 1;
    }
    .PasswordTitle {
      width:120px;
      text-align: right;
      margin-right: 10px;
      margin-bottom:22px;
    }
    .PasswordBody {
      flex: 1;
      display: flex;
      align-items: center;
    }
    .show-pwd {
      margin-left: 10px;
    }
  }
  //执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
  ::v-deep .custom-form-item > .el-form-item__label {
    line-height: 140px !important;
  }
  ::v-deep .custom-textarea .el-textarea__inner {
    resize: none; /* 禁止用户拖拽调整大小 */
  }
  ::v-deep .custom-align-right .el-form-item__label {
    text-align: right; /* 设置标签文字右对齐 */
  }
  ::v-deep .el-select {
    width: 100%; /* 禁止用户拖拽调整大小 */
  }
  //执行v-deep穿透scope选择器 end------------------------------------------------------------>*/
</style>
