<template>
  <div id="yhgl">
    <div class="choice">
      <el-input class="input-content public-input" v-model="input" placeholder="输入需要查询的用户名"></el-input>
      <div class="button-search" @click="queryUser">搜索</div>
      <div class="new-user" @click="addNew">
        <img :src="img3" alt="" />&nbsp;新增
      </div>
    </div>
    <div class="management-content">
      <div class="yhlb">

        <table>
          <thead>
            <tr>
              <td>序号</td>
              <td>登录用户名</td>
              <td>真实姓名</td>
              <td>邮箱</td>
              <td>角色</td>
              <td>电话号码</td>
              <td>创建时间</td>
              <td>状态</td>
              <td>操作</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in data_table">
              <td v-text="index"></td>
              <td v-text="item.account"></td>
              <td v-text="item.username"></td>
              <td v-text="item.mail"></td>
              <td v-text="item.role != null ? item.role.name : null"></td>
              <td v-text="item.telephone"></td>
              <td v-text="item.createTime"></td>
              <td>
                <el-switch v-model="item.state" @change="change_state(item)" active-color="#13ce66"
                  inactive-color="#ff4949" active-value="1" inactive-value="0" active-text="启用" inactive-text="停用">>
                </el-switch>
              </td>
              <td>
                <i class="el-icon-edit" title="编辑用户信息" @click="edit(item, index)"></i>&emsp;
                <i class="el-icon-delete-solid" title="删除用户信息" @click="remove(item, index)"></i>&emsp;
                <i class="el-icon-refresh-left" title="重置用户密码" @click="resetPassword(item.account)"></i>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <el-dialog title="提示" :visible.sync="centerDialogVisible" center>
      <div class="dialog-content" v-show="type == 'add'">
        <el-form label-width="80px" style="margin-bottom: 0px" :rules="rules" ref="new_user" :model="new_user">
          <el-form-item label="账号" prop="account">
            <el-input v-model="new_user.account" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="new_user.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="username">
            <el-input v-model="new_user.username" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          <el-form-item label="电话号码">
            <el-input v-model="new_user.telephone" placeholder="请输入电话号码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="new_user.mail" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="权限">
            <el-select class="public-input" v-model="new_user.role" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in data_role" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit('new_user')">确 定</el-button>
        </span>
      </div>
      <div class="dialog-content" v-show="type == 'edit'">
        <el-form label-width="80px" style="margin-bottom: 0px" :rules="rules_edit" ref="edit_user" :model="edit_user">
          <el-form-item label="账号" prop="account">
            <el-input readonly="readonly" v-model="edit_user.account" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <!-- <el-form-item label="密码">
            <el-input
              v-model="edit_user.password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="真实姓名" prop="username">
            <el-input v-model="edit_user.username" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          <el-form-item label="电话号码">
            <el-input v-model="edit_user.telephone" placeholder="请输入电话号码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input :readonly="edit_user.mailReadOnly" v-model="edit_user.mail" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="权限">
            <el-select class="public-input" v-model="edit_user.role" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in data_role" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit_edit('edit_user')">确 定</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
#yhgl {
  width: 100%;
  height: 100%;
  margin: 0%;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;

  .choice {
    width: 100%;
    height: 40px;
    margin-top: 20px;
    padding-left: 20px;
    box-sizing: border-box;
    // display: -webkit-box;

    .input-content {
      width: 200px;
      height: 30px;
      float: left;

      input {
        height: 30px;
        color: white;
        border-radius: 0px;
        border: 1px solid #1c678a;
        background: none !important;
      }
    }

    .button-search {
      width: 100px;
      height: 30px;
      line-height: 30px;
      float: left;
      margin-left: 20px;
      text-align: center;
      cursor: pointer;
      color: white;
      background-image: url(../../assets/img/yqjc/40.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }

    .new-user {
      width: 120px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      float: left;
      margin-left: 20px;
      color: white;
      cursor: pointer;
      background: url(../../assets/img/yqjc/40.png) no-repeat;
      background-size: 100% 100%;
    }
  }

  .management-content {
    width: 100%;
    height: calc(100% - 60px);
    padding: 10px;
    padding-top: 0px;
    box-sizing: border-box;

    .yhlb {
      width: 100%;
      height: 100%;
      padding: 20px;
      padding-top: 40px;
      box-sizing: border-box;

      table {
        width: 100%;
        height: calc(100% - 10px);
        color: white;
        text-align: center;
        border-collapse: collapse;

        tbody {
          display: block;
          height: calc(100% - 50px);
          overflow-y: scroll;
        }

        thead,
        tbody tr {
          display: table;
          width: 100%;
          table-layout: fixed;
        }

        /*滚动条默认宽度是16px 将thead的宽度减16px*/
        table thead {
          width: calc(100% - 1em);
        }

        thead tr {
          height: 40px;
          background: url(../../assets/img/setting/tr1.png) no-repeat;
          background-size: 100% 100%;
        }

        tbody tr {
          border-bottom: 1px solid #252631;
        }

        tbody tr td {
          padding: 10px;

          .el-icon-edit {
            font-size: 24px;
            color: #409eff;
            cursor: pointer;
          }

          .el-icon-delete-solid {
            font-size: 24px;
            color: red;
            cursor: pointer;
          }

          .el-icon-refresh-left {
            font-size: 24px;
            color: #12dc12;
            cursor: pointer;
          }
        }

        .el-switch__label {
          color: white;
        }

        .el-switch__label.is-active {
          color: green;
        }
      }
    }
  }

  /*修改滚动条样式*/
  tbody::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    /**/
  }

  tbody::-webkit-scrollbar-track {
    background: #146c7e;
    border-radius: 2px;
  }

  tbody::-webkit-scrollbar-thumb {
    background: #00ffff;
    border-radius: 10px;
  }

  tbody::-webkit-scrollbar-thumb:hover {
    background: #00ffff;
  }

  tbody::-webkit-scrollbar-corner {
    background: #179a16;
  }

  .el-dialog {
    // height: 350px;
    width: 500px;
    background-color: #1d2d47;

    .dialog-content {
      width: 100%;
      // padding: 30px 20px;
      box-sizing: border-box;
    }

    .el-dialog__title {
      color: #ffff;
    }

    .el-form-item__label {
      color: #ffff;
    }

    .el-input__inner {
      background: none;
      color: #ffff;
      border: 1px solid #535353 !important;
      box-shadow: 0 0 10px #535353;
    }

    .el-input__count {
      color: #229dbd;
      background: #1d2d4600;
    }
  }
}
</style>

<script>
import img1 from "../../assets/img/setting/1.png";
import img2 from "../../assets/img/setting/2.png";
import img3 from "../../assets/img/setting/04.png";
import back from "../../assets/img/setting/back.png";
import { MAIL_DOMAIN } from "@/constant/user"
import { addUser, removeUser } from "@/api/mail/user"
import {
  delete_util,
  get,
  post,
  startLoading,
  endLoading,
} from "../../util/http_util";
export default {
  name: "yhgl",
  data() {
    return {
      rules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            required: true,
            pattern: /[a-zA-Z0-9]{2,30}$/,
            message: '账号必须2~30位，由数字或字母组成',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            required: true,
            pattern: /(?=.*\d)(?=.*[a-z])[a-zA-Z0-9]{6,30}/,
            message: '密码必须6~30位，由数字字母（非纯数字、非纯字母）组成',
            trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
        ]
      },
      rules_edit: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            required: true,
            pattern: /[a-zA-Z0-9]{2,30}$/,
            message: '账号必须2~30位，由数字或字母组成',
            trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
        ]
      },
      back: back,
      img1: img1,
      img2: img2,
      img3: img3,
      input: "",
      index: 0,
      data_table: [],
      // data_module: [
      //     { index: 1, name: "用户列表" },
      //     { index: 2, name: "用户分组" },
      //     { index: 3, name: "用户权限" },
      // ],
      centerDialogVisible: false,
      new_user: {
        account: "",
        username: "",
        password: "",
        mail: "",
        telephone: "",
        role: "",
        id: null,
      },
      edit_user: {
        account: "",
        username: "",
        password: "",
        mail: "",
        telephone: "",
        role: "",
        state: "",
        id: null,
      },
      options: [
        {
          value: "选项1",
          label: "黄金糕",
        },
        {
          value: "选项2",
          label: "双皮奶",
        },
        {
          value: "选项3",
          label: "蚵仔煎",
        },
        {
          value: "选项4",
          label: "龙须面",
        },
        {
          value: "选项5",
          label: "北京烤鸭",
        },
      ],
      data_role: [],
      data_list: [],
      type: "add",
    };
  },
  methods: {
    queryUser() {
      get("api/rest/system/user/queryUser").then((data) => {
        this.data_table = data;
        this.data_list = data;
        this.search();
      }).catch(err => {
        this.$message.warning(err.message);
      });
    },
    show_info(index) {
      this.index = index;
    },
    addNew() {
      this.new_user = {};
      this.type = "add";
      this.centerDialogVisible = true;
    },
    search() {
      let _search = this.input.toLowerCase(),
        newListData = [];
      if (this.index == 0) {
        // this.data_list = this.data_table;
      } else if (this.index == 2) {
        this.data_list = this.data_table1;
      }

      if (_search) {
        this.data_list.filter((item) => {
          if (item.username != null) {
            if (item.username.toLowerCase().indexOf(_search) !== -1 || item.account.toLowerCase().indexOf(_search) !== -1) {
              newListData.push(item);
            }
          }
        });
        if (this.index == 0) {
          this.data_table = newListData;
        } else if (this.index1 == 2) {
          this.data_table1 = newListData;
        }
      } else {
        this.data_table = this.data_list;
      }
    },
    edit(item, index) {
      this.type = "edit";
      this.centerDialogVisible = true;
      //角色
      let tmp = Object.assign({}, item);
      tmp.role = tmp.role ? tmp.role.id : null;
      this.edit_user = tmp;
      this.edit_user.mailReadOnly = (this.edit_user.mail != null && this.edit_user.mail != "" && this.edit_user.mail != undefined);//当邮箱有了以后就不能修改
    },
    remove(item, index) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delete_util("api/rest/system/user/deleteUser/" + item.id)
            .then(res => {
              if (res != 1) {
                return Promise.reject({ message: "删除失败" })
              } else if (item.mail) {
                return removeUser(item.mail)
              } else {
                return Promise.resolve(true);
              }
            })
            .then((data) => {
              if (data) {
                this.data_table.splice(index, 1);
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
            })
            .catch((err) => {
              this.$message.warning(err.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          startLoading();
          post("api/rest/system/user/register", this.new_user)
            .then(res => {
              if (res != 1) {
                return Promise.reject({ message: "用户新增失败" });
              } else if (this.new_user.mail) {
                return addUser({
                  password: this.new_user.password,
                  email: this.new_user.mail,
                  uname: this.new_user.username,
                  tel: this.new_user.telephone
                });
              } else {//没有输入邮箱
                return Promise.resolve();
              }
            })
            .then((data) => {
              this.$message.success("新增成功！");
              this.centerDialogVisible = false;
              //再次查询用户名  重新赋值
              this.queryUser();
              endLoading();
            })
            .catch((err) => {
              this.$message.warning(err.message);
              endLoading();
            });
        } else {
          return false;
        }
      });
    },
    submit_edit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          post("api/rest/system/user/updateUser", this.edit_user)
            .then(res => {
              if (res != 1) {
                return Promise.reject({ message: "用户新增失败" });
              } else if (this.edit_user.mail) {
                return addUser({
                  password: "3z111111",
                  email: this.edit_user.mail,
                  uname: this.edit_user.username,
                  tel: this.edit_user.telephone
                });
              } else {
                return Promise.resolve();
              }
            })
            .then((data) => {
              this.$message.success("修改成功！");
              (this.centerDialogVisible = false), this.queryUser();
            })
            .catch((err) => {
              this.$message.warning(err.message);
            });
        } else {
          return false;
        }
      });
    },
    resetPassword(account) {
      get("api/rest/system/user/restPassword/" + account)
        .then((data) => {
          data != null ? this.$message.success("密码:" + data) : "";
        })
        .catch((err) => {
          this.$message.warning(err.message);
        });
    },
    change_state(item) {
      get("api/rest/system/user/changeUserState/" + item.account + "/" + item.state)
        .then((res) => {
          this.$message.success("操作成功！");
        })
        .catch((err) => {
          this.$message.warning(err.message);
        });
    },
  },
  activated() {
    startLoading();
    get("api/rest/system/user/queryUser").then((data) => {
      this.data_table = data;
      this.data_list = data;
      return get("api/rest/system/role/queryRole");
    }).then((data) => {
      this.data_role = data;
      endLoading();
    }).catch(err => {
      endLoading();
      this.$message.warning(err.message);
    });
  },
  watch: {
    'new_user.account'(newVal, oldVal) {
      if (newVal) {
        this["new_user"]["mail"] = (newVal ? newVal : "") + "@" + MAIL_DOMAIN;
      } else {
        this["new_user"]["mail"] = null;
      }
    }
  }
};
</script>