<template>
  <div class="body">
    <!-- 头部区域 -->
    <div class="head">
      <div class="head-img">
        <img src="../../../public/images/user-1.png" />
      </div>
      <div class="head-info">账号管理</div>
    </div>

    <!-- 搜索添加区域 -->
    <div class="user">
      条件：
      <div class="input">
        <el-input
          v-model="listQuery.name"
          size="small"
          placeholder="请输入账号 "
          clearable
          @clear="getList"
          @keyup.enter.native="handleFilter"
        >
        </el-input>
      </div>

      <div class="input-serch">
        <el-row>
          <el-button size="small" type="primary" @click="handleFilter"
            >搜索</el-button
          >
        </el-row>
      </div>

      <div class="input-add">
        <el-row>
          <el-button type="primary" size="small" @click="handleCreate"
            ><img src="../../../public/images/img-3.png" />添加
          </el-button>
        </el-row>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="form">
      <el-table :data="list">
        <el-table-column label="账号" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="昵称" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.nickname }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="{ row, $index }">
            <el-button type="text" size="small" @click="handleUpdate(row)"
              >编辑</el-button
            >
            <el-button
              @click="handleDelete(row, $index)"
              type="text"
              size="small"
              class="button"
              ><img src="../../../public/images/img-2.png" />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部分页区 -->
    <div class="block">
      <template>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </template>
    </div>

    <!-- 添加弹窗区域 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="30%"
      center
    >
      <el-form ref="dataForm" :model="temp" :rules="rules">
        <el-form-item
          style="white-space: pre"
          label="账号："
          class="switch-button-item"
          prop="name"
        >
          <el-col :span="12">
            <el-input
              v-model="temp.name"
              autocomplete="off"
              placeholder="请输入账号"
              style="width: 110%"
            >
            </el-input>
          </el-col>
        </el-form-item>

        <el-form-item
          style="white-space: pre"
          label="昵称："
          class="switch-button-item"
          prop="nickname"
        >
          <el-col :span="12">
            <el-input
              v-model="temp.nickname"
              autocomplete="off"
              placeholder="请输入昵称"
              style="width: 110%"
            >
            </el-input>
          </el-col>
        </el-form-item>

        <el-form-item
          style="white-space: pre"
          label="密码："
          class="switch-button-item"
          prop="password"
        >
          <el-col :span="12">
            <el-input
              v-model="temp.password"
              autocomplete="off"
              type="password"
              placeholder="请输入密码"
              style="width: 110%"
            >
            </el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确 定</el-button
        >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  createAdmin,
  updateAdmin,
  deleteAdmin,
  fetchList,
  searchList,
} from "@/api/getuser";

export default {
  components: {
    Pagination,
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error("账号至少五位数"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码至少六位数"));
      } else {
        callback();
      }
    };
    return {
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 8,
        name: "",
        nickname: "",
        password: "",
      },
      temp: {
        id: undefined,
        name: "",
        nickname: "",
        password: "",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑账号信息",
        create: "添加账号",
      },
      rules: {
        name: [
          {
            required: true,
            message: "账号至少五位数",
            trigger: "change",
            validator: validateUsername,
          },
        ],
        nickname: [
          {
            required: true,
            message: "请输入昵称",
            trigger: "change",
          },
        ],
        password: [
          {
            required: true,
            message: "密码至少六位数",
            trigger: "change",
            validator: validatePassword,
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      fetchList(this.listQuery).then((response) => {
        this.list = response.data;
        this.total = response.total;
      });
    },
    handleDelete(row, index) {
      if (confirm("是否删除？")) {
        deleteAdmin({ id: row.id }).then(() => {
          this.$notify({
            title: "删除成功",
            type: "success",
            duration: 2000,
          });
          this.list.splice(index, 1);
        });
      }
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        nickname: "",
        password: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          createAdmin(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "添加成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.password = "";
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);

          updateAdmin(tempData).then(() => {
            const index = this.list.findIndex((v) => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "编辑成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleFilter() {
      if (!this.listQuery.name) {
        alert("请输入账号");
      } else {
        searchList({ name: this.listQuery.name }).then((response) => {
          this.list = response.data;
          this.total = response.total;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.body {
  position: relative;
  width: 1551px;
  margin: 29px 29px 0 31px;

  .head {
    display: flex;
    width: 1380px;
    height: 55px;
    margin-left: 40px;
    border-bottom: 1px solid #cccccc;

    .head-img {
      width: 30px;
      height: 30px;

      img {
        width: 30px;
      }
    }

    .head-info {
      width: 95px;
      height: 22px;
      margin-top: 5px;
      margin-left: 16px;
      font-weight: bold;
    }
  }

  .user {
    display: flex;
    width: 1380px;
    line-height: 110px;
    margin-left: 40px;
    font-size: 9px;

    .input {
      width: 240px;
      margin-left: 21px;
    }

    .input-serch {
      margin-left: 32px;
    }

    .input-add {
      margin-left: 915px;

      img {
        width: 10.5px;
        margin-right: 10px;
      }
    }
  }

  .form {
    margin-left: 40px;
    width: 1380px;

    .button-img {
      img {
        width: 53.5px;
      }
    }

    .button-info {
      margin-top: 39px;
    }

    .button {
      color: red;
    }

    img {
      width: 8.5px;
      margin-right: 8px;
    }
  }

  .block {
    display: flex;
    margin-bottom: 50px;
    margin-left: 500px;
  }
  .switch-button-item {
    margin-left: 100px;
    margin-top: 30px;
  }
}
</style>
