<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.account" @clear="searchBtn" class="w-50 m-2" placeholder="请输入账号"
            style="width: 150px" />
        </div>
        <div class="condition">
          <span>创建时间 : </span>
          <el-date-picker v-model="searchInput.createTime" type="daterange" range-separator="-" start-placeholder="起始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :prefix-icon="Calendar"
            placeholder="请选择日期" />
        </div>

        <el-button style="margin-left: 20px" color="rgba(111, 182, 184, 1)" type="primary" class="search"
          @click="searchBtn"><el-icon>
            <Search />
          </el-icon> <span>查询</span></el-button>
      </div>
      <!-- 按钮列表 -->
      <div class="gongneng">
        <el-button type="primary" color="rgba(111, 182, 184, 1)" @click="addlist"><el-icon>
            <CirclePlus />
          </el-icon><span>新增账号</span></el-button>
        <el-button color="rgba(111, 182, 184, 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" type="selection" width="80" /> -->
        <el-table-column width="150" align="center" label="序号" type="index" index="1" />
        <el-table-column align="center" prop="username" label="名称" />
        <!-- <el-table-column align="center" label="校区">
          <template #default="{ row }">
            <span v-if="row.schoolId == 1">墨轩湖校区</span>
            <span v-if="row.schoolId == 2">黄家湖校区</span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" prop="account" label="账号" />
        <el-table-column align="center" prop="phone" label="手机号码" />
        <el-table-column align="center" label="管理员">
          <template #default="{ row }">
            {{ row.isSuper == 1 ? "超级管理员" : "管理员" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="updateTime" label="创建时间" />

        <el-table-column align="center" label="操作" width="220">
          <template #default="scope">
            <div class="options">
              <div class="look" @click="edit(scope.row)">编辑</div>

              <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled"
                icon-color="#f89626" title="是否删除此账号?" @confirm="del(scope.row)" @cancel="cancelEvent">
                <template #reference>
                  <div class="look">删除</div>
                </template>
              </el-popconfirm>
            </div>
          </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="schoolId">
            <el-select v-model="ruleForm.schoolId" placeholder="请选择校区">
              <el-option label="黄家湖校区" :value="1" />
              <el-option label="墨轩湖校区" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="dialongTitle == '新增账号'" label="微校卡号 :" prop="cardNumber">
            <el-input v-model="ruleForm.cardNumber" placeholder="请输入微校卡号" clearable />
          </el-form-item>
          <el-form-item label="账号 :" prop="account" v-if="dialongTitle == '新增账号'">
            <el-input v-model="ruleForm.account" placeholder="请输入账号" clearable />
          </el-form-item>
          <el-form-item label="账号 :" prop="account" v-if="dialongTitle == '编辑信息'">
            <el-input v-model="ruleForm.account" disabled placeholder="请输入账号" clearable />
          </el-form-item>
          <el-form-item label="密码 :" v-if="dialongTitle == '新增账号'" prop="pass">
            <el-input v-model="ruleForm.pass" placeholder="请输入密码" clearable />
          </el-form-item>
          <el-form-item label="手机号码 :" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入手机号码" clearable />
          </el-form-item>
          <el-form-item label="用户名称 :" prop="name" style="
              padding-bottom: 40px;
              border-bottom: 1px solid rgba(230, 230, 230, 1);
            ">
            <el-input v-model="ruleForm.name" placeholder="请输入用户名称" clearable />
          </el-form-item>

          <el-form-item>
            <div class="options">
              <el-button color="rgba(111, 182, 184, 1)" class="queding" type="primary" @click="submitAdd(ruleFormRef)">
                确定
              </el-button>
              <el-button class="congzhi" @click="cancelAdd()">取消</el-button>
            </div>
          </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,
  watch,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import lodash, { reduce } 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 searchInput = reactive({
  account: "",
  createTime: "",
}); // 搜索按钮数据
5;

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据
const api = ref("");
const addDialogVisible = ref(false); // 控制添加员工弹窗

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  schoolId: "",
  cardNumber: "",
  name: "",
  account: "",
  pass: "",
  phone: "",
  id: "",
});
// 表单验证
const rules = reactive({
  account: [
    { required: true, message: "账号不能为空", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
    // {
    //   pattern: /^[a-zA-z]\w{3,15}$/,
    //   message: "请输入正确账号",
    //   trigger: "blur",
    // },
  ],
  // ^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\._\+(){}])[0-9a-zA-Z!@#$%^&*,\\._\+(){}]{8,20}$
  pass: [
    {
      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",
    // },
  ],
  name: [
    {
      required: true,
      message: "用户名称不能为空",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "手机号码不能为空",
      trigger: "blur",
    },
  ],
  schoolId: [
    {
      required: true,
      message: "校区不能为空",
      trigger: "blur",
    },
  ],
  cardNumber: [
    {
      required: true,
      message: "微校卡号不能为空",
      trigger: "blur",
    },
  ],
  // desc: [{ required: true, message: "Please input activity form", trigger: "blur" }],
});

watch(
  () => searchInput.createTime,
  (newVal, oldVal) => {
    console.log("监听时间:", newVal);
    if (newVal == null) {
      searchBtn();
    }
  }
);
// 获取账户列表
const getList = async (message) => {
  // let res = await vidiconsApi.queryCamera(data);
  // let data = new FormData();
  // if (searchInput.createTime == null) {
  //   searchInput.createTime = "";
  // }
  // data.set("number", searchInput.carnumber);
  // data.set("create_time", searchInput.createTime); //前面的key记得对应！
  // data.set("page", currentPage.value);
  // data.set("rows", pageSize.value); //前面的key记得对应！
  let data = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    // account:"",  //账号
    // phone:"",  //手机号
    // userName:"",  //账号名称
  };
  if (searchInput.account) {
    data.account = searchInput.account;
  }
  if (searchInput.createTime) {
    data.startTime = searchInput.createTime[0];
    data.endTime = searchInput.createTime[1];
  }
  let res = await axios({
    method: "get",
    url: api.value + "/repairAdmin/queryPageRepairAdmin",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(res, "账号信息");
  if (res.data.code == 200) {
    tableData.list = res.data.data.list;
    currentPage.value = res.data.data.currPage;
    total.value = res.data.data.totalCount;
  } 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,
    });
    if (res.data.code == 570) {
      sessionStorage.removeItem("token")
      router.push({
        path: `/login`,
      });
    }
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);

// 重置搜索
const searchRefresh = lodash.debounce(async () => {
  searchInput.carnumber = "";
  searchInput.createTime = "";
  currentPage.value = 1;
  getList();
}, 300);

//导出功能
const importExcel = async () => {
  let datas = {};
  if (searchInput.account) {
    data.account = searchInput.account;
  }
  if (searchInput.createTime) {
    data.startTime = searchInput.createTime[0];
    data.endTime = searchInput.createTime[1];
  }
  let res = await axios({
    method: "get",
    url: api.value + "/repairAdmin/downloadRepairAdminExcel",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    responseType: "blob",
    params: datas,
  });
  console.log(res, "导出账号");
  if (res.status == 200) {
    let name = `账号管理数据`;
    var content = res.data;
    // var data = new Blob([content],{type:"application/octet-stream;charset=utf-8"});
    // var data = new Blob([content], {
    //   type: "application/vnd.ms-excel;charset=utf-8",
    // });
    var data = new Blob([content]);
    var downloadUrl = window.URL.createObjectURL(data);
    var anchor = document.createElement("a");
    anchor.href = downloadUrl;
    anchor.download = name + ".xlsx";
    anchor.click();
    window.URL.revokeObjectURL(data);
    ElMessage({
      type: "success",
      showClose: true,
      message: "导出成功",
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 添加员工
const addlist = () => {
  dialongTitle.value = "新增账号";
  addDialogVisible.value = true;
  ruleForm.name = "";
  ruleForm.account = "";
  ruleForm.pass = "";
  ruleForm.phone = "";
  ruleForm.schoolId = "";
  ruleForm.cardNumber = "";
};
// 取消添加员工
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
};
//编辑按钮
const edit = (row) => {
  dialongTitle.value = "编辑信息";
  addDialogVisible.value = true;
  console.log(row);
  ruleForm.pass = row.password;
  ruleForm.phone = row.phone;
  ruleForm.name = row.username;
  ruleForm.account = row.account;
  ruleForm.schoolId = row.schoolId;
  ruleForm.cardNumber = row.cardNumber;
  ruleForm.id = row.id;
};
// 确认添加员工
const submitAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "新增账号") {
        let data = {
          username: ruleForm.name,
          account: ruleForm.account,
          password: ruleForm.pass,
          phone: ruleForm.phone,
          schoolId: ruleForm.schoolId,
          cardNumber: ruleForm.cardNumber,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/repairAdmin/insertRepairAdmin",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          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 = {
          username: ruleForm.name,
          phone: ruleForm.phone,
          id: ruleForm.id,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/repairAdmin/updateRepairAdminById",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          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 = async (row) => {
  console.log(row);
  let data = {
    id: row.id,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairAdmin/deleteRepairAdminById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: 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);
};
// 取消删除
const cancelEvent = () => {
  ElMessage({
    type: "info",
    showClose: true,
    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();
});
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;
  box-shadow: 0px 3px 10px rgba(213, 228, 252, 1);

  .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;
        color: #fff;
      }

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

      .el-button {
        color: #fff;
      }
    }

    :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 10px;

    .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(.options) {
        display: flex;
        justify-content: center;
        align-items: center;

        .look {
          padding: 5px 10px;
          color: rgba(111, 182, 184, 1);
          cursor: pointer;
        }
      }
    }

    // 添加员工弹窗样式
    :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-input {
          width: 200px;

          .el-input__suffix-inner {
            color: rgba(61, 81, 232, 1);
          }
        }

        .options {
          display: flex;
          flex-direction: row-reverse;
          margin: 10px 20px 0 0;
          width: 100%;

          .queding {
            color: #fff;
            margin-left: 15px;
          }
        }
      }
    }
  }

  .el-pagination {
    // width: 1600px;
    width: 96%;
    margin: 20px 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(111, 182, 184, 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>
