<template>
  <div class="global-variable">
    <div class="condition">
      <el-form
        :inline="true"
        ref="ruleForm"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
      >
        <el-form-item label="用户名称:" prop="userName">
          <el-input
            size="small"
            v-model="formInline.userName"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色名称:" prop="roleId">
          <el-select
            v-model="formInline.roleId"
            placeholder="请选择角色"
            size="small"
          >
            <el-option
              :label="item.roleDescription"
              v-for="item in roleList"
              :key="item.id"
              :value="item.id + ''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="small"
            >查询</el-button
          >
          <el-button @click="reset('ruleForm')" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-page">
      <div class="newly">
        <el-button type="primary" @click="newnuedialog" size="small"
          >新增</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        class="center-align-table"
        :data="tableData"
        border
        :cell-style="rowStyle"
      >
        <el-table-column
          align="center"
          fixed
          prop="userId"
          label="员工ID"
          width="100"
        >
        </el-table-column>

        <el-table-column align="center" label="员工名称" prop="userName">
        </el-table-column>

        <el-table-column prop="loginName" align="center" label="登录账号">
        </el-table-column>
        <el-table-column align="center" prop="userPhone" label="手机号">
        </el-table-column>

        <el-table-column prop="roleName" align="center" label="角色">
        </el-table-column>
        <el-table-column prop="state" align="center" label="状态" width="100">
          <template slot-scope="scope">
            <span>
              {{
                scope.row.state == 0
                  ? "未启用"
                  : scope.row.state == 1
                  ? "启用"
                  : "禁用"
              }}</span
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="transition"
          align="center"
          fixed="right"
          label="操作"
          width="200"
        >
          <template slot-scope="scope">
            <el-button @click="compile(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button
              v-if="scope.row.state == 0 || scope.row.state == 2"
              @click="setState(1, scope.row.userId)"
              type="text"
              size="small"
              >启用</el-button
            >
            <el-button
              v-else
              style="color: #666"
              @click="setState(2, scope.row.userId)"
              type="text"
              size="small"
              >停用</el-button
            >
            <el-button
              style="color: #f90"
              @click="editPwd(scope.row)"
              type="text"
              size="small"
              >修改密码</el-button
            >
            <el-button
              style="color: #f00"
              @click="deleted(scope.row)"
              type="text"
              size="small"
              :disabled="scope.row.state == 1"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="formInline.pageNum"
          layout="total, prev, pager, next"
          :page-size="formInline.pageSize"
          :total="formInline.totalSize"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 弹出层 -->
    <!-- 新增 /编辑-->
    <el-dialog :title="title" :visible.sync="nuedialog" width="500px">
      <div v-loading="loadingView" class="views">
        <el-form
          :model="ruleForm"
          :rules="addUserRules"
          ref="addUserForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="员工名称" prop="userName">
            <el-input
              v-model="ruleForm.userName"
              placeholder="请输入员工名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input
              v-model="ruleForm.phone"
              placeholder="请输入电话号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="账号名称" prop="loginName">
            <el-input
              v-model="ruleForm.loginName"
              placeholder="请输入账号名称"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pwd" v-if="title === '新增'">
            <el-input
              v-model="ruleForm.pwd"
              autocomplete="new-password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色名称:" prop="roleId">
            <el-select
              v-model="ruleForm.roleId"
              placeholder="请选择角色"
              style="width: 100%"
            >
              <el-option
                :label="item.roleDescription"
                v-for="item in roleList"
                :key="item.id"
                :value="item.id + ''"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel('addUserForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="submitForm('addUserForm')"
            size="small"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
    <!-- 风场详情 -->
    <el-dialog title="修改密码" :visible.sync="unusualdialog" width="500px">
      <div v-loading="loadingView" class="views">
        <el-form
          :model="editUserPassword"
          ref="editUserPassword"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="旧密码"
            prop="oldPWD"
            :rules="[{ required: true, message: '旧密码不能为空' }]"
          >
            <el-input
              v-model.number="editUserPassword.oldPWD"
              autocomplete="off"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item
            label="新密码"
            prop="newPWD"
            :rules="[{ required: true, message: '新密码不能为空' }]"
          >
            <el-input
              v-model.number="editUserPassword.newPWD"
              autocomplete="off"
              show-password
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              () => {
                this.$refs['editUserPassword'].resetFields();
                this.unusualdialog = false;
                this.loadingView = false;
              }
            "
            size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="editUserPwd('editUserPassword')"
            size="small"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserTableList,
  getRoleTableList,
  enableUser,
  disableUser,
  getUserInfoByUserId,
  addUser,
  editUser,
  deleteUserInfo,
  updatePWD,
} from "@/api/system.js";
export default {
  data() {
    const validateUserName = (rule, value, callback) => {
      const regex = /^[^\u4e00-\u9fa5\W]+$/;
      if (!value) {
        callback(new Error("账号名称不能为空"));
      } else if (!regex.test(value)) {
        callback(new Error("账号名称不能包含中文及特殊字符"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^[1][3-9][0-9]{9}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
      if (!phoneRegex.test(value)) {
        return callback(new Error("请输入正确的手机号"));
      }
      callback();
    };
    return {
      loadingView: false,
      loading: false, //数据加载中
      rules: {
        roleId: { trigger: "change" },
        userName: { trigger: "blur" },
      },
      roleList: [],
      formInline: {
        userName: undefined,
        roleId: undefined,
        pageNum: 1,
        pageSize: 10,
        // sort: "desc",
        totalSize: 0,
      },
      tableData: [],
      // 新增编辑表单
      ruleForm: {
        phone: null,
        pwd: null,
        roleId: null,
        userName: null,
        loginName: null,
      },
      addUserRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        loginName: [
          { required: true, message: "请输入账号名称", trigger: "blur" },
          { validator: validateUserName, trigger: "blur" },
        ],
        pwd: { required: true, message: "请输入密码", trigger: "blur" },
        roleId: { required: true, message: "请选择角色", trigger: "change" },
        userName: [
          { required: true, message: "请输入员工姓名", trigger: "blur" },
        ],
      },
      //修改密码
      editUserPassword: {
        oldPWD: "",
        newPWD: "",
        userId: "",
      },
      nuedialog: false,
      unusualdialog: false,
      title: "",
    };
  },
  created() {
    this.getTableList();
    this.getRoleList();
  },

  methods: {
    //修改密码
    editUserPwd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingView = true;
          updatePWD({ ...this.editUserPassword })
            .then((res) => {
              this.$message({
                message: "密码修改成功",
                type: "success",
              });
              this.getTableList();
              this.unusualdialog = false;
              this.loadingView = false;
            })
            .catch(() => {
              this.loadingView = false;
            });
        } else {
          return false;
        }
      });
    },
    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.getTableList();
    },
    //修改状态
    setState(state, userId) {
      switch (state) {
        case 1:
          //启用接口
          enableUser({ userId })
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.getTableList();
            })
            .catch((error) => {});
          break;
        case 2:
          //禁用接口
          disableUser({ userId })
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.getTableList();
            })
            .catch((error) => {});
          break;
        default:
          return;
      }
    },
    async getTableList() {
      try {
        this.loading = true;
        const result = await getUserTableList({
          ...this.formInline,
          totalSize: undefined,
        });
        this.tableData = result.data.list;
        this.formInline.totalSize = result.data.totalSize;
        this.loading = false;
      } catch (error) {
        this.$message({
          type: "error",
          message: "请检查是否连接网络",
        });
      }
    },
    async getRoleList() {
      try {
        const result = await getRoleTableList({ pageNum: 1, pageSize: 100000 });
        this.roleList = result.data.list;
      } catch (error) {
        this.$message({
          type: "error",
          message: "请检查是否连接网络",
        });
      }
    },
    rowStyle() {
      return "text-align:center";
    },
    // 查询
    onSubmit() {
      this.getTableList();
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields();
      this.getTableList();
    },

    // 新增,编辑确定
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingView = true;
          switch (this.title) {
            case "新增":
              addUser({ ...this.ruleForm, userId: undefined })
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.getTableList();
                  this.nuedialog = false;
                  this.loadingView = false;
                })
                .catch(() => {
                  this.loadingView = false;
                });

              break;
            case "编辑":
              editUser({ ...this.ruleForm })
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.getTableList();
                  this.nuedialog = false;
                  this.loadingView = false;
                })
                .catch(() => {
                  this.loadingView = false;
                });

              break;
          }
          // this.nuedialog = false;
        } else {
          return false;
        }
      });
    },
    //点击取消
    cancel(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields();
      this.ruleForm = {
        phone: null,
        pwd: null,
        roleId: null,
        userName: null,
        userId: null,
        loginName: null,
      };
      this.nuedialog = false;
      this.loadingView = false;
    },
    //异常详情
    particulars(row) {
      this.unusualdialog = true;
    },
    // 编辑 回显数据
    async compile(row) {
      try {
        const result = await getUserInfoByUserId({ userId: row.userId });
        const userInfo = result.data;

        // 直接替换整个对象，以确保 Vue 的响应式系统能够检测到变化
        this.ruleForm = {
          phone: userInfo.userPhone,
          pwd: undefined, // 如果需要重置密码字段
          roleId: userInfo.roleId.toString(),
          userName: userInfo.userName,
          userId: userInfo.userId, // 如果需要用户ID
          loginName: userInfo.loginName,
        };
        this.nuedialog = true;
        this.title = "编辑";
      } catch (error) {
        this.$message.error("获取用户信息失败");
      }
    },
    // 删除
    deleted(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteUserInfo({ userId: row.userId })
            .then((res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getTableList();
            })
            .catch(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editPwd(row) {
      this.editUserPassword.userId = row.userId;
      this.unusualdialog = true;
    },
    // 新增
    newnuedialog() {
      this.cancel("addUserForm");
      this.ruleForm = {
        loginName: "",
        pwd: "",
        userName: "",
      };
      this.nuedialog = true;
      this.title = "新增";
    },
  },
};
</script>

<style lang="scss" scoped>
.general {
  display: flex;
  flex-wrap: wrap;

  .condition {
    width: 50%;
    display: flex;

    p {
      width: 100px;
      text-align: right;
      line-height: 40px;
    }

    span {
      line-height: 40px;

      padding-left: 20px;
    }

    .el-select {
      width: 100%;
      margin-bottom: 20px;
    }

    .el-input {
      margin-bottom: 20px;
    }
  }
}

.attachment {
  display: flex;
  padding-top: 10px;

  p {
    margin-right: 20px;
    color: #409eff;
  }
}

.addition {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.demo-ruleForm {
  .el-form-item {
    margin-bottom: 25px;
  }
}
</style>
