<template>
  <div style="height: (screenHeight-300)+'px'">
    <div id="buttomContain">
      <div class="search-container">
        <el-input
          style="width: 300px; margin-right: 15px;"
          placeholder="请输入用户名搜索"
          v-model="inputUsername"
        >
          <i
            slot="suffix"
            class="el-input__icon el-icon-search"
            @click="searchUser()"
          ></i>
          <i
            slot="suffix"
            class="el-input__icon el-icon-circle-close"
            @click="cancelSearch()"
          ></i>
        </el-input>
      </div>
      <div class="button-container">
        <el-button
          id="buttonStyle"
          size="small"
          style="margin-top: 20px"
          @click="adduser1()"
          >添加用户</el-button
        >
      </div>
    </div>

    <el-table
      id="tableStyle"
      :data="usersData"
      style="width: 100%"
      header-cell-class-name="sinCl"
    >
      <el-table-column
        fixed="left"
        prop="username"
        label="用户名称"
        min-width="100"
      ></el-table-column>
      <el-table-column
        fixed="left"
        prop="realName"
        label="真实姓名"
        min-width="100"
      ></el-table-column>
      <el-table-column prop="role" label="权限" min-width="80">
        <template slot-scope="scope">
          <el-select size="small" v-model="scope.row.role" placeholder="请选择">
            <el-option
              v-for="item in idenOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="280" fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click.native="EditField(scope.$index)"
            >确认</el-button
          >
          <el-button
            type="text"
            size="small"
            @click.native="deleteField(scope.$index)"
            >删除</el-button
          >
            <el-button
            type="text"
            size="small"
            @click.native="resetPassword(scope.$index)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 50px">
      <el-pagination
        layout="prev, pager, next"
        :page-count="dataPageNum"
        @current-change="pageChange"
      ></el-pagination>
    </div>

    <el-dialog
      v-dialogDrag
      class="taskDialog"
      title="添加用户"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
    >
      <div style="text-align: left">
        <el-form
          ref="account"
          :model="account"
          :rules="rules"
          label-width="130px"
          style="margin-top: 20px"
        >
          <el-form-item prop="username" label="用户名：">
            <el-input
              style="width: 90%"
              type="text"
              v-model="account.username"
              auto-complete="off"
              :autofocus="true"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="realName" label="真实姓名：">
            <el-input
              style="width: 90%"
              type="text"
              v-model="account.realName"
              auto-complete="off"
              :autofocus="true"
              placeholder="请输入真实姓名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码：">
            <el-input
              style="width: 90%"
              type="password"
              v-model="account.password"
              auto-complete="off"
              :autofocus="true"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password1" label="确认密码：">
            <el-input
              style="width: 90%"
              type="password"
              v-model="account.password1"
              auto-complete="off"
              :autofocus="true"
              placeholder="请确认密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="role" label="权限：">
            <el-select
              style="width: 90%"
              size="small"
              v-model="account.role"
              placeholder="请选择"
            >
              <el-option
                v-for="item in idenOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-button id="buttonStyle" size="small" @click="addUser()"
        >确认</el-button
      >
    </el-dialog>
  </div>
</template>
<script>
import { ajax as request } from "@/request.js";
import md5 from "js-md5";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.account.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validpassword = (rule, value, callback) => {
      let reg = /[0-9a-zA-Z]{6,18}/;
      if (!reg.test(value)) {
        callback(new Error("密码必须是由6-18位数字和字母组合"));
      } else {
        callback();
      }
    };

    return {
      isSearch: false,
      currentSearchUser: "",
      inputUsername: "",
      dataPageNum: 1,
      currentPage: 1,
      account: {
        username: "",
        realName: "",
        password: "",
        password1: "",
        role: "Worker",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validpassword, trigger: "blur" },
        ],
        password1: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
      },
      dialogVisible: false,
      screenHeight: document.documentElement.clientHeight,
      usersData: [],
      idenOptions: [
        {
          value: "Admin",
          label: "管理员",
        },
        {
          value: "Leader",
          label: "领导人员",
        },
        {
          value: "Worker",
          label: "外业人员",
        },
        {
          value: "Operator",
          label: "工作人员",
        },
        {
          value: "SuperAdmin",
          label: "超级管理员",
        },
      ],
    };
  },
  methods: {
    init() {
      let that = this;
      request({
        url: "/user/all",
        method: "get",
        params: {
          page: 1,
        },
      }).then(function (response) {
        //登录成功获取数据存入usersData
        if (response.data.success) {
          that.usersData = response.data.data.users;
          that.dataPageNum = response.data.data.totalPages;
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
    },
    pageChange(val) {
      let that = this;
      this.usersData = [];
      this.currentPage = val;
      if (this.isSearch) {
        request({
          url: "/user/search",
          method: "post",
          params: { page: 1, username: that.currentSearchUser },
        }).then(function (response) {
          //上传成功
          if (response.data.success) {
            that.usersData = response.data.data.users;
            that.dataPageNum = response.data.data.totalPages;
          } else if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          }
        });
      } else {
        request({
          url: "/user/all",
          method: "post",
          params: {
            page: val,
          },
        }).then(function (response) {
          if (response.data.success) {
            that.usersData = response.data.data.users;
          }
        });
      }
    },
  //重置密码
  resetPassword(index) {
  let that = this;
  this.$confirm("确认重置该用户密码？", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
  })
    .then(() => {
      // 调用重置密码接口
      request({
        url: "/user/resetPassword",
        method: "post",
        params: {
          id: that.usersData[index].id,
        },
      }).then(function (response) {
        if (response.data.success) {
          that.$notify.success({
            title: "提示",
            message: "密码已成功重置为默认密码！",
          });
        } else {
          that.$notify.error({
            title: "提示",
            message: response.data.message || "密码重置失败",
          });
        }
      });
      // 刷新用户列表
      request({
        url: "/user/all",
        method: "post",
        params: {
          page: that.currentPage,
        },
      }).then(function (response) {
        if (response.data.success) {
          that.usersData = response.data.data.users;
        }
      });
    })
    .catch(() => {
      that.$notify.info({
        title: "提示",
        message: "已取消操作",
      });
    });
},
    deleteField(index) {
      let that = this;
      this.$confirm("确认删除？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确认",
        type: "warning",
      })
        .then(() => {
          request({
            url: "/user/delete",
            method: "post",
            params: {
              id: that.usersData[index].id,
            },
          }).then(function (response) {
            if (response.data.success) {
              that.$notify.success({
                title: "提示",
                message: "删除成功！",
              });
            } else {
              that.$notify.error({
                title: "提示",
                message: "删除失败",
              });
            }
          });
          request({
            url: "/user/all",
            method: "post",
            params: {
              page: that.currentPage,
            },
          }).then(function (response) {
            if (response.data.success) {
              that.usersData = response.data.data.users;
            }
          });
        })
        .catch(() => {
          this.$notify.error({
            title: "提示",
            message: "删除失败",
          });
        });
    },
    EditField(index) {
      let that = this;
      request({
        url: "/user/role_change",
        method: "post",
        params: {
          id: that.usersData[index].id,
          role: that.usersData[index].role,
        },
      }).then(function (response) {
        //上传成功
        if (response.data.success) {
          that.$notify.success({
            title: "提示",
            message: "提交成功！",
          });
          that.init();
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
      request({
        url: "/user/all",
        method: "post",
        params: {
          page: that.currentPage,
        },
      }).then(function (response) {
        if (response.data.success) {
          that.usersData = response.data.data.users;
        }
      });
    },
    cancelSearch() {
      this.isSearch = false;
      this.inputUsername = "";
    },
    searchUser() {
      this.isSearch = true;
      let that = this;
      this.currentSearchUser = this.inputUsername;
      request({
        url: "/user/search",
        method: "post",
        params: { page: 1, username: that.currentSearchUser },
      }).then(function (response) {
        //上传成功
        if (response.data.success) {
          that.usersData = response.data.data.users;
          that.dataPageNum = response.data.data.totalPages;
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else {
          that.$notify.error({
            title: "提示",
            message: "未查找到符合条件的用户！",
          });
        }
      });
    },
    addUser() {
      let that = this;
      this.$refs.account.validate((valid) => {
        if (valid) {
          let that = this;
          request({
            url: "/user/new",
            method: "post",
            params: {
              username: that.account.username,
              realName: that.account.realName,
              password: md5(md5(that.account.password)),
              role: that.account.role,
            },
          }).then(function (response) {
            if (response.data.success) {
              that.dialogVisible = false;
              that.$notify.success({
                title: "提示",
                message: "添加成功！",
              });
              that.init();
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            }
          });
        }
      });
    },
    adduser1() {
      this.dialogVisible = true;
      this.account = {
        username: "",
        realName: "",
        password: "",
        password1: "",
        role: "Worker",
      };
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style scoped lang="scss">
.el-input__inner {
  >>> &::placeholder {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #c0c4cc;
  }
}

#buttomContain {
  top: 5px;
  right: 25px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: calc(100% - 50px);
}

.search-container {
  /* 搜索容器靠左 */
}

.button-container {
  /* 按钮容器靠右 */
}

#tableStyle {
  top: 50px;
  margin-bottom: 30px;
  height: 600px;
}
>>> .el-pager li {
  background: #fff !important;
}

>>> .el-pagination button {
  background: #fff !important;
}
</style>