<template>
  <div class="task-manage-page">
    <div class="toolbar-container">
      <div class="search-box">
        <el-input
          placeholder="请输入用户名搜索"
          v-model="inputUsername"
          prefix-icon="el-icon-search"
          clearable
          size="small"
          @clear="cancelSearch()"
          @keyup.enter.native="searchUser()"
        >
          <i
            slot="suffix"
            class="el-input__icon el-icon-search"
            @click="searchUser()"
            style="cursor: pointer;"
          ></i>
        </el-input>
      </div>
      <div class="toolbar-actions">
        <el-button
          class="forest-btn-small"
          size="medium"
          icon="el-icon-plus"
          @click="adduser1()"
          >添加用户</el-button
        >
      </div>
    </div>

    <el-table
      id="tableStyle"
      :data="usersData"
      :max-height="600"
      stripe
      border
      highlight-current-row
      header-cell-class-name="sinCl"
    >
      <el-table-column
        fixed="left"
        prop="username"
        label="用户名称"
        min-width="100"
      ></el-table-column>
      <el-table-column
        fixed="left"
        prop="realName"
        label="真实姓名"
        min-width="100"
      ></el-table-column>
      <el-table-column prop="role" label="权限" min-width="80">
        <template slot-scope="scope">
          <el-select size="small" v-model="scope.row.role" placeholder="请选择">
            <el-option
              v-for="item in idenOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="280" fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            class="action-btn"
            @click.native="EditField(scope.$index)"
            >确认</el-button
          >
          <el-button
            type="text"
            size="small"
            class="action-btn"
            @click.native="deleteField(scope.$index)"
            >删除</el-button
          >
            <el-button
            type="text"
            size="small"
            class="action-btn"
            @click.native="resetPassword(scope.$index)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        layout="prev, pager, next"
        :page-count="dataPageNum"
        @current-change="pageChange"
      ></el-pagination>
    </div>

    <el-dialog
      v-dialogDrag
      class="taskDialog"
      title="添加用户"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
    >
      <div style="text-align: left">
        <el-form
          ref="account"
          :model="account"
          :rules="rules"
          label-width="130px"
          style="margin-top: 20px"
        >
          <el-form-item prop="username" label="用户名：">
            <el-input
              style="width: 90%"
              type="text"
              v-model="account.username"
              auto-complete="off"
              :autofocus="true"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="realName" label="真实姓名：">
            <el-input
              style="width: 90%"
              type="text"
              v-model="account.realName"
              auto-complete="off"
              :autofocus="true"
              placeholder="请输入真实姓名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码：">
            <el-input
              style="width: 90%"
              type="password"
              v-model="account.password"
              auto-complete="off"
              :autofocus="true"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password1" label="确认密码：">
            <el-input
              style="width: 90%"
              type="password"
              v-model="account.password1"
              auto-complete="off"
              :autofocus="true"
              placeholder="请确认密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="role" label="权限：">
            <el-select
              style="width: 90%"
              size="small"
              v-model="account.role"
              placeholder="请选择"
            >
              <el-option
                v-for="item in idenOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button class="forest-btn-small" @click="addUser()"
        >确认</el-button
      >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { ajax as request } from "@/request.js";
import md5 from "js-md5";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.account.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validpassword = (rule, value, callback) => {
      let reg = /[0-9a-zA-Z]{6,18}/;
      if (!reg.test(value)) {
        callback(new Error("密码必须是由6-18位数字和字母组合"));
      } else {
        callback();
      }
    };

    return {
      isSearch: false,
      currentSearchUser: "",
      inputUsername: "",
      dataPageNum: 1,
      currentPage: 1,
      account: {
        username: "",
        realName: "",
        password: "",
        password1: "",
        role: "Worker",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validpassword, trigger: "blur" },
        ],
        password1: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
      },
      dialogVisible: false,
      screenHeight: document.documentElement.clientHeight,
      usersData: [],
      idenOptions: [
        {
          value: "Admin",
          label: "管理员",
        },
        {
          value: "Leader",
          label: "领导人员",
        },
        {
          value: "Worker",
          label: "外业人员",
        },
        {
          value: "Operator",
          label: "工作人员",
        },
        {
          value: "SuperAdmin",
          label: "超级管理员",
        },
      ],
    };
  },
  methods: {
    init() {
      let that = this;
      request({
        url: "/user/all",
        method: "get",
        params: {
          page: 1,
        },
      }).then(function (response) {
        //登录成功获取数据存入usersData
        if (response.data.success) {
          that.usersData = response.data.data.users;
          that.dataPageNum = response.data.data.totalPages;
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
    },
    pageChange(val) {
      let that = this;
      this.usersData = [];
      this.currentPage = val;
      if (this.isSearch) {
        request({
          url: "/user/search",
          method: "post",
          params: { page: 1, username: that.currentSearchUser },
        }).then(function (response) {
          //上传成功
          if (response.data.success) {
            that.usersData = response.data.data.users;
            that.dataPageNum = response.data.data.totalPages;
          } else if (response.data.status == "401") {
            that.$alert(response.data.message);
            that.$router.push({ path: "/login" });
          }
        });
      } else {
        request({
          url: "/user/all",
          method: "post",
          params: {
            page: val,
          },
        }).then(function (response) {
          if (response.data.success) {
            that.usersData = response.data.data.users;
          }
        });
      }
    },
  //重置密码
  resetPassword(index) {
  let that = this;
  this.$confirm("确认重置该用户密码？", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
  })
    .then(() => {
      // 调用重置密码接口
      request({
        url: "/user/resetPassword",
        method: "post",
        params: {
          id: that.usersData[index].id,
        },
      }).then(function (response) {
        if (response.data.success) {
          that.$notify.success({
            title: "提示",
            message: "密码已成功重置为默认密码！",
          });
        } else {
          that.$notify.error({
            title: "提示",
            message: response.data.message || "密码重置失败",
          });
        }
      });
      // 刷新用户列表
      request({
        url: "/user/all",
        method: "post",
        params: {
          page: that.currentPage,
        },
      }).then(function (response) {
        if (response.data.success) {
          that.usersData = response.data.data.users;
        }
      });
    })
    .catch(() => {
      that.$notify.info({
        title: "提示",
        message: "已取消操作",
      });
    });
},
    deleteField(index) {
      let that = this;
      this.$confirm("确认删除？", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确认",
        type: "warning",
      })
        .then(() => {
          request({
            url: "/user/delete",
            method: "post",
            params: {
              id: that.usersData[index].id,
            },
          }).then(function (response) {
            if (response.data.success) {
              that.$notify.success({
                title: "提示",
                message: "删除成功！",
              });
            } else {
              that.$notify.error({
                title: "提示",
                message: "删除失败",
              });
            }
          });
          request({
            url: "/user/all",
            method: "post",
            params: {
              page: that.currentPage,
            },
          }).then(function (response) {
            if (response.data.success) {
              that.usersData = response.data.data.users;
            }
          });
        })
        .catch(() => {
          this.$notify.error({
            title: "提示",
            message: "删除失败",
          });
        });
    },
    EditField(index) {
      let that = this;
      request({
        url: "/user/role_change",
        method: "post",
        params: {
          id: that.usersData[index].id,
          role: that.usersData[index].role,
        },
      }).then(function (response) {
        //上传成功
        if (response.data.success) {
          that.$notify.success({
            title: "提示",
            message: "提交成功！",
          });
          that.init();
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        }
      });
      request({
        url: "/user/all",
        method: "post",
        params: {
          page: that.currentPage,
        },
      }).then(function (response) {
        if (response.data.success) {
          that.usersData = response.data.data.users;
        }
      });
    },
    cancelSearch() {
      this.isSearch = false;
      this.inputUsername = "";
    },
    searchUser() {
      this.isSearch = true;
      let that = this;
      this.currentSearchUser = this.inputUsername;
      request({
        url: "/user/search",
        method: "post",
        params: { page: 1, username: that.currentSearchUser },
      }).then(function (response) {
        //上传成功
        if (response.data.success) {
          that.usersData = response.data.data.users;
          that.dataPageNum = response.data.data.totalPages;
        } else if (response.data.status == "401") {
          that.$alert(response.data.message);
          that.$router.push({ path: "/login" });
        } else {
          that.$notify.error({
            title: "提示",
            message: "未查找到符合条件的用户！",
          });
        }
      });
    },
    addUser() {
      let that = this;
      this.$refs.account.validate((valid) => {
        if (valid) {
          let that = this;
          request({
            url: "/user/new",
            method: "post",
            params: {
              username: that.account.username,
              realName: that.account.realName,
              password: md5(md5(that.account.password)),
              role: that.account.role,
            },
          }).then(function (response) {
            if (response.data.success) {
              that.dialogVisible = false;
              that.$notify.success({
                title: "提示",
                message: "添加成功！",
              });
              that.init();
            } else if (response.data.status == "401") {
              that.$alert(response.data.message);
              that.$router.push({ path: "/login" });
            }
          });
        }
      });
    },
    adduser1() {
      this.dialogVisible = true;
      this.account = {
        username: "",
        realName: "",
        password: "",
        password1: "",
        role: "Worker",
      };
    },
  },
  mounted() {
    this.init();
  },
};
</script>
<style scoped lang="scss">
.task-manage-page {
  padding: 24px 28px 40px;
  background: linear-gradient(135deg, #edf7ef 0%, #fdfefe 100%);
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  border-radius: 20px;
  box-shadow: 0 14px 32px rgba(76, 175, 80, 0.12);
  border: 1px solid rgba(129, 199, 132, 0.25);
  }

.toolbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  flex: 0 0 auto;
  width: 450px;
}

:deep(.search-box .el-input) {
  width: 100%;
}

.toolbar-actions {
  display: flex;
  gap: 16px;
  flex: 0 0 auto;
}

.forest-btn-small {
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  border: none;
  color: #fff;
  border-radius: 10px;
  padding: 8px 20px;
  font-weight: 600;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
  transition: all 0.3s ease;
}

.forest-btn-small:hover:not(:disabled) {
  filter: brightness(1.05);
  transform: translateY(-1px);
}

.forest-btn-small:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

#tableStyle {
  margin-bottom: 30px;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid rgba(129, 199, 132, 0.3);
  box-shadow: 0 14px 28px rgba(76, 175, 80, 0.12);
}

:deep(#tableStyle .el-table__header-wrapper th) {
  background: linear-gradient(90deg, #e0f0e2, #f2fbf3) !important;
  color: #1b5e20 !important;
  font-weight: 600 !important;
  border-bottom: 1px solid rgba(129, 199, 132, 0.35) !important;
  font-size: 14px !important;
  font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif !important;
}

:deep(#tableStyle .el-table__body-wrapper td) {
  color: #2e4b31;
  border-bottom: 1px solid rgba(76, 175, 80, 0.08);
}

:deep(#tableStyle .el-table__body tr:hover > td) {
  background: rgba(129, 199, 132, 0.15) !important;
  color: #1b5e20;
}

:deep(#tableStyle .el-table__row--striped td) {
  background: rgba(233, 247, 235, 0.65);
}

:deep(#tableStyle .el-table__row.current-row > td) {
  background: rgba(76, 175, 80, 0.18) !important;
  color: #1b5e20;
}

:deep(#tableStyle .el-table__body tr) {
  transition: transform 0.15s ease, box-shadow 0.15s ease;
}

:deep(#tableStyle .el-table__body tr:hover) {
  transform: translateY(-1px);
  box-shadow: inset 0 2px 0 rgba(76, 175, 80, 0.15);
}

:deep(#tableStyle .el-button--text) {
  color: #2e7d32;
  font-weight: 500;
  padding: 6px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(#tableStyle .el-button--text:hover) {
  color: #1b5e20;
  background: rgba(129, 199, 132, 0.2);
  transform: translateY(-1px);
}

.action-btn {
  color: #2e7d32 !important;
  font-weight: 500 !important;
  padding: 6px 12px !important;
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
}

.action-btn:hover {
  color: #1b5e20 !important;
  background: rgba(129, 199, 132, 0.2) !important;
  transform: translateY(-1px) !important;
}

/* 下拉选择框样式 */
:deep(#tableStyle .el-select .el-input__inner) {
  border-color: rgba(129, 199, 132, 0.4) !important;
  color: #1b5e20 !important;
}

:deep(#tableStyle .el-select .el-input__inner:focus) {
  border-color: #4caf50 !important;
}

:deep(#tableStyle .el-select .el-input__suffix .el-input__suffix-inner .el-select__caret) {
  color: #4caf50 !important;
}

/* 滚动条样式 */
:deep(#tableStyle .el-table.el-table--scrollable-x .el-table__body-wrapper) {
  scrollbar-width: thin !important;
  scrollbar-color: rgba(76, 175, 80, 0.4) rgba(232, 245, 233, 0.5) !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-x .el-table__body-wrapper::-webkit-scrollbar) {
  height: 8px !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-x .el-table__body-wrapper::-webkit-scrollbar-track) {
  background: rgba(232, 245, 233, 0.5) !important;
  border-radius: 4px !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-x .el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: linear-gradient(90deg, #81c784, #66bb6a) !important;
  border-radius: 4px !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-x .el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(90deg, #66bb6a, #4caf50) !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-y .el-table__body-wrapper) {
  scrollbar-width: thin !important;
  scrollbar-color: rgba(76, 175, 80, 0.4) rgba(232, 245, 233, 0.5) !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-y .el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-y .el-table__body-wrapper::-webkit-scrollbar-track) {
  background: rgba(232, 245, 233, 0.5) !important;
  border-radius: 4px !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-y .el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: linear-gradient(180deg, #81c784, #66bb6a) !important;
  border-radius: 4px !important;
}

:deep(#tableStyle .el-table.el-table--scrollable-y .el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(180deg, #66bb6a, #4caf50) !important;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

:deep(.pagination-container .el-pagination) {
  .el-pager li {
    background: rgba(255, 255, 255, 0.9) !important;
    color: #2e7d32 !important;
    border: 1px solid rgba(129, 199, 132, 0.3) !important;
    border-radius: 6px !important;
    margin: 0 4px !important;
    transition: all 0.3s ease !important;
  }
  
  .el-pager li:hover {
    background: rgba(129, 199, 132, 0.2) !important;
    color: #1b5e20 !important;
    transform: translateY(-2px) !important;
  }
  
  .el-pager li.active {
    background: linear-gradient(135deg, #4caf50, #2e7d32) !important;
    color: #fff !important;
    border-color: #4caf50 !important;
    font-weight: 600 !important;
  }
  
  .btn-prev,
  .btn-next {
    background: rgba(255, 255, 255, 0.9) !important;
    color: #2e7d32 !important;
    border: 1px solid rgba(129, 199, 132, 0.3) !important;
    border-radius: 6px !important;
    transition: all 0.3s ease !important;
  }
  
  .btn-prev:hover,
  .btn-next:hover {
    background: rgba(129, 199, 132, 0.2) !important;
    color: #1b5e20 !important;
    transform: translateY(-2px) !important;
  }
  
  .btn-prev:disabled,
  .btn-next:disabled {
    opacity: 0.5 !important;
    cursor: not-allowed !important;
  }
}

.taskDialog :deep(.el-dialog) {
  border-radius: 18px;
  border: 1px solid rgba(129, 199, 132, 0.35);
  box-shadow: 0 12px 30px rgba(76, 175, 80, 0.18);
}

.taskDialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #4caf50, #2e7d32);
  color: #fff;
  border-radius: 18px 18px 0 0;
}

.taskDialog :deep(.el-form-item__label) {
  color: #1b5e20;
  font-weight: 600;
}

.taskDialog :deep(.el-input__inner) {
  border-color: rgba(129, 199, 132, 0.4) !important;
}

.taskDialog :deep(.el-input__inner:focus) {
  border-color: #4caf50 !important;
}

.taskDialog :deep(.el-select .el-input__inner) {
  border-color: rgba(129, 199, 132, 0.4) !important;
}

.taskDialog :deep(.el-select .el-input__inner:focus) {
  border-color: #4caf50 !important;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-select-dropdown) {
  border: 1px solid rgba(129, 199, 132, 0.3) !important;
  border-radius: 10px !important;
  box-shadow: 0 8px 20px rgba(76, 175, 80, 0.15) !important;
}

:deep(.el-select-dropdown .el-select-dropdown__item) {
  color: #2e4b31 !important;
}

:deep(.el-select-dropdown .el-select-dropdown__item:hover) {
  background: rgba(129, 199, 132, 0.2) !important;
  color: #1b5e20 !important;
}

:deep(.el-select-dropdown .el-select-dropdown__item.selected) {
  background: rgba(76, 175, 80, 0.25) !important;
  color: #1b5e20 !important;
  font-weight: 600 !important;
}
</style>

<style>
/* 全局表格样式覆盖 */
#tableStyle.el-table {
  border: 1px solid rgba(129, 199, 132, 0.3) !important;
  border-radius: 16px !important;
  overflow: hidden !important;
}

#tableStyle.el-table.el-table--border {
  border: 1px solid rgba(129, 199, 132, 0.3) !important;
}

#tableStyle.el-table.el-table--border::after,
#tableStyle.el-table.el-table--border::before {
  background-color: rgba(129, 199, 132, 0.3) !important;
}

#tableStyle.el-table.el-table--border th {
  border-right: 1px solid rgba(129, 199, 132, 0.25) !important;
}

#tableStyle.el-table.el-table--border th:last-child {
  border-right: none !important;
}

#tableStyle.el-table.el-table--border td {
  border-right: 1px solid rgba(76, 175, 80, 0.08) !important;
}

#tableStyle.el-table.el-table--border td:last-child {
  border-right: none !important;
}

#tableStyle.el-table.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: rgba(233, 247, 235, 0.65) !important;
}

#tableStyle.el-table.el-table--striped .el-table__body tr.el-table__row--striped:hover td {
  background: rgba(200, 230, 201, 0.5) !important;
}

/* 表头样式全局覆盖 */
#tableStyle.el-table .el-table__header-wrapper th {
  background: linear-gradient(90deg, #e0f0e2, #f2fbf3) !important;
  color: #1b5e20 !important;
  font-weight: 600 !important;
  border-bottom: 1px solid rgba(129, 199, 132, 0.35) !important;
  font-size: 14px !important;
  font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif !important;
}

#tableStyle.el-table .el-table__header-wrapper thead th {
  background: linear-gradient(90deg, #e0f0e2, #f2fbf3) !important;
  color: #1b5e20 !important;
}

#tableStyle.el-table .el-table__header th {
  background: linear-gradient(90deg, #e0f0e2, #f2fbf3) !important;
  color: #1b5e20 !important;
  font-weight: 600 !important;
  border-bottom: 1px solid rgba(129, 199, 132, 0.35) !important;
}

#tableStyle.el-table .el-table__header th .cell {
  color: #1b5e20 !important;
  font-weight: 600 !important;
  font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif !important;
}

#tableStyle.el-table .el-table__header th.sinCl {
  background: linear-gradient(90deg, #e0f0e2, #f2fbf3) !important;
  color: #1b5e20 !important;
  font-weight: 600 !important;
  border-bottom: 1px solid rgba(129, 199, 132, 0.35) !important;
}

#tableStyle.el-table .el-table__header th.sinCl .cell {
  color: #1b5e20 !important;
  font-weight: 600 !important;
}
</style>