<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-input
              clearable
              v-model.trim="searchInput.carNumber"
              class="w-50 m-2"
              placeholder="请输入车牌号"
              style="width: 180px"
              @clear="searchBtn"
            />
          </div>
          <div class="condition">
            <span>学生姓名 :</span>
            <el-input
              clearable
              v-model.trim="searchInput.name"
              class="w-50 m-2"
              placeholder="请输入学生姓名"
              style="width: 180px"
              @clear="searchBtn"
            />
          </div>
          <div class="condition">
            <span>校区名称 :</span>
            <el-select
              clearable
              @change="schoolChange"
              v-model="searchInput.school"
              placeholder="请选择校区名称"
            >
              <el-option
                v-for="i in schoolData"
                :key="i.id"
                :label="i.school"
                :value="i.school"
              />
            </el-select>
          </div>
          <div class="condition">
            <span>到访时间 :</span>
            <el-date-picker
              v-model="searchInput.date"
              type="date"
              placeholder="请输入到访时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </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('visitorManagementSetting1')"
            type="primary"
            color="rgba(48, 201, 191, 1)"
            @click="buildExportbtn"
            >导出</el-button
          >
          <el-button
            v-if="store.BtnRole('visitorManagementSetting2')"
            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
            width="100"
            align="center"
            prop="name"
            label="学生姓名"
          />
          <el-table-column
            align="center"
            width="220"
            prop="studentCard"
            label="身份证号"
          />
          <el-table-column
            align="center"
            width="130"
            prop="phone"
            label="手机号码"
          />
          <el-table-column
            align="center"
            show-overflow-tooltip
            prop="visitorReason"
            width="220"
            label="访问事由"
          />
          <el-table-column
            width="120"
            align="center"
            prop="school"
            label="校区名称"
          />
          <el-table-column
            align="center"
            prop="startTime"
            width="200"
            label="到访开始时间"
          />
          <el-table-column
            width="200"
            align="center"
            prop="endTime"
            label="到访结束时间"
          />
          <el-table-column
            align="center"
            prop="carNumber"
            width="120"
            label="车牌号"
          />
          <!-- <el-table-column
            align="center"
            prop="peerNum"
            width="100"
            label="陪同人数"
          /> -->
          <el-table-column
            align="center"
            show-overflow-tooltip
            width="200"
            prop="remark"
            label="备注"
          />
          <el-table-column
            align="center"
            label="操作"
            fixed="right"
            min-width="120"
          >
            <template #default="{ row }">
              <div class="options">
                <span
                  v-if="store.BtnRole('visitorManagementSetting3')"
                  class="edit"
                  @click="updateS(row)"
                  >编辑</span
                >
                <span
                  v-if="store.BtnRole('visitorManagementSetting4')"
                  class="delete"
                  @click="deleteS(row)"
                  >删除</span
                >
              </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="120px"
        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="studentCard">
          <el-input
            v-model.trim="ruleForm.studentCard"
            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="school">
          <el-select
            clearable
            v-model="ruleForm.school"
            placeholder="请选择校区名称"
          >
            <el-option
              v-for="i in schoolData"
              :key="i.id"
              :label="i.school"
              :value="`${i.school},${i.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 520px" label="到访时间 :" prop="startTime">
          <el-date-picker
            v-model="ruleForm.startTime"
            type="datetimerange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期"
            :default-time="defaultTime"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="车牌号 :" prop="carNumber">
          <el-input
            v-model.trim="ruleForm.carNumber"
            placeholder="请输入车牌号"
            clearable
          />
        </el-form-item>
        <el-form-item label="同行人数 :" prop="peerNum">
          <el-input
            v-model.trim="ruleForm.peerNum"
            placeholder="请输入同行人数"
            clearable
          />
        </el-form-item>
        <el-form-item label="访问事由 :" prop="visitorReason">
          <el-input
            v-model.trim="ruleForm.visitorReason"
            placeholder="请输入访问事由"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            style="width: 400px"
          />
        </el-form-item>
        <!-- <el-form-item label="备注 :" prop="remark">
          <el-input
            v-model.trim="ruleForm.remark"
            placeholder="请输入备注"
            clearable
          />
        </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 } = storeToRefs(store);

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

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

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

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

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  phone: "13011111111", // 驾驶员手机号
  studentCard: "1234", // 驾驶员证件号
  name: "测试", // 学生姓名
  school: "墨轩湖校区", // 校区名称不能为空 只能为墨轩湖校区或黄家湖校区
  startTime: "2025-06-16 10:00:00", // 到访开始时间
  carNumber: "赣A0AY39", // 车牌号
  peerNum: 1, // 同行人数不能为空
  visitorReason: "测试", // 访问事由
  // remark: "测试", // 访问事由
  id: "",
});
// 表单验证
const rules = reactive({
  phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    {
      min: 8,
      max: 20,
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式有误，请重新输入",
      trigger: "blur",
    },
  ],
  name: [{ required: true, message: "学生姓名不能为空", trigger: "blur" }],
  studentCard: [
    { required: true, message: "身份证号不能为空", trigger: "blur" },
    {
      min: 8,
      max: 20,
      pattern: /^(?:\d{15}|\d{17}[\dX])$/,
      message: "身份证号码格式有误，请重新输入",
      trigger: "blur",
    },
  ],
  school: [{ required: true, message: "校区名称不能为空", trigger: "blur" }],
  startTime: [{ required: true, message: "到访时间不能为空", trigger: "blur" }],
  carNumber: [{ required: true, message: "车牌号不能为空", trigger: "blur" }],
  peerNum: [{ required: true, message: "同行人数不能为空", trigger: "blur" }],
  visitorReason: [
    { required: true, message: "访问事由不能为空", trigger: "blur" },
  ],
});

const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]; // '12:00:00', '08:00:00'
const disabledDate = (time) => {
  const today = new Date();
  // 获取当前日期的开始时间
  const startOfToday = new Date(today.setHours(0, 0, 0, 0));
  // 获取当前日期的结束时间
  const endOfToday = new Date(today.setHours(23, 59, 59, 999));
  return time < startOfToday || time > endOfToday;
};

const schoolData = ref();

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    page: currentPage.value, // 当前页
    limit: pageSize.value, // 一页数据条数
    name: searchInput.name,
    carNumber: searchInput.carNumber,
    school: searchInput.school,
    startTime: searchInput.date ? searchInput.date + " 00:00:00" : "",
    endTime: searchInput.date ? searchInput.date + " 23:59:59" : "",
  };

  let res = await https.get(
    "/welcome/api/visitor/admin/page",
    "params",
    params
  );
  console.log(res, "访客信息管理");
  if (res.code == 200) {
    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 schoolList = async () => {
  let res = await https.get("/welcome/api/welcome-build/schoolGroup", "params");
  console.log(res, "校区数据");
  if (res.code == 200) {
    schoolData.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.name = null;
  searchInput.carNumber = null;
  searchInput.school = null;
  searchInput.date=null;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增访客信息";
  addDialogVisible.value = true;
  ruleForm.phone = null; // 手机号
  ruleForm.name = null; // 学生姓名
  ruleForm.studentCard = null;
  ruleForm.school = null; // 校区名称不能为空 只能为墨轩湖校区或黄家湖校区
  ruleForm.startTime = null; // 到访开始时间
  ruleForm.carNumber = null; // 车牌号
  ruleForm.peerNum = null; // 同行人数不能为空
  ruleForm.visitorReason = null; // 访问事由
  // ruleForm.remark = null; // 访问事由
  ruleForm.id = null;
};
// 添加账号
const updateS = (row) => {
  dialongTitle.value = "编辑访客信息";
  console.log(row);

  addDialogVisible.value = true;
  ruleForm.phone = row.phone;
  ruleForm.studentCard = row.studentCard;
  ruleForm.name = row.name;
  ruleForm.school = `${row.school},${row.schoolId}`;
  ruleForm.startTime = [row.startTime, row.endTime];
  ruleForm.carNumber = row.carNumber;
  ruleForm.peerNum = row.peerNum;
  ruleForm.visitorReason = row.visitorReason;
  // ruleForm.remark = row.remark;
  ruleForm.id = row.id;
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = [row.id];
      let res = await https.delete(
        "/welcome/api/visitor/admin/batch-del",
        "data",
        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 = {
        phone: ruleForm.phone,
        name: ruleForm.name,
        studentCard: ruleForm.studentCard,
        school: ruleForm.school.split(",")[0],
        schoolId: ruleForm.school.split(",")[1],
        startTime: ruleForm.startTime[0],
        endTime: ruleForm.startTime[1],
        carNumber: ruleForm.carNumber,
        peerNum: ruleForm.peerNum,
        visitorReason: ruleForm.visitorReason,
        // remark: ruleForm.remark,
      };
      console.log(data);

      if (ruleForm.id) {
        data.id = ruleForm.id;
        let res = await https.put(
          "/welcome/api/visitor/admin/update",
          "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/visitor/admin/add",
          "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();
};
// 楼栋导出
const buildExportbtn = async () => {
  let params = {
    name: searchInput.name,
    carNumber: searchInput.carNumber,
    school: searchInput.school,
    startTime: searchInput.date ? searchInput.date + " 00:00:00" : "",
    endTime: searchInput.date ? searchInput.date + " 23:59:59" : "",
  };
  let res = await https.getBlob(
    "/welcome/api/visitor/admin/export",
    "params",
    params
  );
  console.log(res, "床位信息管理导出");
  let name = `访客信息管理`;
  var content = res;
  var datas = new Blob([content]);
  var downloadUrl = window.URL.createObjectURL(datas);
  var anchor = document.createElement("a");
  anchor.href = downloadUrl;
  anchor.download = name + ".xlsx";
  anchor.click();
  window.URL.revokeObjectURL(datas);
  ElMessage({
    type: "success",
    showClose: true,
    message: "导出成功",
    center: true,
  });
};

onBeforeMount(() => {
  getList();
  schoolList();
});
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;
      }
    }
  }
}
</style>
