<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">用户管理</span>
    </div>
    <div class="scroll">
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <span>状态 :</span>
            <el-select
              clearable
              v-model="searchInput.status"
              placeholder="请选择状态"
            >
              <el-option label="正常" :value="1" />
              <el-option label="冻结" :value="2" />
            </el-select>
          </div>
          <div class="condition">
            <span>姓名 :</span>
            <el-input
              clearable
              v-model.trim="searchInput.keyWord"
              class="w-50 m-2"
              placeholder="请输入姓名"
              style="width: 180px"
              @clear="searchBtn"
            />
          </div>
          <div class="condition">
            <span>创建时间 :</span>
            <el-date-picker
              v-model="searchInput.createTime"
              type="datetimerange"
              range-separator="-"
              start-placeholder="起始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择日期"
            />
          </div>
          <el-button
            style="margin-left: 20px"
            color="rgba(38, 151, 255, 1)"
            type="primary"
            class="search"
            @click="searchBtn"
            ><span>查询</span></el-button
          >
          <el-button @click="resetBtn" plain color="rgba(43, 153, 255, 1)"
            >重置</el-button
          >
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button
            v-if="store.BtnRole('accountManagementSetting1')"
            type="primary"
            style="margin-left: 0"
            color="rgba(38, 151, 255, 1)"
            @click="addlist"
            >添加用户</el-button
          >
        </div>
      </div>
      <div class="footer" v-loading="loading">
        <el-table
          :row-class-name="tableRowClassName"
          :data="tableData.list"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }"
        >
          <el-table-column
            width="80"
            align="center"
            label="序号"
            type="index"
            index="1"
          />
          <el-table-column align="center" prop="account" label="账号" />
          <el-table-column align="center" prop="roleName" label="角色" />
          <el-table-column
            align="center"
            prop="departmentList"
            label="可管理部门"
            width="300"
            ><template #default="{ row }">
              <div class="ul" style="display: flex; flex-wrap: wrap">
                <el-tag
                  v-for="i in row.welcomeOrgList"
                  :key="i.id"
                  style="margin: 5px"
                  type="primary"
                  >{{ i.name }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="真实姓名" />
          <el-table-column align="center" prop="phone" label="手机号" />
          <el-table-column align="center" prop="createTime" label="创建时间" />
          <el-table-column align="center" prop="name" label="状态">
            <template #default="{ row }">
              <span v-if="row.status == 2" style="color: #fa9e19">冻结</span>
              <span v-if="row.status == 1" style="color: #2697ff">正常</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="160"
            fixed="right"
          >
            <template #default="{ row }">
              <div class="options" v-if="roleId == 1">
                <div v-if="row.id == 1"></div>
                <div v-else>
                  <span
                    v-if="store.BtnRole('accountManagementSetting2')"
                    class="edit"
                    @click="updateS(row)"
                    >编辑</span
                  >
                  <span
                    v-if="store.BtnRole('accountManagementSetting3')"
                    class="delete"
                    @click="deleteS(row)"
                    >删除</span
                  >
                </div>
              </div>
              <div class="options" v-else-if="roleId == 10">
                <div v-if="row.id == 1"></div>
                <div v-else-if="row.roleId == 10"></div>
                <div v-else>
                  <span
                    v-if="store.BtnRole('accountManagementSetting2')"
                    class="edit"
                    @click="updateS(row)"
                    >编辑</span
                  >
                  <span
                    v-if="store.BtnRole('accountManagementSetting3')"
                    class="delete"
                    @click="deleteS(row)"
                    >删除</span
                  >
                </div>
              </div>
              <div class="options" v-else-if="roleId == 2">
                <div v-if="row.id == 1"></div>
                <div v-else-if="row.roleId == 10"></div>
                <div v-else-if="row.roleId == 2"></div>
                <div v-else-if="row.roleId == 11"></div>
                <div v-else-if="row.roleId == 12"></div>
                <div v-else>
                  <span
                    v-if="store.BtnRole('accountManagementSetting2')"
                    class="edit"
                    @click="updateS(row)"
                    >编辑</span
                  >
                  <span
                    v-if="store.BtnRole('accountManagementSetting3')"
                    class="delete"
                    @click="deleteS(row)"
                    >删除</span
                  >
                </div>
              </div>
              <div class="options" v-else></div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div class="pageSize">
          <span></span>
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            layout="total,sizes, prev, pager, next, jumper, slot"
            :total="total"
            @size-change="handleSizeChange"
            @update:current-page="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 添加账号弹窗 -->
    <el-dialog
      class="addStaff"
      v-model="addDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="dialongTitle"
      align-center
      width="580"
      :before-close="cancelAdd"
      destroy-on-close
      draggable
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="姓名 :" prop="name">
          <el-input
            v-model.trim="ruleForm.name"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号码 :" prop="phone">
          <el-input
            v-model.trim="ruleForm.phone"
            placeholder="请输入手机号码"
            clearable
          />
        </el-form-item>
        <el-form-item label="用户名 :" prop="account">
          <el-input
            v-model.trim="ruleForm.account"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="密码 :" prop="password">
          <el-input
            v-model.trim="ruleForm.password"
            placeholder="请输入密码"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态 :" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :value="1" size="large">正常</el-radio>
            <el-radio :value="2" size="large">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色 :" prop="roleId">
          <el-select
            clearable
            v-model="ruleForm.roleId"
            placeholder="请选择角色"
          >
            <el-option
              v-for="i in roleData"
              :key="i.id"
              :label="i.roleName"
              :value="i.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门 :" prop="collegeId">
          <el-select
            @change="collegeFormChange"
            v-model="ruleForm.collegeId"
            clearable
            multiple
            placeholder="请选择部门"
          >
            <el-option
              v-for="i in collegeData"
              :key="i.id"
              :label="i.name"
              :value="`${i.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="options">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button
            color="rgba(0, 97, 255, 1)"
            class="queding"
            type="primary"
            @click="submitAdd(ruleFormRef)"
          >
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import lodash from "lodash";
import { https } from "@/utils/request"; // 绝对路径

import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/index";

const router = useRouter();
const store = useCounterStore();

// 为避免解构时失去响应性
const { name, age, isCollapse, realAge, roleId } = storeToRefs(store);

// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [{}],
});
const activeIndex = ref(); // 默认跳转路由
const dialongTitle = ref("新增账号"); // 弹窗标题

const searchInput = reactive({
  keyWord: "",
  status: "",
  createTime: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectIds = ref([]);

const addDialogVisible = ref(false); // 控制添加账号弹窗
// 学院
const collegeData = ref([]);
const roleData = ref([]);

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  name: "", //名称
  account: "", //账号
  phone: "", //手机号
  status: 1, //状态 2：冻结 ，1正常
  password: "", //密码
  roleId: "", //角色id
  collegeId: [], //学院id，多个用逗号隔开
  id: "",
});
// 表单验证
const rules = reactive({
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  account: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    {
      min: 8,
      max: 20,
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式有误，请重新输入",
      trigger: "blur",
    },
  ],
  status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      min: 8,
      max: 20,
      pattern:
        /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\._\+(){}])[0-9a-zA-Z!@#$%^&*,\\._\+(){}]{8,20}$/,
      message: "请输入8-20位正确密码（大小写字母·字符·数字）",
      trigger: "blur",
    },
  ],
  roleId: [{ required: true, message: "角色不能为空", trigger: "blur" }],
  collegeId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
});

const schoolData = ref();

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    keyWord: searchInput.keyWord,
    status: searchInput.status,
  };
  if (searchInput.createTime) {
    params.startTime = searchInput.createTime[0];
    params.endTime = searchInput.createTime[1];
  }

  let res = await https.get(
    "/welcome/api/welcomeAccount/listAccount",
    "params",
    params
  );
  console.log(res, "账号信息");
  if (res.code == 200) {
    res.data.list.forEach((i) => {
      if (i.welcomeRole) {
        i.roleName = i.welcomeRole.roleName;
      }
    });
    tableData.list = res.data.list;
    total.value = res.data.totalCount;
    loading.value = false;
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const roleList = async () => {
  let res = await https.get("/welcome/api/welcomeRole/roleGroup", "params");
  console.log(res, "角色数据");
  if (res.code == 200) {
    roleData.value = res.data.filter((i) => {
      if (roleId.value == 1) {
        return i.id != 1;
      } else if (roleId.value == 2) {
        return i.id != 1 && i.id != 10 && i.id != 2 && i.id != 11 && i.id != 12;
      } else if (roleId.value == 10) {
        return i.id != 1 && i.id != 10;
      } else {
        return [];
      }
    });
    console.log(roleData.value, "重组后角色数据");
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const collegeList = async () => {
  let res = await https.get("/welcome/api/welcomeOrg/getColleges", "params");
  console.log(res, "学院数据");
  if (res.code == 200) {
    collegeData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);
const resetBtn = lodash.debounce(async () => {
  searchInput.keyWord = null;
  searchInput.status = null;
  searchInput.createTime = null;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增用户";
  addDialogVisible.value = true;
  ruleForm.id = null;
  ruleForm.name = null;
  ruleForm.account = null;
  ruleForm.phone = null;
  ruleForm.status = 1;
  ruleForm.password = null;
  ruleForm.roleId = null;
  ruleForm.collegeId = null;
};
// 添加账号
const updateS = (row) => {
  console.log(row, row.collegeId.split(","));

  dialongTitle.value = "编辑用户";
  addDialogVisible.value = true;
  ruleForm.id = row.id;
  ruleForm.name = row.name;
  ruleForm.account = row.account;
  ruleForm.phone = row.phone;
  ruleForm.status = row.status;
  ruleForm.password = row.password;
  ruleForm.roleId = row.roleId;
  ruleForm.collegeId = row.collegeId.split(",");
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = {
        accountId: row.id,
      };
      let res = await https.get(
        "/welcome/api/welcomeAccount/deleteAccount",
        "params",
        data
      );
      if (res.code == 200) {
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
        getList();
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 确认添加员工
const submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        name: ruleForm.name,
        account: ruleForm.account,
        phone: ruleForm.phone,
        status: ruleForm.status,
        password: ruleForm.password,
        roleId: ruleForm.roleId,
        collegeId: ruleForm.collegeId.join(","),
      };
      if (ruleForm.id) {
        data.id = ruleForm.id;
        let res = await https.post(
          "/welcome/api/welcomeAccount/updateAccount",
          "data",
          data
        );
        if (res.code == 200) {
          addDialogVisible.value = false;
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.message,
            center: true,
          });
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.message,
            center: true,
          });
        }
      } else {
        let res = await https.post(
          "/welcome/api/welcomeAccount/saveAccount",
          "data",
          data
        );
        if (res.code == 200) {
          addDialogVisible.value = false;
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.message,
            center: true,
          });
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
      loading.value = false;
    }
  });
}, 1000);
const cancelAdd = () => {
  addDialogVisible.value = false;
  // ruleFormRef.value.resetFields();
};
// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectIds.value = val.map((i) => i.id);
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 每页显示条数
const handleSizeChange = (value) => {
  console.log(value, "每页显示条数");
  pageSize.value = value;
  getList();
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};

onBeforeMount(() => {
  getList();
  roleList();
  collegeList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: calc(100% - 40px);
  height: calc(100% - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #000;
  display: flex;
  flex-direction: column;

  .svg {
    width: 22px;
    height: 22px;
  }

  .left {
    width: calc(100% - 60px);
    height: 60px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;
    .camera {
      margin-right: 15px;
      color: #4392f7;
    }
  }
  .scroll {
    width: calc(100% - 60px);
    height: calc(100% - 61px);
    margin: 0 auto;
    display: flex;
    flex-direction: column;

    .middle {
      width: calc(100%);
      color: #000;
      .filter {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        .search {
          margin-left: 0 !important;
          color: #fff;
        }
        .condition {
          display: flex;
          align-items: center;
          margin: 10px 30px 10px 0;
          :deep(.el-input .el-input__inner) {
            font-size: 14px;
          }
          .el-select {
            width: 220px;
          }
          span {
            margin: 0 10px 0 0;
          }
        }
      }
      .gongneng {
        margin: 10px 0;
        .el-button {
          color: #fff;
          margin-right: 15px;
        }
      }
    }
    .footer {
      width: calc(100%);
      flex: 1;
      margin: 0 auto;
      overflow: auto;

      .el-table--fit {
        height: calc(100% - 60px);
        :deep(.el-table__header-wrapper) {
          background-color: #000;
          font-size: 15px;
          color: #000;
          .cell {
            color: #000;
          }
        }
        :deep(.el-table__row) {
          height: 50px;
          font-size: 15px;
          color: #000;
        }
        :deep(.el-table__row td) {
          padding: 0;
          border: 0;
        }

        .el-button--primary {
          margin-left: 5px;
        }
        :deep(.el-table__body .even) {
          background-color: #fff;
        }
        :deep(.el-table__body .odd) {
          background-color: rgba(240, 243, 247, 1);
        }
        :deep(.options) {
          display: flex;
          justify-content: center;
          align-items: center;
          .edit {
            margin: 0 15px 0 0;
            color: rgba(0, 186, 173, 1);
            cursor: pointer;
          }
          .delete {
            color: rgba(212, 48, 48, 1);
            cursor: pointer;
          }
        }
      }

      .pageSize {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 0 30px;
        height: 60px;

        span {
          color: #000;
        }

        .el-pagination {
          // width: 1600px;
          :deep(.el-pagination__total) {
            color: #000;
          }

          :deep(.el-pagination__goto) {
            color: #000;
          }

          :deep(.el-pagination__classifier) {
            color: #000;
          }

          :deep(.el-input__wrapper) {
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            box-shadow: none;
          }

          :deep(.el-pager li) {
            margin: 0 5px;
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            background-color: transparent;
          }

          :deep(.el-pager li.is-active) {
            // background-color: rgba(0, 97, 255, 0.8);
            border: 1px solid rgba(0, 97, 255, 1);
            color: rgba(0, 97, 255, 1);
          }

          :deep(.btn-prev) {
            margin-right: 5px;
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            background-color: transparent;
          }

          :deep(.btn-next) {
            margin-left: 5px;
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            background-color: transparent;
          }
        }
      }
    }
  }

  // 添加员工弹窗样式
  :deep(.addStaff) {
    .el-dialog__body {
      padding: 20px 20px 10px 20px;
      .el-input {
        width: 400px;
        .el-input__suffix-inner {
          color: rgba(61, 81, 232, 1);
        }
      }
      .el-select {
        width: 400px;
      }
      .el-tree {
        width: 400px;
      }
      .el-form {
        .el-form-item {
          display: flex;
          align-items: center;
        }
        .options {
          margin-top: 30px;
        }
      }
    }
  }
}
</style>
