<template>
  <div class="app-container">
    <el-form :inline="true" ref="form" :model="form" size="mini">
      <el-form-item label="帐号" prop="uuid">
        <el-select v-model="form.uuid" filterable placeholder="请输入帐号">
          <el-option
            v-for="(item, index) in users"
            :key="index"
            :label="item.account"
            :value="item.uuid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        ><el-button type="primary" @click="onSubmit"
          >查询</el-button
        ></el-form-item
      >
      <el-form-item
        ><el-button @click="onReset('form')">重置</el-button></el-form-item
      >
      <el-form-item
        ><el-button type="warning" @click="onAdd">添加</el-button></el-form-item
      >
    </el-form>
    <el-table
      v-loading="isLoading"
      element-loading-text="Loading"
      :data="list"
      size="mini"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column
        prop="username"
        label="用户名"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="account"
        label="账号"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column prop="phone" label="手机" width="150"></el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        width="200"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="remarks"
        label="备注"
        width="240"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="create_at"
        label="创建时间"
        width="150"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="page-wrapper">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="form.pagenum"
        background
        small
        :page-size="form.pagesize"
        :pager-count="5"
        layout="pager, prev, next, total"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%">
      <el-form
        :model="post"
        status-icon
        :rules="rules"
        ref="post"
        size="mini"
        label-width="80px"
      >
        <el-form-item label="账号" prop="account">
          <el-input
            type="text"
            v-model="post.account"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="post.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="password">
          <el-select v-model="post.role" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="post.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input
            type="text"
            v-model="post.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            type="email"
            v-model="post.email"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            type="text"
            v-model="post.remarks"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" plain @click="submitForm('post')"
          >提交</el-button
        >
        <el-button type="success" size="mini" plain @click="onReset('post')"
          >重置</el-button
        >
        <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, deleteUser, updateUser, addUser } from "@/api/index";
import { mapTrim, compareObjectDiff } from "@/utils/index";
export default {
  data() {
    return {
      data: {},
      total: 0,
      list: [],
      isLoading: false,
      users: [],
      options: [
        { value: "USER", label: "用户" },
        { value: "ADMIN", label: "管理员" },
      ],
      form: {
        uuid: null,
        role: null,
        depot: null,
        pagesize: 15,
        pagenum: 1,
      },
      dialogTitle: "",
      dialogVisible: false,
      currentValue: null,
      currentIndex: 0,
      post: {
        account: null,
        username: null,
        phone: null,
        birthday: null,
        gender: 1,
        email: null,
        hometown: null,
        entry_time: null,
        expire_date: null,
        depot: null,
        role: null,
        remarks: "",
      },
      rules: {
        account: [
          {
            type: "string",
            required: true,
            message: "账号不能为空",
            trigger: "blur",
          },
        ],
        username: [
          {
            type: "string",
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 20,
            message: "字符串长度在 1 到 20 之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            type: "string",
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          {
            type: "string",
            required: false,
            message: "手机号不能为空",
            trigger: "blur",
          },
          { len: 11, message: "手机号长度为11", trigger: "blur" },
        ],
        birthday: [
          { required: false, message: "出生年月不能为空", trigger: "blur" },
        ],
        gender: [
          {
            type: "number",
            required: false,
            message: "性别不能为空",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            required: false,
            message: "邮箱不能为空",
            trigger: "blur",
          },
        ],
        hometown: [
          {
            type: "string",
            required: false,
            message: "籍贯不能为空",
            trigger: "blur",
          },
        ],
        role: [
          {
            type: "string",
            required: false,
            message: "角色不能为空",
            trigger: "blur",
          },
        ],
        remarks: [
          {
            type: "string",
            required: false,
            message: "备注不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    fetchData(params) {
      this.isLoading = true;
      getUserList(
        Object.assign(
          {
            pagenum: this.form.pagenum,
            pagesize: this.form.pagesize,
          },
          params
        )
      )
        .then((res) => {
          this.total = res.count;
          this.list = res.data.map((item) => {
            item.gender = item.gender == 1 ? "男" : "女";
            if (item.email == "user@example.com") item.email = null;
            return item;
          });
        })
        .catch((err) => {
          this.list = err.data;
          // this.$message.error(err.message)
          console.log(err.message);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    fetchSelectData() {
      getUserList({ scope_type: "list" })
        .then((res) => {
          if (res.code == 200) this.users = res.data;
        })
        .catch((err) => {
          // this.$message.error(err.message)
          console.log(err.message);
        });
    },
    handleSizeChange(e) {
      this.form.pagesize = e;
      this.fetchData(mapTrim(this.form));
    },
    handleCurrentChange(e) {
      this.form.pagenum = e;
      this.fetchData(mapTrim(this.form));
    },
    handleEdit(index, row) {
      this.post.account = row.account;
      this.post.username = row.username;
      this.post.phone = row.phone;
      this.post.birthday = row.birthday;
      this.post.email = row.email;
      this.post.hometown = row.hometown;
      this.post.entry_time = row.entry_time;
      this.post.expire_date = row.expire_date;
      this.post.role = row.role_id;
      this.post.depot = row.depot_id;
      this.post.remarks = row.remarks;
      this.dialogTitle = "编辑";
      this.dialogVisible = true;
      this.currentValue = row;
      this.currentIndex = index;
      this.rules.password[0].required = false;
    },
    handleDelete(index, row) {
      this.$alert(
        "您确定要删除么？删除操作将不可恢复。如需取消操作，请点击右上角关闭按钮。",
        "删除提醒",
        {
          confirmButtonText: "确定",
          callback: (action) => {
            if (action == "confirm")
              deleteUser(row.uuid)
                .then((res) => {
                  console.log(res);
                  this.total -= 1;
                  this.$delete(this.list, index);
                  this.$message({
                    type: "success",
                    message: `成功删除第${index}行`,
                  });
                })
                .catch((err) => {
                  this.$message.error(err.message);
                });
          },
        }
      );
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        let result = true;
        if (valid) {
          if (!this.post.username) this.post.username = this.post.account;
          if (this.dialogTitle === "添加")
            addUser(mapTrim(this.post))
              .then((res) => {
                console.log(res);
                this.$message({ type: "success", message: "添加成功" });
                this.fetchData();
              })
              .catch((err) => {
                this.$message.error(err.message);
              });
          else if (this.dialogTitle === "编辑")
            updateUser(
              this.currentValue.uuid,
              compareObjectDiff(this.post, this.currentValue)
            )
              .then((res) => {
                console.log(res);
                this.$message({ type: "success", message: "更新成功" });
                this.fetchData();
              })
              .catch((err) => {
                this.$message.error(err.message);
              });
        } else {
          result = false;
        }
        this.dialogVisible = false;
        return result;
      });
    },
    onAdd() {
      this.dialogTitle = "添加";
      this.dialogVisible = true;
      this.rules.password[0].required = true;
    },
    onSubmit() {
      this.form.pagenum = 1;
      this.form.pagesize = 15;
      this.fetchData(mapTrim(this.form));
    },
    onReset(formName) {
      this.form.account = null;
      this.form.username = null;
      this.form.pagesize = 15;
      this.form.pagenum = 1;
      this.$refs[formName].resetFields();
      this.fetchData();
    },
  },
  mounted() {},
  created() {
    if (this.$store.getters.role !== "ADMIN")
      this.$router.push({ path: "/403" });

    this.fetchData();
    this.fetchSelectData();
  },
};
</script>
<style lang="less" scoped>
.app-container {
  & > div.page-wrapper {
    margin: 10px 0px;
  }
}
</style>
