<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-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(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>
      </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" width="80" type="index" label="序号" />
        <el-table-column align="center" show-overflow-tooltip prop="content" label="公告内容" />
        <el-table-column align="center" prop="userName" label="创建人" />
        <el-table-column align="center" prop="updateTime" label="创建时间" />
        <el-table-column align="center" width="100" label="是否置顶">
          <template #default="scope">
            <el-switch v-model="scope.row.isTopShow" class="ml-2" style="--el-switch-on-color: rgba(111, 182, 184, 1)"
              @change="switchChange($event, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <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="confirmEvent(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="content">
            <el-input v-model="ruleForm.content" :rows="6" type="textarea" show-word-limit :autofocus="true"
              placeholder="请输入公告内容" />
          </el-form-item>
          <el-form-item class="options">
            <el-button color="rgba(111, 182, 184, 1)" class="queding" type="primary" @click="submitAdd(ruleFormRef)">
              确定
            </el-button>
            <el-button @click="cancelAdd(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, watch, 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({
  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({
  content: "",
  isTop: "",
  id: "",
});
// 表单验证
const rules = reactive({
  content: [{ required: true, message: "公告内容不能为空", trigger: "blur" }],
});
watch(
  () => searchInput.createTime,
  (newVal, oldVal) => {
    console.log("监听时间:", newVal);
    if (newVal == null) {
      searchBtn();
    }
  }
);
// 获取公告列表数据
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 data = {
    currentPage: currentPage.value,
    pageCount: pageSize.value,
    createTime: searchInput.createTime,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairNoticeSetting/queryPageRepairNoticeSetting",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(res, "公告数据");
  if (res.data.code == 200) {
    if (message) {
      ElMessage({
        type: "success",
        showClose: true,
        message: message,
        center: true,
      });
    }
    res.data.data.list.forEach((item) => {
      if (item.isTop == 1) {
        item.isTopShow = true;
      } else {
        item.isTopShow = false;
      }
    });
    tableData.list = res.data.data.list;
    total.value = res.data.data.totalCount;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
    if (res.data.code == 570) {
      sessionStorage.removeItem("token")
      router.push({
        path: `/login`,
      });
    }
  }
  // console.log(res);
};

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

// 添加员工
const addlist = () => {
  dialongTitle.value = "添加公告";
  addDialogVisible.value = true;
  ruleForm.content = "";
};
//编辑按钮
const edit = (row) => {
  // console.log(ruleForm.startTime, row.start_time, row.end_time);

  dialongTitle.value = "修改公告";
  addDialogVisible.value = true;
  ruleForm.content = row.content;
  ruleForm.isTop = row.isTop;
  ruleForm.id = row.id;
};
// 取消添加员工
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 = {
          content: ruleForm.content,
          isTop: 0,
        };
        // let res = await admin.adminAdd(data);
        let res = await axios({
          method: "post",
          url: api.value + "/repairNoticeSetting/insertRepairNoticeSetting",
          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 = {
          content: ruleForm.content,
          isTop: ruleForm.isTop,
          id: ruleForm.id,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/repairNoticeSetting/updateRepairNoticeSettingById",
          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 confirmEvent = async (row) => {
  let data = {
    id: row.id,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairNoticeSetting/deleteRepairNoticeSettingById",
    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 switchChange = async (val, row) => {
  console.log(val, row);
  // 切换按钮
  let isTop;
  if (val) {
    isTop = 1;
  } else {
    isTop = 0;
  }
  let data = {
    id: row.id,
    isTop,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairNoticeSetting/cancelOrTopNoticeById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(res, "置顶切换");
  if (res.data.code == 200) {
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

//导出功能
// 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();
});
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 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;

        .options {
          display: flex;
          align-items: center;
          justify-content: center;

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

      .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(.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 {
          .el-form-item__content {
            display: flex;
            flex-direction: row-reverse;

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

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