<template>
  <el-menu
    :default-active="activeIndex"
    class="el-menu-demo"
    mode="horizontal"
    background-color=""
    text-color="#000"
    active-text-color="#4392f7"
    @select="handleSelect"
  >
    <!-- <el-icon
      :size="20"
      v-show="!menuclose"
      class="fold"
      @click="SpreadMenu(true)"
      ><Fold
    /></el-icon>
    <el-icon
      :size="20"
      v-show="menuclose"
      class="fold"
      @click="SpreadMenu(false)"
      ><Expand
    /></el-icon> -->

    <div class="logo">
      <!-- <img src="@/assets/nanchang.png" style="width: 30px; height: 30px" /> -->
      <span>智慧公寓管理系统</span>
    </div>
    <div class="login">
      <span class="dateTime">{{ dateTime }}</span>
      <!-- <el-badge :value="titlenumber" class="item" v-if="titlenumber">
        <img
          src="@/assets/news.png"
          @click="newsClick"
          style="width: 20px; height: 20px; cursor: pointer"
          alt=""
        />
      </el-badge>
      <img
        v-else
        src="@/assets/news.png"
        @click="newsClick"
        style="width: 20px; height: 20px; cursor: pointer"
        alt=""
      /> -->
      <div class="flex flex-wrap items-center" style="cursor: pointer">
        <el-dropdown :hide-on-click="false" trigger="click">
          <el-avatar :size="30">
            <img
              src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
            />
          </el-avatar>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="uppassword">
                <el-icon class="switchButton" :size="20" color="#000">
                  <Lock />
                </el-icon>
                <span>修改密码</span>
              </el-dropdown-item>
              <el-dialog
                class="updatePass"
                custom-class="pw"
                v-model="uppasswordShow"
                title="修改密码"
                width="30%"
                :before-close="uppasswordClose"
                align-center
                :close-on-click-modal="false"
              >
                <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="oldpass">
                    <el-input
                      v-model="ruleForm.oldpass"
                      placeholder="请输入原密码"
                      clearable
                    />
                  </el-form-item>
                  <el-form-item label="新密码" prop="nowpass">
                    <el-input
                      v-model="ruleForm.nowpass"
                      placeholder="请输入新密码"
                      clearable
                    />
                  </el-form-item>
                  <el-form-item
                    label="确定新密码"
                    prop="correctpass"
                    style="
                      padding-bottom: 40px;
                      border-bottom: 1px solid rgba(230, 230, 230, 1);
                    "
                  >
                    <el-input
                      v-model="ruleForm.correctpass"
                      placeholder="请再次输入新密码"
                      clearable
                    />
                  </el-form-item>

                  <el-form-item class="options">
                    <el-button
                      class="queding"
                      type="primary"
                      color="rgba(9, 101, 98, 1)"
                      @click="submitForm(ruleFormRef)"
                    >
                      确定
                    </el-button>
                    <el-button class="congzhi" @click="resetForm(ruleFormRef)"
                      >重置</el-button
                    >
                  </el-form-item>
                </el-form>
                <!-- <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="dialogVisible = false">
                      确定
                    </el-button>
                  </span>
                </template> -->
              </el-dialog>
              <el-dropdown-item @click="loginOut">
                <el-icon class="switchButton" :size="20" color="#000">
                  <SwitchButton />
                </el-icon>
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <span class="name">{{ username }}</span>
    </div>
  </el-menu>
</template>

<script setup>
import { ref, reactive, onBeforeMount, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { JSEncrypt } from "jsencrypt";
import { dayjs } from "element-plus";
import axios from "axios";

const api = ref();
const store = useStore();
const router = useRouter();
const username = ref(); // 账号名称
const titlenumber = ref(1); //  消息条数
const activeIndex = ref(); // 路由路径
const loginOutDialogVisible = ref(false); // 退出按钮
const menuclose = ref(false); // 左边状态栏展开按钮状态
const uppasswordShow = ref(false); // 修改密码展示框
const ruleForm = reactive({
  oldpass: "",
  nowpass: "",
  correctpass: "",
});
const ruleFormRef = ref();
// 表单验证
const rules = reactive({
  oldpass: [
    {
      required: true,
      message: "原密码不能为空",
      trigger: "blur",
    },
  ],
  nowpass: [
    {
      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",
    },
  ],
  correctpass: [
    {
      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",
    },
  ],
  // desc: [{ required: true, message: "Please input activity form", trigger: "blur" }],
});

// 监控消息通知数量
watch(
  () => store.state.user.newsNum,
  (newValue, oldValue) => {
    titlenumber.value = newValue;
    console.log(newValue, "监控消息数量");
  }
);

// 点击消息通知
const newsClick = () => {
  store.commit("indexUp", 0);
  sessionStorage.setItem("sidevarItem", 0);
  router.push({
    path: `/repairs/news`,
  });
};
const dateTime = ref(
  dayjs().format("YYYY-MM-DD") + ` 星期四 ` + dayjs().format("HH:mm:ss")
); // 时间

// 选择菜单
const handleSelect = (key, keyPath) => {
  store.commit("navbarUpdata", key);
  console.log(key);
  activeIndex.value = key;
};

// 展开按钮
const SpreadMenu = (flag) => {
  store.commit("menuClose", flag);
  menuclose.value = flag;
};
// 修改密码
const uppassword = () => {
  uppasswordShow.value = true;
};
const uppasswordClose = () => {
  uppasswordShow.value = false;
  ruleFormRef.value.resetFields();
};
// 提交修改密码表单
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let publicKey =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMOcPB06u5yKyQsPjfVWiWgbEIrd14kiXNNihciaVKb6HnkQvq7zpQuZ80WEX94spnUMI3iOAl/GmIvHrpGwcbB4hJbznm+PajiwnUSPuCCXA68YJF640cJKb/8KeM7WVz69OFkIEPHhVxOy4FFF5QWe/kt6zOZ19HmE+ak+5x/QIDAQAB";
      let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
      encryptor.setPublicKey(publicKey); // 设置公钥
      let oldPassword = encryptor.encrypt(ruleForm.oldpass); // 对密码进行加密
      let newPassword = encryptor.encrypt(ruleForm.nowpass); // 对密码进行加密
      let confirmPassword = encryptor.encrypt(ruleForm.correctpass); // 对密码进行加密
      let data = {
        oldPassword: oldPassword,
        newPassword: newPassword,
        confirmPassword: confirmPassword,
        adminId: sessionStorage.getItem("id"),
      };
      if (ruleForm.nowpass == ruleForm.correctpass) {
        let resUpdata = await axios({
          method: "post",
          url: api.value + "/login/ChangePassword",
          headers: {
            // token: sessionStorage.getItem("token"),
            // user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        if (resUpdata.data.code == 200) {
          ElMessage({
            type: "success",
            showClose: true,
            message: resUpdata.data.message,
            center: true,
          });
          sessionStorage.removeItem("token");
          // localStorage.removeItem("pass");
          uppasswordShow.value = false;
          ruleFormRef.value.resetFields();
          ElNotification({
            type: "warning",
            title: "提示!!!",
            message: "密码已修改,请重新登录页面",
            // duration: 0,
            // position: "top-right",
          });
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: "两次密码输入不正确",
          center: true,
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 重置表单
const resetForm = (formEl) => {
  // console.log("重置表单");
  if (!formEl) return;
  formEl.resetFields();
};

const loginOut = () => {
  ElMessageBox.confirm("是否退出登录?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("id");
      sessionStorage.removeItem("adminMenuId");
      sessionStorage.removeItem("username");
      router.push({
        path: `/login`,
      });
      ElMessage({
        type: "success",
        message: "已退出",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消登录",
      });
    });
};

onBeforeMount(() => {
  api.value = store.state.user.api;
  activeIndex.value = store.state.user.navbar;
  username.value = sessionStorage.getItem("username");
  setInterval(() => {
    var week = ["日", "一", "二", "三", "四", "五", "六"];
    var datas = dayjs().day();
    dateTime.value =
      dayjs().format("YYYY-MM-DD") +
      ` 星期${week[datas]} ` +
      dayjs().format("HH:mm:ss");
  }, 1000);
});
</script>

<style scoped lang="scss">
.el-menu--horizontal {
  border-bottom: none;
  display: flex;
  align-items: center;
  height: 65px;
  // width: 100%;
  background-color: #fff;
  box-shadow: 5px 5px 10px 0px rgba(213, 228, 252, 1);

  .logo {
    left: 90px;
    display: flex;
    align-items: center;

    span {
      margin-left: 20px;
      font-size: 24px;
      font-weight: 600;
    }
  }

  .login {
    color: #000;
    display: flex;
    align-items: center;
    position: absolute;
    right: 10px;
    top: 17px;

    .dateTime {
      margin-right: 20px;
    }

    .el-badge {
      display: flex;
      align-items: center;
      // :deep(.el-badge__content) {
      //   width: 2px;
      //   height: 14px;
      // }
    }

    .items-center {
      margin-left: 20px;
    }

    .name {
      height: 20px;
      line-height: 20px;
      text-decoration: underline;
      padding: 0 10px;
      margin: 0 10px;
      border-left: 2px solid #ccc;
    }

    .switchButton {
      cursor: pointer;
    }
  }

  .login:focus {
    outline: none;
  }

  .fold {
    width: 46px;
    height: 65px;
  }

  .fold:hover {
    cursor: pointer;
    background-color: rgba(67, 146, 249, 0.1);
  }
}

:deep(.updatePass) {
  //   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: 20px 30px 20px 30px;
    .table {
      width: 100%;
      border-radius: 4px;
      overflow: auto;
      display: flex;
      &::-webkit-scrollbar-track {
        background-color: #daeeff;
        border-radius: 4px;
      }
      // 滚动条的滚动区域（轨道）
      &::-webkit-scrollbar {
        background-color: #242424;
        height: 5px;
        width: 4px;
        border-radius: 4px;
      }
      // 滚动条的可拖拽部分（滑块）
      &::-webkit-scrollbar-thumb {
        background: #57b2ff;
        border-radius: 4px;
      }
      .items {
        &:last-child {
          border-right: 1px solid rgba(230, 230, 230, 1);
        }
        .txt {
          height: 40px;
          line-height: 40px;
          text-align: center;
          border-left: 1px solid rgba(230, 230, 230, 1);
          border-top: 1px solid rgba(230, 230, 230, 1);
          &.scoreItem {
            background-color: rgba(240, 243, 247, 1);
          }
          &:nth-child(2) {
            border-bottom: 1px solid rgba(230, 230, 230, 1);
          }
          .el-input__wrapper {
            box-shadow: none;
            .el-input__inner {
              text-align: center;
            }
          }
        }

        .items_li {
          display: flex;
          flex-wrap: nowrap;
          .lis {
            width: 120px;
          }
        }
      }
    }
    .options {
      margin: 20px 30px 0 0;
      width: 100%;
      display: flex;
      flex-direction: row-reverse;

      .queding {
        color: #fff;
        margin-left: 15px;
      }
    }
  }
}
.el-dialog__body {
  .options {
    display: flex;
    flex-direction: row-reverse;

    :deep(.el-form-item__content) {
      margin-left: 0 !important;
      flex: none;
    }

    :deep(.queding) {
      background-color: rgba(41, 109, 227, 1) !important;
      border: 0.5px solid rgba(41, 109, 227, 1) !important;
    }
  }
}
</style>
<style lang="scss">
.el-overlay {
  .el-message-box__btns {
    .el-button--primary {
      background-color: rgba(41, 109, 227, 1) !important;
      border: 0.5px solid rgba(41, 109, 227, 1) !important;
    }
  }

  .el-overlay-dialog {
    .pw {
      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;
        }

        .options {
          margin-left: 170px;
        }
      }
    }
  }
}
</style>
