<!-- 用户列表 -->
<template>
  <div class="userbox">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title">
        <p>用户管理</p>
      </div>
      <p class="baselistbox_top_line"></p>
      <div class="baselistbox_top_search">
        <div class="left_search">
          <div class="btnbox2" @click="adduser">新增</div>
        </div>
        <div class="right_search">
          <div class="firstsearch">
            <el-input
              v-model="username"
              size="mini"
              placeholder="请输入用户名称"
            ></el-input>
          </div>
          <div class="btnbox" @click="searchChange">查询</div>
        </div>
      </div>
    </div>
    <div class="baselistbox_table">
      <el-table
        v-loading="loading"
        :data="userlist"
        stripe
        style="width: 100%"
        height="560"
        :default-sort="{ prop: 'user_name', order: 'create_time' }"
      >
        <el-table-column prop="user_name" sortable label="用户名">
        </el-table-column>
        <el-table-column prop="create_time" sortable label="创建时间">
        </el-table-column>
        <el-table-column prop="is_ziguang" label="是否专家">
          <template slot-scope="scope" :title="scope.row.is_ziguang">{{
            scope.row.is_ziguang ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="allocation(scope.row)"
              >分配权限</span
            >
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="
                passdialogVisible = true;
                u_id = scope.row.uid;
              "
              >修改密码</span
            >
            <span
              style="color: red; margin-right: 15px; cursor: pointer"
              @click="deluser(scope.row.uid)"
              >删除</span
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next,sizes,jumper"
          :total="totalnum"
          :page-sizes="[1, 2, 3, 5]"
          :page-size="page_size"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-size.sync="page"
          :key="pagekey"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="创建用户"
      :visible.sync="dialogVisible"
      width="580px"
      :close-on-click-modal="false"
    >
      <div class="userinfobox">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input
              size="mini"
              v-model="ruleForm.username"
              :maxlength="10"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input
              size="mini"
              type="password"
              v-model="ruleForm.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="sumbitinfo" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="修改密码"
      :visible.sync="passdialogVisible"
      width="580px"
      :close-on-click-modal="false"
    >
      <div class="userinfobox">
        <el-form
          :model="ruleForm2"
          :rules="rules2"
          ref="ruleForm2"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="新密码" prop="password">
            <el-input
              size="mini"
              v-model="ruleForm2.password"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="secpassword">
            <el-input
              size="mini"
              type="password"
              v-model="ruleForm2.secpassword"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passdialogVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button type="primary" @click="amendpass" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="juridialogVisible"
      width="580px"
      :close-on-click-modal="false"
    >
      <div class="jurbox">
        <el-tree
          :data="jurdata"
          show-checkbox
          node-key="pur_id"
          :props="defaultProps"
          ref="tree"
          :default-checked-keys="defKeys"
        >
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="juridialogVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button type="primary" @click="authority" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    var validatePass2 = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入用户密码"));
      } else if (value.length < 6) {
        callback(new Error("用户密码最少输入6位"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 6) {
        callback(new Error("密码最少输入6位"));
      } else if (value != this.ruleForm2.password) {
        callback(new Error("俩次密码输入不一致"));
      } else {
        callback();
      }
    };
    return {
      username: "",
      page: 1,
      page_size: 1,
      pagekey: 1,
      userlist: [],
      totalnum: 10,
      loading: false,
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: {
          required: true,
          message: "请输入用户名称",
          trigger: "blur",
        },
        password: {
          required: true,
          validator: validatePass2,
          trigger: "blur",
        },
      },
      dialogVisible: false,
      juridialogVisible: false,
      jurdata: [],
      defaultProps: {
        children: "children",
        label: "purview_name",
        id: "pur_id",
      },
      defKeys: [],
      passdialogVisible: false,
      ruleForm2: {
        password: "",
        secpassword: "",
      },
      rules2: {
        password: {
          required: true,
          validator: validatePass2,
          trigger: "blur",
        },
        secpassword: {
          required: true,
          validator: validatePass,
          trigger: "blur",
        },
      },
      u_id: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    adduser() {
      this.dialogVisible = true;
    },
    searchChange() {
      this.page = 1;
      this.pagekey = Math.random()*10+1;
      this.getuserlist();
    },
    handleSizeChange(e) {
      this.page_size = e;
      this.page = 1;
      this.pagekey = Math.random()*10+1;
      this.getuserlist();
    },
    handleCurrentChange(e) {
      this.page = e;
      this.getuserlist();
    },
    getuserlist() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=user.login.list_user",
        data: this.qs.stringify({
          username: this.username,
          page: this.page,
          page_size: this.page_size,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          console.log(res.data.data.data);
          this.userlist = res.data.data.data;
          this.totalnum = res.data.data.total_num;
        }
      });
    },
    dataDetails() {},
    allocation(e) {
      this.jurdata = JSON.parse(localStorage.getItem("menu"));
      this.jurdata[0].disabled = true;
      var data = e.children;
      this.defKeys = [1];
      var arr = [];
      for (var i = 0; i < data.length; i++) {
        if (data[i].children) {
          var childrens = data[i].children;
          for (var j = 0; j < childrens.length; j++) {
            arr.push(childrens[j].pur_id);
          }
        } else {
          arr.push(data[i].pur_id);
        }
      }
      this.defKeys = this.defKeys.concat(arr);
      this.juridialogVisible = true;
      this.u_id = e.uid;
    },
    authority() {
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=user.perms.allot_perm",
        data: this.qs.stringify({
          uid: this.u_id,
          role_perm: idStr,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.success("分配成功");
          }
          this.juridialogVisible = false;
          this.getuserlist();
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.error(res.data.message);
          }
        }
      });
    },
    sumbitinfo() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=user.login.create_user",
            data: this.qs.stringify({
              username: this.ruleForm.username,
              password: this.ruleForm.password,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("创建成功");
              }
              this.dialogVisible = false;
              this.getuserlist();
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    amendpass() {
      this.$refs["ruleForm2"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=user.login.modify_pwd",
            data: this.qs.stringify({
              uid: this.u_id,
              new_password: this.ruleForm2.secpassword,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("修改密码成功");
              }
              this.passdialogVisible = false;
              this.getuserlist();
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deluser(id) {
      this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=user.login.del_user",
            data: this.qs.stringify({
              uid: id,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getuserlist();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getuserlist();
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.userbox {
  width: 100%;
  height: 100%;
  .baselistbox_top {
    width: 100%;
    height: 130px;
    background-color: #fff;
    border-radius: 10px;
    .baselistbox_top_title {
      width: 100%;
      height: 65px;
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      line-height: 25px;
      justify-content: space-between;
      p:first-child {
        font-size: 18px;
        font-weight: 700;
      }
    }
    .baselistbox_top_line {
      width: 100%;
      height: 1px;
      background-color: #f2f2f2;
    }
    .baselistbox_top_search {
      width: 100%;
      height: 68px;
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      line-height: 28px;
      justify-content: space-between;
      .left_search {
        display: flex;
        .btnbox,
        .btnbox2 {
          width: 68px;
          height: 28px;
          border: 1px solid #4f71ff;
          text-align: center;
          border-radius: 3px;
          font-size: 14px;
          cursor: pointer;
        }
        .btnbox {
          background-color: #4f71ff;
          color: #fff;
        }
        .btnbox2 {
          color: #4f71ff;
        }
      }
      .right_search {
        display: flex;
        .firstsearch,
        .secsearch {
          display: flex;
          margin-right: 40px;
          /deep/.el-input {
            width: 240px;
          }
          .biaoti {
            font-size: 14px;
            margin-right: 20px;
          }
        }
        .btnbox,
        .btnbox2 {
          width: 68px;
          height: 28px;
          border: 1px solid #4f71ff;
          text-align: center;
          border-radius: 3px;
          font-size: 14px;
          margin-left: 20px;
          cursor: pointer;
        }
        .btnbox {
          background-color: #4f71ff;
          color: #fff;
        }
        .btnbox2 {
          color: #4f71ff;
        }
      }
    }
  }
  .baselistbox_table {
    width: 100%;
    background-color: #fff;
    margin-top: 10px;
    padding: 20px;
    box-sizing: border-box;
    position: relative;
    border-radius: 10px;
    /deep/.el-table__header {
      th {
        background-color: #f1f1f3;
      }
    }
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      /deep/.el-pager {
        .active {
          background-color: #4f71ff !important;
        }
      }
      /deep/.el-input__inner:hover {
        border-color: #4f71ff;
      }
    }
  }
}
</style>