<template>
  <div class="box">
    <div class="top">
      <div class="box_img"></div>
      <div class="box_school">万载三中</div>
    </div>
    <div class="content">
      <div class="box_wel">
        <span>欢迎使用智慧校园管理平台</span>
      </div>
      <div class="box_login" v-if="bindShow">
        <div id="weixin"></div>
      </div>
      <div class="box_login" v-else>
        <div class="login_title">绑定手机号</div>
        <div class="bind_code">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            class="login-container"
          >
            <!-- <div class="title">绑定后可以使用账号登录,账号更加安全</div> -->
            <div class="title">用户绑定手机号获取登录权限</div>
            <el-form-item label="手机号" prop="user">
              <el-input v-model="ruleForm.user" placeholder="请输入手机号">
              </el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="pass">
              <el-input v-model="ruleForm.pass" placeholder="请输入验证码">
                <template #append
                  ><span @click="sendPhone">{{ sendTitle }}</span></template
                >
              </el-input>
            </el-form-item>
            <!-- <el-checkbox v-model="checked" class="remeberPwd el-form-item"
              >记住密码</el-checkbox
            > -->
            <el-form-item>
              <!-- <el-button
                :loading="loading"
                type="primary"
                @click="submitForm(ruleFormRef)"
                color="rgba(0, 97, 255, 1)"
                >确认绑定</el-button
              > -->
              <div class="btn" @click="bindClick(ruleFormRef)">
                <a :href="bindWX">绑定</a>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="footer">
      <img src="@/assets/jinghui.png" alt="">
      &nbsp;
      <a
        target="_blank"
        href="https://beian.mps.gov.cn/#/query/webSearch?recordcode=36010602000314"
        >赣公网安备36010602000314号</a
      >&nbsp;&nbsp;&nbsp;
      <a
        target="_blank"
        href="https://beian.miit.gov.cn/"
        >赣ICP备17015482号-4</a
      >
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  nextTick,
  onBeforeMount,
  onMounted,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import wxlogin from "vue-wxlogin";
import { useStore } from "vuex";
import eds from "@/utils/eds.js";

const store = useStore();
const router = useRouter();
const api = ref();
const bindWX = ref(); // 绑定手机号的跳转链接
const bindShow = ref(true); // 判断用户是否绑定
const ruleFormRef = ref();
const ruleForm = reactive({
  user: "",
  pass: "",
});
const sendTime = ref(60); // 验证码时间
const sendTitle = ref("发送短信");

var checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("手机号不能为空"));
  } else {
    const reg = /^1[3-9][0-9]\d{8}$/;
    // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
    if (reg.test(value)) {
      callback();
    } else {
      // 具体错误信息没有提示
      return callback(new Error("请输入正确的手机号"));
    }
  }
};
const rules = reactive({
  user: [
    { required: true, min: 11, message: "手机号不足11位", trigger: "blur" },
    { validator: checkPhone, trigger: "blur" },
  ],
  pass: [{ required: true, message: "请填写验证码", trigger: "blur" }],
});
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // loading.value = true;
      // let data = {
      //   account: ruleForm.user,
      //   password: ruleForm.pass,
      // };
      // let res = await axios({
      //   method: "post",
      //   url: api.value + "/login/Login",
      //   headers: {
      //   token: sessionStorage.getItem("token"),
      //   user_head: sessionStorage.getItem("userhead"),
      // },
      //   data: data,
      // });
      // console.log(res);
      // if (res.data.code == 200) {
      //   if (checked.value) {
      //     localStorage.setItem("user", ruleForm.user);
      //     localStorage.setItem("pass", ruleForm.pass);
      //   } else {
      //     localStorage.removeItem("user", ruleForm.user);
      //     localStorage.removeItem("pass", ruleForm.user);
      //   }
      //   sessionStorage.setItem("token", res.data.data.token);
      //   sessionStorage.setItem("userhead", res.data.data.userhead);
      //   sessionStorage.setItem("schoolId", res.data.data.schoolId);
      //   sessionStorage.setItem("username", res.data.data.userName);
      //   sessionStorage.setItem("sidevarItem", 1);
      //   store.commit("indexUp", 1);
      //   store.commit("userName", ruleForm.user);
      //   store.commit("passWord", ruleForm.user);
      //   router.push({
      //     path: `/repairs/home`,
      //   });
      //   ElMessage({
      //     type: "success",
      //     showClose: true,
      //     message: "登录成功",
      //     center: true,
      //   });
      // } else {
      //   ElMessage({
      //     type: "error",
      //     showClose: true,
      //     message: "登录失败",
      //     center: true,
      //   });
      //   loading.value = false;
      // }
    } else {
      return false;
    }
  });
};

const loginClick = () => {
  // router.push({ path: `/wanzai/home` });
  // sessionStorage.setItem("sidevarItem", "/wanzai/home");
};

// 实例微信js对象
const setWxerwma = async () => {
  let res = await axios({
    method: "get",
    url: api.value + "/wanzai/api/login/getAesStr",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(res, JSON.parse(eds.decryptDes(res.data.data)), "state");
  if (res.data.code == 200) {
    let state = JSON.parse(eds.decryptDes(res.data.data));
    //生成微信扫码登录二维码页面
    var obj = new WxLogin({
      self_redirect: true,
      id: "weixin",
      appid: "wxa94836d74473fe5c",
      scope: "snsapi_login",
      redirect_uri:
        "https%3A%2F%2Fwww.campussmartlife.com%2FsmartApi%2Fwanzai%2Fapi%2Fwechat%2Fcallback",
      // redirect_uri: 'https%3A%2F%2Fwww.campussmartlife.com%2FsmartManage%2F%23%2Fwanzai%2Fhome',
      state: state,
      style: "black",
      // href: `data:text/css;base64,${bast64css.value}`,
      href: "",
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: "获取二维码失败,请刷新重试",
      center: true,
    });
  }
};

// 绑定点击微信
const bindClick = (formEl) => {
  // if (ruleForm.user) {
  //   bindWX.value =
  //     "https://www.campussmartlife.com/smartApi//wanzai/api/wechat/bind?cardNo=" +
  //     ruleForm.user;
  // }
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      bindWX.value =
        "https://www.campussmartlife.com/smartApi/wanzai/api/wechat/bind?" +
        `phone=${ruleForm.user}&messageCode=${ruleForm.pass}`;
      // let data = {
      //   phone: ruleForm.user,
      //   messageCode: ruleForm.pass,
      //   // managerId: sessionStorage.getItem("token"),
      // };
      // let res = await axios({
      //   method: "post",
      //   url: api.value + "/wanzai/api/wechat/bind",
      //   headers: {
      //     token: sessionStorage.getItem("token"),
      //     user_head: sessionStorage.getItem("userhead"),
      //   },
      //   params: data,
      // });
      // if (res.data.code == 200) {
      //   setWxerwma();
      //   ElMessage({
      //     type: "success",
      //     showClose: true,
      //     message: res.data.message,
      //     center: true,
      //   });
      // } else {
      //   ElMessage({
      //     type: "error",
      //     showClose: true,
      //     message: res.data.message,
      //     center: true,
      //   });
      // }
    } else {
      return false;
    }
  });
};
// 发送短信
const sendPhone = async () => {
  if (ruleForm.user) {
    var formData = new FormData();
    // var psw = formData.get("psw"); // 获取密码
    formData.append("phone", ruleForm.user);
    let res = await axios({
      method: "post",
      url: api.value + "/wanzai/api/wechat/sendMessage",
      headers: {
        token: sessionStorage.getItem("token"),
        user_head: sessionStorage.getItem("userhead"),
      },
      data: formData,
    });
    console.log(res, "发送短信");
    if (res.data.code == 200) {
      sendTitle.value = 60;
      let timer = setInterval(() => {
        sendTitle.value--;
        if (sendTitle.value == 0) {
          sendTitle.value = "重新发送";
          clearInterval(timer);
        }
      }, 1000);
      ElMessage({
        type: "success",
        showClose: true,
        message: res.data.message,
        center: true,
      });
    } else {
      ElMessage({
        type: "error",
        showClose: true,
        message: res.data.message,
        center: true,
      });
    }
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: "请输入手机号",
      center: true,
    });
  }
};

// const token = ref(sessionStorage.getItem("token") || '')
const handleStorageChange = async (event) => {
  if (sessionStorage.getItem("token") && sessionStorage.getItem("userhead")) {
    console.log("登录也判断token是否存在");
    // store.commit("indexUp", sessionStorage.getItem("sidevarItem"));
    // sessionStorage.removeItem("message");
    // router.replace({
    //   path: `${sessionStorage.getItem("sidevarItem")}`,
    // });
    const formDatas = new FormData();
    formDatas.append("userId", "");
    let resData = await axios({
      method: "post",
      url: api.value + "/wanzai/api/smartAuthorGroup/queryUserAuthor",
      headers: {
        token: sessionStorage.getItem("token"),
        user_head: sessionStorage.getItem("userhead"),
      },
      data: formDatas,
    });
    console.log(resData, "查看当前用户权限");
    if (resData.data.code == 200) {
      let roleList = resData.data.data[0].treAuthor;
      sessionStorage.setItem("roleList", JSON.stringify(roleList));
      // store.commit("ROLELIST", "");
      let flag = roleList.some((item) => {
        return item.route == "/wanzai/systemHome";
      });
      console.log("触发跳转页面");
      let address = roleList[0].route;
      console.log(flag, address);
      setTimeout(() => {
        store.commit("indexUp", address);
        router.push({
          path: `${address}`,
        });
      }, 100);

      // if (!flag) {
      //   store.commit("indexUp", address);
      //   router.push({
      //     path: `${address}`,
      //   });
      // } else {
      //   store.commit("indexUp", "/wanzai/systemHome");
      //   router.push({
      //     path: `/wanzai/systemHome`,
      //   });
      // }
    } else {
    }
  }
  if (sessionStorage.getItem("message") == "请绑定信息") {
    bindShow.value = false;
    ElMessage({
      type: "warning",
      showClose: true,
      message: "当前用户未绑定手机号，请先绑定",
      center: true,
    });
  } else if (sessionStorage.getItem("message") == "无登录权限") {
    bindShow.value = true;
    setWxerwma();
    ElMessage({
      type: "error",
      showClose: true,
      message: "暂无登录权限，请联系管理添加权限",
      center: true,
    });
  } else if (sessionStorage.getItem("message") == "请勿非法进入") {
    bindShow.value = true;
    setWxerwma();
    ElMessage({
      type: "error",
      showClose: true,
      message: "请勿非法进入",
      center: true,
    });
  }
};
onMounted(() => {
  setWxerwma();
  // console.log(router.currentRoute.value.query);
  // console.log(window.location.href);
  sessionStorage.removeItem("message");
  window.addEventListener("storage", handleStorageChange);
  if (router.currentRoute.value.query.message == "请绑定信息") {
    sessionStorage.setItem("message", router.currentRoute.value.query.message);
    // ElMessage({
    //   type: "warning",
    //   showClose: true,
    //   message: "当前用户未绑定手机号，请先绑定",
    //   center: true,
    // });
    bindShow.value = false;
  } else if (router.currentRoute.value.query.message == "无登录权限") {
    sessionStorage.setItem("message", router.currentRoute.value.query.message);
    bindShow.value = true;
    // ElMessage({
    //   type: "error",
    //   showClose: true,
    //   message: "暂无登录权限，请联系管理添加权限",
    //   center: true,
    // });
  }
});
onBeforeMount(() => {
  api.value = store.state.user.api;
});
onUnmounted(() => {
  window.removeEventListener("storage", handleStorageChange);
});
</script>

<style lang="scss" scoped>
.box {
  // position: relative;
  min-width: 1300px;
  min-height: 750px;
  width: 100vw;
  height: 100vh;
  color: #000;
  background-image: url(@/assets/school/login_bg.png);
  background-size: 100% 100%;
  .top {
    display: flex;
    align-items: center;
    padding: 54px 0 0 62px;

    .box_img {
      // position: absolute;
      // top: 54px;
      // left: 62px;
      width: 56px;
      height: 56px;
      border-radius: 50%;
      background-color: skyblue;
      margin-right: 20px;
    }

    .box_school {
      // position: absolute;
      // top: 61px;
      // left: 141px;
      font-size: 29px;
      font-weight: bold;
    }
  }

  .content {
    width: 100%;
    height: calc(100% - 140px);
    // margin-top: 40px;
    display: flex;
    // justify-content: space-between;
    .box_wel {
      font-size: 52.5px;
      font-weight: bold;
      margin-top: 20px;
      width: 66%;
      height: 40%;
      span {
        display: block;
        text-align: center;
      }
    }

    .box_login {
      // position: absolute;
      // top: 223px;
      // left: 1286px;
      width: 24%;
      height: 70%;
      box-shadow: 0px 3px 10px rgba(0, 97, 255, 0.2);
      background-color: #fff;
      // border: 1px solid red;
      // margin-top: 100px;
      padding: 80px 0 0 0;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      // justify-content: space-between;
      align-items: center;

      // width: 426px;
      // height: 536px;

      .login_title {
        font-size: 24px;
        font-weight: bold;
      }

      .login_tips {
        color: #a6a6a6;
        font-size: 16px;
      }

      .login_code {
        width: 200px;
        height: 250px;
        // background-color: skyblue;
        .el-form {
          width: 280px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 35px 0;
          border-radius: 16px;
          // background: rgba(255, 255, 255, 1);

          .title {
            color: rgba(0, 185, 170, 1);
            font-size: 14px;
            margin: 0 0 10px 0;
          }

          .el-divider {
            width: 85%;
            margin: 20px 0 30px;
          }

          .el-form-item {
            width: 280px;
            height: 40px;
            // margin-bottom: 0;

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

              .el-input {
                height: 40px;

                .el-input__wrapper {
                  border-radius: 12px;

                  .el-input__prefix {
                    margin: 0 10px 0 12px;
                  }
                }

                // .el-icon {
                //   width: 24px;
                //   height: 24px;

                //   svg {
                //     width: 24px;
                //     height: 24px;
                //   }
                // }

                .el-input__inner {
                  height: 100%;
                  font-size: 14px;
                }
              }

              // .el-form-item__error {
              //   font-size: 16px;
              // }

              .el-button {
                width: 100%;
                height: 40px;
                font-size: 16px;
                border-radius: 12px;
              }
            }

            .el-button--primary {
              width: 280px;
            }
          }

          .remeberPwd {
            height: 30px;
            margin-bottom: 30px;

            // :deep(.el-checkbox__input) {
            //   .el-checkbox__inner {
            //     width: 15px;
            //     height: 15px;
            //   }

            //   .el-checkbox__inner::after {
            //     width: 6px;
            //     height: 12px;
            //     top: 0px;
            //   }
            // }

            :deep(.el-checkbox__label) {
              font-size: 14px;
            }
          }
        }
      }
      .bind_code {
        .el-form {
          width: 300px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 80px 0 0 0;
          border-radius: 16px;
          // background: rgba(255, 255, 255, 1);

          .title {
            color: rgba(0, 185, 170, 1);
            font-size: 14px;
            margin: 0 0 10px 0;
          }

          .el-divider {
            width: 85%;
            margin: 20px 0 30px;
          }

          .el-form-item {
            width: 300px;
            height: 40px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;

            :deep(.el-form-item__content) {
              margin-left: 0 !important;
              border-bottom: 1px solid #ccc;
              .btn {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 300px;
                height: 40px;
                color: #fff;
                font-size: 16px;
                border-radius: 8px;
                background-color: #0061ff;
                cursor: pointer;
                a {
                  color: #fff;
                  width: 300px;
                  height: 40px;
                  text-align: center;
                  line-height: 40px;
                }
              }
              .el-input {
                height: 40px;

                .el-input__wrapper {
                  // border-radius: 12px;
                  box-shadow: none;

                  .el-input__prefix {
                    margin: 0 10px 0 12px;
                  }
                }
                .el-input-group__append {
                  cursor: pointer;
                  box-shadow: none;
                  background-color: transparent;
                  padding: 0 10px;
                }

                // .el-icon {
                //   width: 24px;
                //   height: 24px;

                //   svg {
                //     width: 24px;
                //     height: 24px;
                //   }
                // }

                .el-input__inner {
                  height: 100%;
                  font-size: 14px;
                }
              }
            }
            &:nth-child(4) {
              :deep(.el-form-item__content) {
                border: none;
              }
            }
          }
        }
      }

      .login_btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 210px;
        height: 40px;
        // display: none;

        .btn {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 210px;
          height: 40px;
          color: #fff;
          font-size: 16px;
          border-radius: 8px;
          background-color: #0061ff;
          cursor: pointer;
          a {
            width: 210px;
            height: 40px;
            color: #fff;
            text-align: center;
            line-height: 40px;
          }
        }
      }
    }
  }
  .footer {
    width: 100%;
    height: 20px;
    display: flex;
    justify-content: center;
    font-size: 12px;
    a {
      color: #000;
      font-size: 14px;
      text-decoration: none;
    }
  }
}
</style>
