<template>
  <div class="scroll">
    <div class="middle">
      <div class="filter">
        <div class="condition">
          <span>账号 :</span>
          <el-input
            clearable
            v-model.trim="searchInput.name"
            class="w-50 m-2"
            placeholder="请输入账号"
            style="width: 180px"
          />
        </div>
        <div class="condition">
          <span>角色 :</span>
          <el-select
            clearable
            v-model="searchInput.roleId"
            placeholder="请选择角色"
          >
            <el-option
              v-for="i in roleData"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            />
          </el-select>
        </div>
        <div class="condition">
          <span>状态 :</span>
          <el-select
            clearable
            v-model="searchInput.stateId"
            placeholder="请选择状态"
          >
            <el-option
              v-for="i in stateData"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            />
          </el-select>
        </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
          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 type="selection" align="center" width="55" /> -->
        <el-table-column type="index" align="center" label="序号" width="60" />
        <el-table-column align="center" prop="account" label="账号" />
        <el-table-column width="100" align="center" prop="roleName" label="角色">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="name"
          label="真实姓名"
        />
        <el-table-column align="center" prop="phone" label="联系方式" />
        <el-table-column align="center" label="状态">
          <template #default="{ row }">
            <span v-if="row.stateId == 1" style="color: #67c23a">正常</span>
            <span v-if="row.stateId == 2" style="color: #e6a23c">禁用</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="createAccountTime"
          label="创建时间"
        />
        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button type="primary" @click="updateS(row)" link
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteS(row)" link>删除</el-button>
          </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="560"
    :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="cardNumber">
        <el-input
          clearable
          v-model.trim="ruleForm.cardNumber"
          class="w-50 m-2"
          placeholder="请输入微校卡号"
        />
      </el-form-item>
      <el-form-item label="账号 :" prop="account">
        <el-input
          clearable
          v-model.trim="ruleForm.account"
          class="w-50 m-2"
          placeholder="请输入账号"
        />
      </el-form-item>
      <el-form-item label="密码 :" prop="password">
        <el-input
          clearable
          v-model.trim="ruleForm.password"
          class="w-50 m-2"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item label="角色 :" prop="roleId">
        <el-select v-model="ruleForm.roleId" clearable placeholder="请选择角色">
          <el-option
            v-for="i in roleData"
            :key="i.id"
            :label="i.name"
            :value="i.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="真实姓名 :" prop="name">
        <el-input
          clearable
          v-model.trim="ruleForm.name"
          class="w-50 m-2"
          placeholder="请输入真实姓名"
        />
      </el-form-item>
      <el-form-item label="联系方式 :" prop="phone">
        <el-input
          clearable
          v-model.trim="ruleForm.phone"
          class="w-50 m-2"
          placeholder="请输入联系方式"
        />
      </el-form-item>
      <el-form-item label="状态 :" prop="stateId">
        <el-radio-group v-model="ruleForm.stateId">
          <el-radio
            :value="i.id"
            size="large"
            v-for="i in stateData"
            :key="i.id"
            >{{ i.name }}</el-radio
          >
        </el-radio-group>
      </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>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import lodash from "lodash";

import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/index";
import { getQueryAccountPage, getAllStatus, getAllRole,editAccount,addAccount,deleteAccount } from "@/api/account";

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

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

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

const searchInput = reactive({
  name: "",
  roleId: "",
  stateId: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(0); // 当前总数
const selectIds = ref([]); // 勾选的全部数据

const addDialogVisible = ref(false); // 控制添加账号弹窗

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  name: "",
  account: "",
  password: "",
  cardNumber:"",
  phone: "",
  roleId: "",
  stateId: "",
  id: "",
});
// 表单验证
const rules = reactive({
  name: [{ required: true, message: "真实姓名不能为空", trigger: "blur" }],
  account: [{ 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",
    },],
  phone: [{ required: true, message: "联系方式不能为空", trigger: "blur" }],
  cardNumber: [{ required: true, message: "微校卡号不能为空", trigger: "blur" }],
  roleId: [{ required: true, message: "角色不能为空", trigger: "blur" }],
  stateId: [{ required: true, message: "状态不能为空", trigger: "blur" }],
});

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    name: searchInput.name,
    roleId: searchInput.roleId,
    stateId: searchInput.stateId,
  };
  getQueryAccountPage(params).then((res) => {
    console.log(res);
    if (res.code == 200) {
      tableData.list = res.data.list;
      total.value = res.data.totalCount;
      loading.value = false;
    } else {
      loading.value = false;
    }
  });
};

const roleData = ref();
const stateData = ref();
const roleList = async () => {
  let res = await getAllRole();
  if (res.code == 200) {
    roleData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
  let j = await getAllStatus();
  if (j.code == 200) {
    stateData.value = j.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: j.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  currentPage.value = 1;
  getList();
}, 300);
const resetBtn = lodash.debounce(async () => {
  searchInput.name = "";
  searchInput.roleId = null;
  searchInput.stateId = null;
  currentPage.value = 1;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增账号";
  addDialogVisible.value = true;
  ruleForm.name = "";
  ruleForm.account = "";
  ruleForm.password = "";
  ruleForm.cardNumber = "";
  ruleForm.phone = "";
  ruleForm.roleId = "";
  ruleForm.stateId = 1;
  ruleForm.id = "";
};
// 添加账号
const updateS = (row) => {
  console.log(row);
  dialongTitle.value = "编辑账号";
  addDialogVisible.value = true;
  ruleForm.id = row.id || ""; // 兼容 row 中无该字段的情况，避免赋值 undefined
  ruleForm.name = row.name || "";
  ruleForm.cardNumber = row.cardNumber || "";
  ruleForm.account = row.account || "";
  ruleForm.phone = row.phone || "";
  ruleForm.roleId = row.roleId || "";
  ruleForm.stateId = row.stateId || "";
  ruleForm.password = "";
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let params = {
        id: row.id,
      };
      let res = await deleteAccount(params);
      if (res.code == 200) {
        getList()
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
      } 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,
        password: ruleForm.password,
        phone: ruleForm.phone,
        roleId: ruleForm.roleId,
        stateId: ruleForm.stateId,
        cardNumber:ruleForm.cardNumber,
      };
      let res = "";
      if (dialongTitle.value == "新增账号") {
        res = await addAccount(data);
      } else {
        data.id = ruleForm.id;
        res = await editAccount(data);
      }
      if (res.code == 200) {
        addDialogVisible.value = false;
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
        getList();
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}, 1000);

const cancelAdd = () => {
  addDialogVisible.value = false;
};

// 多选框功能
const handleSelectionChange = (val) => {
  // console.log(val);
  selectIds.value = val.map((i) => i.id);
  console.log(selectIds.value);
};

// 表格斑马纹颜色修改
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();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.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);
      }
    }

    .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;
        }
      }
    }
  }
}

.addStaff {
  .el-dialog__body {
    padding: 20px 20px 10px 20px;
    .el-input {
      width: 400px;
    }
    .el-textarea {
      width: 400px;
    }
    .el-select {
      width: 400px;
    }
    .el-form-item {
    }
  }
}
</style>
