<template>
  <div class="home" v-if="showLogin">
    <div class="home-btn" @click="checkLoginType">
      <span v-if="type === 2">二维码登录</span>
      <span v-else>账号登录</span>
    </div>
    <div class="home-content">
      <div class="home-left">
        <div class="box">
          <img :src="parseImgUrl('ipdImages', 'logo.svg')" alt="" />
          <div class="logo-text">SagaCare</div>
        </div>
      </div>
      <div class="home-right">
        <div class="box" v-if="type === 1">
          <div class="qrcode-main">
            <qrcode-vue
              :value="codeValue"
              class="qrcode"
              foreground="#CE9F27"
              level="H"
            />
            <div class="qrcode-model" v-if="codeStatus.status">
              <span v-if="codeStatus.status === 1">已扫描</span>
              <!-- <span v-if="codeStatus.status === 2">已确认</span> -->
              <van-icon
                v-if="codeStatus.status === 2 || codeStatus.status === 3"
                class="code-replay"
                @click="refreshCode"
                name="replay"
              />
            </div>
          </div>
          <div class="qrcode-text">
            请使用朵朵小程序,扫描上面二维码进行授权登录
          </div>
        </div>
        <div class="box" v-else>
          <van-form @submit="onSubmit" class="box-form">
            <van-cell-group inset>
              <van-field
                v-model="username"
                name="username"
                placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
              />
              <van-field
                v-model="password"
                type="password"
                name="password"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
              />
            </van-cell-group>
            <div>
              <van-button round block native-type="submit"> 提交 </van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>
    <div class="fotter">欢迎使用智能办公</div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  ref,
  onBeforeUnmount,
} from "vue";
import QrcodeVue from "qrcode.vue";
import { useRouter } from "vue-router";
import { getUserInfo, newNumber, parseImgUrl, setQueryConfig } from "@/utils";
import { store, useStore } from "@/store";
import { login } from "@/apis/user";
import { Form, Field, CellGroup, Button, Toast } from "vant";
import { getCookieMac, setToken } from "@/utils/cookies";
import { getPadQrCodeStatus, queryWorkSpace } from "@/apis/envmonitor";
import { UserMutationTypes } from "@/store/modules/user/mutation-types";

export default defineComponent({
  components: {
    QrcodeVue,
    vanForm: Form,
    vanField: Field,
    CellGroup: CellGroup,
    vanButton: Button,
  },
  beforeRouteEnter(to, from, next) {
    let mac: any = getCookieMac();
    if (mac && mac != "null") {
      if (to.query.type !== "logoOut") {
        next((e: any) => {
          console.log(e);
          e.queryWorkSpace();
        });
      } else {
        next((e: any) => {
          e.showLogin = true;
          let mac: any = getCookieMac();
          console.log(mac);
          // to.query = { mac: mac};
          console.log(to);
          // console.log( e.showLogin )
          // router.push({ name: "home", query: { mac: mac } });
        });
      }
    } else {
      next("/error");
    }
  },
  setup(props) {
    let router: any = useRouter();
    const userInfo: any = getUserInfo();
    const store = useStore();
    const codeStatus: any = {};
    const timer: any = null;
    const orgin: any = location.origin;
    const proxyData = reactive({
      parseImgUrl: parseImgUrl,
      codeValue: `${orgin}/sgipad/home`,
      showLogin: false,
      size: 134,
      type: 1, // 1:二维码登录 2:用户密码登录
      userInfo: userInfo,
      checkLoginType() {
        if (proxyData.type === 1) {
          proxyData.type = 2;
        } else {
          proxyData.type = 1;
        }
        if (proxyData.type === 1) {
          proxyData.getPadQrCodeStatus();
        } else {
          if (proxyData.timer) {
            clearTimeout(proxyData.timer);
            proxyData.timer = null;
          }
        }
      },
      username: "",
      password: "",
      onSubmit(values: any) {
        // console.log("submit", values);
        let params: any = values;
        // params.username = params.username
        //   ? params.username.trim()
        //   : params.username;
        // params.password = params.password
        //   ? params.password.trim()
        //   : params.password;
        login(params).then((res) => {
          let resData: any = res;
          if (resData.result === "success") {
            setToken(resData.token);
            router.push({ path: "/choice-project" });
          } else {
            Toast("登录失败!");
          }
        });
      },
      // 查询工作空间
      queryWorkSpace() {
        if (!proxyData.userInfo.mac) {
          proxyData.showLogin = true;
        } else {
          let params: any = {
            criteria: {
              macAddress: proxyData.userInfo.mac,
              isMajorSpace: 1,
            },
            orders: [
              {
                column: "createTime",

                asc: false,
              },
            ],
            page: 1,
            size: 1,
          };
          queryWorkSpace(params)
            .then((res: any) => {
              let resData: any = res;
              if (resData.result === "success") {
                let content: any = resData?.content ?? [];
                if (content && content.length) {
                  proxyData.showLogin = false;
                  let projectId: any = content[0].projectId;
                  store.commit(UserMutationTypes.SET_PROJECT_ID, projectId);
                  router.push({
                    name: "envmonitor",
                    query: { spaceId: content[0].spaceId },
                  });
                } else {
                  proxyData.showLogin = true;
                }
              } else {
                proxyData.showLogin = true;
              }
            })
            .catch(() => {
              proxyData.showLogin = true;
            });
        }
      },
      /**
       * 获取mac地址
       */
      getQrcode() {
        let mac: any = proxyData.userInfo.mac;
        const id: any = newNumber(0, 100000, mac);
        return id;
      },
      qrCodeId: "",
      setCodeUrl() {
        let mac: any = proxyData.userInfo.mac;
        let qrCodeId: any = proxyData.getQrcode();
        proxyData.qrCodeId = qrCodeId;
        proxyData.codeValue = `${orgin}/sgipad/home?type=ipad&id=${proxyData.qrCodeId}&mac=${mac}`;
      },
      //  定时器清楚
      clearTimer() {
        if (proxyData.timer) {
          clearTimeout(proxyData.timer);
          proxyData.timer = null;
        }
      },
      // 二维码刷新
      refreshCode() {
        proxyData.setCodeUrl();
        proxyData.clearTimer();
        proxyData.getPadQrCodeStatus();
      },
      /**
       *
       *获取二维码状态
       */
      codeStatus: codeStatus,
      timer: timer,
      getPadQrCodeStatus() {
        let params: any = setQueryConfig({ qrCodeId: proxyData.qrCodeId });
        getPadQrCodeStatus(params).then((res) => {
          let resData: any = res;
          proxyData.codeStatus = resData?.data ?? {};
          if (proxyData.codeStatus.status === 2) {
            // debugger
            let projectId: any = proxyData.codeStatus.projectId;
            let spaceId: any = proxyData.codeStatus.spaceId;
            if (projectId && spaceId) {
              // 直接去环境条件页面
              // setLocalProjectId(projectId)
              store.commit(UserMutationTypes.SET_PROJECT_ID, projectId);
              router.push({
                name: "choiceSpace",
                query: { id: projectId, spaceId: spaceId },
              });
            } else if (projectId) {
              // 去选择项目页面
              store.commit(UserMutationTypes.SET_PROJECT_ID, projectId);
              router.push({ name: "choiceSpace", query: { id: projectId } });
            }
          } else {
            if (proxyData.timer) {
              clearTimeout(proxyData.timer);
              proxyData.timer = null;
            }
            proxyData.timer = setTimeout(() => {
              proxyData.getPadQrCodeStatus();
            }, 1000);
          }
        });
      },
    });
    onBeforeUnmount(() => {
      if (proxyData.timer) {
        clearTimeout(proxyData.timer);
        proxyData.timer = null;
      }
    });
    onMounted(() => {
      // 设置二维码路径
      proxyData.setCodeUrl();
      proxyData.getPadQrCodeStatus();
    });
    return {
      ...toRefs(proxyData),
    };
  },
});
</script>
<style lang="scss" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100%;
  background: #eceff4;
  padding: 20px;
  .home-btn {
    position: absolute;
    right: 0;
    top: 20px;
    width: 126px;
    height: 46px;
    line-height: 46px;
    background: #ffffff;
    border: 1px solid #e2d0a0;
    font-family: "Persagy";
    font-style: normal;
    font-weight: 500;
    font-size: 16px;
    text-align: center;
    border-radius: 40px 0 0 40px;
    color: #4d5262;
  }
  .home-content {
    width: 75%;
    // min-width: 640px;
    display: flex;
    height: 232px;
    position: absolute;
    left: 50%;
    top: 45%;
    transform: translate(-50%, -50%);
    .home-left {
      position: relative;
      flex: 1;
      height: 100%;
      text-align: center;
      .box {
        top: 10px;
        position: absolute;
        width: 160px;
        right: 138px;
      }
      img {
        width: 160px;
        height: 160px;
      }
      .logo-text {
        padding-top: 17px;
        font-family: "Persagy";
        font-style: normal;
        font-weight: 700;
        font-size: 24px;
        line-height: 29px;
        text-align: center;
        text-transform: capitalize;
        color: #af810c;
      }
    }
    .home-right {
      position: relative;
      flex: 1;
      height: 100%;
      border-left: 1px solid #d9d9d9;
      .box {
        top: 10px;
        width: 308px;
        position: absolute;
        left: 80px;
      }
      .qrcode-main {
        position: relative;
        margin: 0 auto;
        width: 164px;
        height: 160px;
        padding: 15px;
        background: #ffffff;
        border: 1px solid #ce9f27;
        .qrcode {
          width: 100% !important;
          height: 100% !important;
        }
      }
      .qrcode-model {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        top: 0;
        width: 164px;
        height: 160px;
        background: rgba(0, 0, 0, 0.3);
        span {
          display: block;
          line-height: 160px;
          text-align: center;
          font-size: 12px;
          color: #4d5262;
        }
        .code-replay {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          font-size: 32px;
          color: #fff;
        }
      }
      .qrcode-text {
        padding-top: 25px;
        font-family: "Noto Sans SC";
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        line-height: 20px;
        // margin-left: 13%;
        text-align: center;
        color: #af810c;
      }
    }
  }
  .fotter {
    position: fixed;
    left: 0;
    width: 100%;
    bottom: 80px;
    font-family: "Persagy";
    font-style: normal;
    font-weight: 500;
    font-size: 24px;
    line-height: 29px;
    color: #4d5262;
    text-align: center;
  }
}
</style>
<style lang="scss">
.box-form {
  width: 280px;
  margin: 0 auto;
  padding: 0 !important;
  .van-cell {
    width: 100%;
    height: 48px;
    background: #ffffff;
    border: 1px solid #c3c7cb;
    border-radius: 16px;
    margin-bottom: 28px;
    font-family: "Microsoft YaHei UI";
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 22px;
    color: #c3c7cb;
  }
  .van-button {
    width: 100%;
    height: 48px;
    background: #ce9f27;
    border-radius: 16px;
    font-family: "PingFang SC";
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    text-align: center;
    color: #ffffff;
    flex: none;
    order: 1;
    flex-grow: 0;
  }
  .van-field__error-message {
    position: absolute;
    top: 15px;
  }
}
</style>
