<template>
  <el-card class="user">
    <el-card class="search">
      <el-form :inline="true" :model="searchForm" class="search_form" style="text-align: left">
        <el-form-item label="用户名称">
          <el-input v-model="searchForm.username" placeholder="请输入用户名称" @keyup.enter.native="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table">
      <table-template :indexShow="true" :tableData="tableData" :tableColumns="tableColumns" :loading="loading"
        :pagination="pagination" @Jump="jumpPage">
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" round @click="changePassWord(scope.row)">修改密码</el-button>
            <el-button type="warning" size="mini" round @click="edit(scope.row)">分配权限</el-button>
            <el-button type="danger" size="mini" round @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </table-template>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="addVisible" width="40%" :before-close="addClose"
      :close-on-click-modal="false">
      <el-form class="form" ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="telephone">
          <el-input v-model="form.telephone"></el-input>
        </el-form-item>
        <el-form-item label="用户描述：" prop="content">
          <el-input v-model="form.content"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClose">取 消</el-button>
        <el-button type="primary" @click="createUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="editVisible" width="40%" :before-close="editClose"
      :close-on-click-modal="false">
      <el-form class="form" label-width="100px">
        <el-form-item label="用户名称：">
          <el-input v-model="username" readonly></el-input>
        </el-form-item>
        <el-form-item label="角色分配：">
          <el-select v-model="roleId" filterable placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editClose">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import TableTemplate from "@/components/Table";
import { userPage, createUser, updatePassword, listAllRole, updateRole, deleteUser } from "@/api/user";


export default {
  components: { TableTemplate },
  data() {
    return {
      searchForm: {
        username: "",
      },
      loading: false,
      pagination: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      tableData: [],
      tableColumns: [
        {
          key: "username",
          label: "用户名称",
          width: 180
        },
        {
          key: "email",
          label: "邮箱",
        },
        {
          key: "telephone",
          label: "电话",
          width: 180
        },
        {
          key: "content",
          label: "用户描述",
        },
        {
          key: "createTime",
          label: "创建时间",
          width: 200
        },
      ],
      addVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        telephone: '',
        content: '',
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'change' }],
        password: [{ required: true, message: '请输入用户名', trigger: 'change' }],
        email: [{ required: false, message: '请输入邮箱', trigger: 'change' }],
        telephone: [{ required: true, message: '请输入手机号', trigger: 'change' }],
        content: [{ required: true, message: '请输入用户描述', trigger: 'change' }]
      },
      editVisible: false,
      username: '',
      roleList: [],
      roleId: '',
      id: '',
    };
  },
  methods: {
    init() {
      this.loading = true;
      let params = {
        username: this.searchForm.username,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      };
      userPage(params).then((res) => {
        this.loading = false;
        if (res.success) {
          console.log(res)
          this.pagination.total = res.data.total;
          this.tableData = res.data.list;
        }
      });
    },
    jumpPage() {
      this.init();
    },
    onSubmit() {
      this.pagination.currentPage = 1;
      this.init();
    },
    addUser() {
      this.addVisible = true
    },
    addClose() {
      this.addVisible = false;
      this.form = {};
    },
    createUser() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          createUser(this.form).then((res) => {
            if (res.success) {
              this.$message({
                type: "success",
                message: "创建成功!",
              });
              this.addClose();
              this.onSubmit();
            } else {
              this.$message({
                type: "error",
                message: res.msg ||"创建失败!",
              });
            }
          })
        }
      })
    },
    changePassWord(row) {
      this.$prompt(`确定修改该用户密码吗?`, `用户名：${row.username}`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入新密码",
        inputType: "text",
      }).then(({ value }) => {
        if (!value) {
          this.$message.error("未输入新密码");
          return;
        }
        updatePassword({ id: row.id, password: value }).then((res) => {
          if (res.success) {
            this.$message.success("修改成功");
            this.init()
          } else {
            this.$message.error(res.msg || "修改失败");
          }
        })
      }).catch(() => {
        this.$message("取消修改");
      });
    },
    edit(row) {
      console.log(row)
      listAllRole().then((res) => {
        console.log(res)
        if (res.success) {
          this.id = row.id
          this.username = row.username
          this.roleId = row.role
          this.roleList = res.data
          this.editVisible = true;
        }
      })
    },
    editClose() {
      this.editVisible = false;
    },
    editUser() {
      if (this.roleId) {
        updateRole({ id: this.id, roleId: this.roleId }).then((res) => {
          console.log(res)
          if (res.success) {
            this.$message.success("分配权限成功");
            this.editVisible = false;
            this.init()
          }
        })
      } else {
        this.$message({
          type: "warning",
          message: '请选择角色',
        });
      }
    },
    del(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteUser({ id: row.id }).then((res) => {
            if (res.success == true) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            } else {
              this.$message({
                type: "warning",
                message: res.msg || '删除失败，请联系管理员',
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }
  },
  created() {
    this.init();
  },
};
</script>

<style lang="stylus" scoped>
.user {
  width: 100%;
  height: calc(100vh - 100px);

  .search {
  }

  .table {
    margin-top: 15px;
    max-height: calc(100vh - 260px);
    overflow: auto;
  }
}
</style>