<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">报备管理</span>
    </div>
    <div class="middle">
      <div class="filter">
        <div class="condition">
          <span>姓名 : </span>
          <el-input
            clearable
            v-model="searchInput.name"
            class="w-50 m-2"
            placeholder="请输入姓名"
            style="width: 150px"
          />
        </div>
        <!-- <div class="condition">
          <span>手机号码 : </span>
          <el-input
            clearable
            v-model="searchInput.phone"
            class="w-50 m-2"
            placeholder="请输入手机号码"
            style="width: 150px"
          />
        </div> -->
        <div class="condition">
          <span>创建时间 : </span>
          <el-date-picker
            v-model="searchInput.createTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
            placeholder="请选择日期"
          />
        </div>
        <el-button
          style="margin-left: 20px"
          color="rgba(61, 81, 232, 1)"
          type="primary"
          class="search"
          @click="searchBtn"
          ><el-icon><Search /></el-icon> <span>查询</span></el-button
        >
        <el-button
          style="margin-left: 20px !important"
          color="rgba(61, 81, 232, 1)"
          type="primary"
          class="search"
          @click="searchRefresh"
          ><el-icon><Refresh /></el-icon><span>重置</span></el-button
        >
      </div>
      <!-- 按钮列表 -->
      <div class="gongneng">
        <el-button type="primary" color="rgba(61, 81, 232, 1)" @click="addlist"
          ><el-icon><CirclePlus /></el-icon><span>新增报备人员</span></el-button
        >
        <!-- <el-button
          color="rgba(61, 81, 232, 1)"
          class="import"
          type="primary"
          @click="importExcel"
          ><img
            src="@/assets/import.png"
            style="width: 14px; height: 14px; margin-right: 4px"
            alt=""
          />
          <span>导出表单</span></el-button
        > -->
      </div>
    </div>
    <div class="footer">
      <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 align="center" prop="create_time" label="创建时间" />
        <el-table-column align="center" prop="user_name" label="姓名" />
        <el-table-column align="center" prop="card_number" label="卡号" />
        <el-table-column align="center" width="300" label="有效时间">
          <template #default="scope">
            <div>{{ scope.row.start_time + " ~ " + scope.row.end_time }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="user_phone" label="电话号码" />
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="edit(scope.row)"
              ><div class="look">编辑</div></el-button
            >
            <el-button link type="danger" @click="del(scope.row)"
              ><div class="looks">删除</div></el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加报备人员弹窗 -->
      <el-dialog
        class="addStaff"
        v-model="addDialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="dialongTitle"
        align-center
        width="609"
        :before-close="cancelAdd"
      >
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :size="formSize"
          label-position="left"
          status-icon
        >
          <el-form-item label="姓名 :" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入姓名"
              clearable
            />
          </el-form-item>
          <el-form-item label="卡号 :" prop="cardnumber">
            <!-- <el-tooltip
              :visible="cardVisible"
              placement="right-start"
              effect="light"
            >
              <template #content>
                <span>微校卡号</span>
              </template>
              <el-input
                v-model="ruleForm.cardnumber"
                placeholder="请输入卡号"
                clearable
                @focus="cardShow"
                @blur="cardHide"
              />
            </el-tooltip> -->
            <el-input
              v-model="ruleForm.cardnumber"
              placeholder="请输入微校卡号"
              clearable
            />
          </el-form-item>
          <el-form-item label="手机号码 :">
            <el-input
              v-model="ruleForm.phone"
              placeholder="请输入手机号码"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="类型 :" prop="post">
            <el-select
              v-model="ruleForm.post"
              class="m-2"
              placeholder="请选择职位"
            >
              <el-option label="临时人员" value="临时人员" />
              <el-option label="学生" value="学生" />
            </el-select>
          </el-form-item> -->
          <el-form-item
            label="有效时间 :"
            prop="startTime"
            style="padding-bottom: 30px"
          >
            <el-date-picker
              v-model="ruleForm.startTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-divider />
          <el-form-item class="options">
            <el-button class="congzhi" @click="cancelAdd(ruleFormRef)"
              >取消</el-button
            >
            <el-button
              color="rgba(61, 81, 232, 1)"
              class="queding"
              type="primary"
              @click="submitAdd(ruleFormRef)"
            >
              确定
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper, slot"
      :total="total"
      @update:current-page="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onBeforeMount, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const router = useRouter();
// 表格数据
const tableData = reactive({ list: [] });
const activeIndex = ref(); // 默认跳转路由
const dialongTitle = ref("新增报备人员"); // 弹窗标题
const api = ref("");
const searchInput = reactive({
  name: "",
  phone: "",
  createTime: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据

const addDialogVisible = ref(false); // 控制添加员工弹窗
const cardVisible = ref(false); // 卡号提示文字

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  name: "",
  phone: "",
  post: "0",
  cardnumber: "",
  startTime: "",
  id: "",
});
// 表单验证
const rules = reactive({
  name: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
    {
      pattern: /[\u4e00-\u9fa5]$/,
      message: "请输入正确姓名",
      trigger: "blur",
    },
  ],
  // /^[\u4E00-\u9FA5]$/
  cardnumber: [
    { required: true, message: "卡号不能为空", trigger: "blur" },
    // {
    //   // pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
    //   // pattern: /^[0-9]*$/,
    //   message: "请输入正确卡号(数字类型)",
    //   trigger: "blur",
    // },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      // pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
      pattern: /^((\(\+86\))|(\(86\)))?[1][3456789][0-9]{9}$/,
      message: "请输入合法手机号/电话号",
      trigger: "blur",
    },
  ],
  post: [
    {
      required: true,
      message: "职位不能为空",
      trigger: "blur",
    },
  ],
  startTime: [
    {
      required: true,
      message: "请选择时间段",
      trigger: "blur",
    },
  ],

  // desc: [{ required: true, message: "Please input activity form", trigger: "blur" }],
});
// 获取摄像头列表
const getList = async (message) => {
  let data = new FormData();
  data.set("user_name", searchInput.name);
  data.set("create_time", searchInput.createTime);
  data.set("page", currentPage.value);
  data.set("rows", pageSize.value); //前面的key记得对应！
  // let res = await adminApi.adminLogin(data);
  let res = await axios({
    method: "post",
    url: api.value + "/ubblist.action",
    headers: {
      token: sessionStorage.getItem("token"),
    },
    data: data,
  });
  console.log(res, "报备数据");
  if (res.status == 200) {
    if (message) {
      ElMessage({
        type: "success",
        showClose: true,
        message: message,
        center: true,
      });
    }
    tableData.list = res.data.rows;
    // currentPage.value = res.data.currentPage;
    total.value = res.data.total;
  } else {
    tableData.list = res.data.rows;
    currentPage.value = 1;
    total.value = res.data.total;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
  // console.log(res);
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList("查询成功");
}, 300);
// 重置搜索
const searchRefresh = lodash.debounce(async () => {
  searchInput.name = "";
  searchInput.createTime = "";
  currentPage.value = 1;
  getList();
}, 300);
// 添加员工
const addlist = () => {
  dialongTitle.value = "新增报备人员";
  addDialogVisible.value = true;
  ruleForm.name = "";
  ruleForm.cardnumber = "";
  ruleForm.phone = "";
  ruleForm.post = "";
  ruleForm.startTime = [];
};
//编辑按钮
const edit = (row) => {
  // console.log(ruleForm.startTime, row.start_time, row.end_time);

  dialongTitle.value = "编辑报备人员";
  addDialogVisible.value = true;
  console.log(row);
  ruleForm.name = row.user_name;
  ruleForm.phone = row.user_phone;
  ruleForm.id = row.id;
  ruleForm.cardnumber = row.card_number;
  let data = [row.start_time, row.end_time];
  console.log(row.start_time == "");
  if (row.start_time != "") {
    ruleForm.startTime = data;
  } else {
    ruleForm.startTime = "";
  }
};
// 取消添加员工
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
};
// 确认添加员工
const submitAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "新增报备人员") {
        let data = {
          start_time: ruleForm.startTime[0],
          end_time: ruleForm.startTime[1],
          user_name: ruleForm.name,
          card_number: ruleForm.cardnumber,
          user_phone: ruleForm.phone,
        };
        // let res = await admin.adminAdd(data);
        let res = await axios({
          method: "post",
          url: api.value + "/ubbinsert.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        console.log(res, "添加报备");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        let data = {
          user_name: ruleForm.name,
          user_phone: ruleForm.phone,
          id: ruleForm.id,
          card_number: ruleForm.cardnumber,
          start_time: ruleForm.startTime[0],
          end_time: ruleForm.startTime[1],
        };
        let res = await axios({
          method: "post",
          url: api.value + "/ubbupdate.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        console.log(res, "修改报备");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//删除按钮
const del = (row) => {
  ElMessageBox.confirm(`是否删除 ${row.user_name} 报备人员?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = new FormData();
      data.set("id", row.id);
      // let res = await adminApi.adminLogin(data);
      let res = await axios({
        method: "post",
        url: api.value + "/ubbdel.action",
        headers: {
          token: sessionStorage.getItem("token"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        if (tableData.list.length == 1 && currentPage.value != 1) {
          currentPage.value = currentPage.value - 1;
        }
        getList();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
      console.log(res);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 控制卡号显示
const cardShow = () => {
  cardVisible.value = true;
};
// 控制卡号隐藏
const cardHide = () => {
  cardVisible.value = false;
};

//导出功能
// const importExcel = async () => {
//   if (searchInput.createTime == null) {
//     searchInput.createTime = "";
//   }
//   let data = new FormData();
//   data.set("user_name", searchInput.name);
//   data.set("user_phone", searchInput.phone);
//   data.set("create_time", searchInput.createTime);
//   let res = await axios({
//     method: "post",
//     url: api.value + "/carBook/usertoExcel.action",
//     headers: {
//       token: sessionStorage.getItem("token"),
//     },
//     data: data,
//   });
//   // console.log(res, "导出账号");
//   if (res.data.code == 200) {
//     // const elt = document.createElement("a");
//     // elt.setAttribute(
//     //   "href",
//     //   "https://chtech.ncjti.edu.cn/carstop" + res.data.downurl
//     // );
//     // // elt.setAttribute("download", "file.xlsx");
//     // // elt.style.display = "none";
//     // document.body.appendChild(elt);
//     // elt.click();
//     var downloadPath = "https://chtech.ncjti.edu.cn/carstop" + res.data.downurl;
//     console.log("获得地址数据:", downloadPath);
//     var downloadLink = document.createElement("a");
//     downloadLink.style.display = "none"; // 使其隐藏
//     downloadLink.href = downloadPath;
//     downloadLink.download = "";
//     downloadLink.click();
//     document.body.appendChild(downloadLink);
//     document.body.removeChild(downloadLink);
//     ElMessage({
//       type: "success",
//       showClose: true,
//       message: res.data.message,
//       center: true,
//     });
//   } else {
//     ElMessage({
//       type: "error",
//       showClose: true,
//       message: res.data.message,
//       center: true,
//     });
//   }
// };
// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};

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

onBeforeMount(() => {
  api.value = store.state.user.api;
  getList();
  // let arr = [2, 4, 6, 3, 5, 8, 7, 9, 1];
  // for (let j = 1; j <= arr.length - 1; j++) {
  //   for (let i = 0; i <= arr.length - j; i++) {
  //     let a = arr[i];
  //     if (arr[i] > arr[i + 1]) {
  //       arr[i] = arr[i + 1];
  //       arr[i + 1] = a;
  //     }
  //   }
  // }
  // for (let j = 0; j <= arr.length - 2; j++) {
  //   for (let i = j + 1; i <= arr.length - 1; i++) {
  //     let a = arr[j];
  //     if (arr[j] < arr[i]) {
  //       arr[j] = arr[i];
  //       arr[i] = a;
  //     }
  //   }
  // }
  // let arr = [2, 4, 6, 3, 3, 4, 8, 9, 3, 1, 2, 5, 8, 7, 9, 1];
  // let arr2 = [];
  // for (let j = 0; j <= arr.length - 1; j++) {
  //   let flag = true;
  //   for (let i = 0; i <= arr2.length - 1; i++) {
  //     if (arr[j] == arr2[i]) {
  //       flag = false;
  //       break;
  //     }
  //   }
  //   if (flag) {
  //     arr2.push(arr[j]);
  //   }
  // }
  // console.log(arr2);

  // let arr = [2, 4, 6, 3, 3, 4, 8, 9, 3, 1, 2, 5, 8, 7, 9, 1];
  // var newArr = arr.reduce((pre, cur) => {
  //   console.log(pre, cur);
  //   if (cur in pre) {
  //     pre[cur]++;
  //   } else {
  //     pre[cur] = 1;
  //   }
  //   return pre;
  // }, {}); //这里注意初始值要默认赋予空对象，不然会报错
  // console.log(newArr);

  // let arr = [2, 4, 6, 3, 3, 4, 8, 9, 3, 1, 2, 5, 8, 7, 9, 1];
  // let newArr = arr.reduce((pre, cur) => {
  //   if (!pre.includes(cur)) {
  //     return pre.concat(cur);
  //   } else {
  //     return pre;
  //   }
  // }, []);

  // console.log(newArr);
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: 97.5%;
  height: 89%;
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;

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

    color: #000;
    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin: 10px 0 0 0;
      .search {
        margin-left: 0 !important;
      }
      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;
        :deep(.el-input .el-input__inner) {
          font-size: 16px;
        }
        span {
          margin: 0 10px 0 0;
        }
      }
    }
    .gongneng {
      margin: 10px 0;
    }
    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }
    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }
    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }
    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }
    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }
  .footer {
    width: 96%;
    height: 550px;
    margin: 10px auto 30px;
    .el-table--fit {
      height: 100%;
      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 16px;
        color: #000;
      }
      :deep(.el-table__row) {
        height: 50px;
        font-size: 16px;
        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(.look) {
        padding: 5px 10px;
        border-radius: 45px;
        border: 0.74px solid rgba(30, 125, 251, 1);
      }
      :deep(.looks) {
        padding: 5px 10px;
        border-radius: 45px;
        border: 0.74px solid #f56c6c;
      }
    }

    // 添加员工弹窗样式
    :deep(.addStaff) {
      //   height: 420px;
      border-radius: 11px;
      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;
        .el-dialog__headerbtn {
          outline: none;
        }
      }
      .el-dialog__body {
        padding: 30px 20px 10px 20px;
        // .el-form-item {
        //   // width: 500px;
        // }
        .el-input {
          width: 200px;
        }
        .options {
          margin-left: 320px;
        }
      }
    }
  }
  .el-pagination {
    // width: 1600px;
    width: 96%;
    margin: 0 auto 18px;
    justify-content: flex-end;
    :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(30, 125, 251, 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;
    }
  }
}
.el-input {
  width: 192px;
}
</style>
