<template>
  <div class="qrcodeLogin">
    <div class="qrcodeLogin-center">
      <div class="login-title"><img src="@/assets/images/login/login.png" /></div>
      <Transition :enter-active-class="proxy?.animate.error.enter">
        <div class="qrcodeLogin-box" :key="key">
          <div class="tab">
            <div class="li" :class="{ 'current': type == 1 }" @click="changeType(1)">扫码登录</div>
            <div class="li" :class="{ 'current': type == 2 }" @click="changeType(2)">密码登录</div>
          </div>
          <div class="qrcodeLogin-content">
            <div class="qrcodeBox" v-show="type == 1 ? true : false">
              <div class="pic"><img :src="erweima" @click="getMobile" /></div>
              <div class="name">使用微信扫一扫</div>
            </div>
            <div class="login-input-box" v-show="type == 2 ? true : false">
              <div class="login-item">
                <input class="login-input" type="text" placeholder="请输入设备ID" v-model.trim="loginForm.deviceid" />
              </div>
              <div class="login-item">
                <input class="login-input" type="text" placeholder="请输入帐号" v-model.trim="loginForm.username" />
              </div>
              <div class="login-item">
                <input class="login-input" type="password" autocomplete="off" placeholder="请输入密码"
                  v-model.trim="loginForm.password" />
              </div>
              <div @click="getLogin" class="login-btn">
                <el-icon class="is-loading" v-if="loading">
                  <Loading />
                </el-icon>
                登 录
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </div>
  </div>
</template>

<script setup name="QrcodeLogin" lang="ts">
import { useWebSocket } from '@/utils/handWs';
import QRCode from 'qrcode';
import CryptoJS from 'crypto-js';
const { handWs, startLogin } = useWebSocket();
const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const route = useRoute();

interface DataType {
  erweima: string,
  sid: string,
  listenWs: boolean,
  loginForm: {
    username: string,
    password: string,
    deviceid: string,
  },
  loading: boolean,
  key: number,
  type: number,
}

const data = reactive<DataType>({
  erweima: '',
  sid: '',
  listenWs: false, //是否监听手势
  loginForm: {
    username: '',
    password: '',
    deviceid: '',
  },
  loading: false,
  key: 0,
  type: 1
});
const { erweima, sid, listenWs, loginForm, loading, key, type } = toRefs(data);

/**
 * 手势
 */
const getHandWs = () => {
  //加载手势WS
  handWs((e: any) => {
    //发送设备
    if (e?.wksid) {
      console.log('e.wksid', e.wksid);
      listenWs.value = true;
      sid.value = e.wksid;
      //登录码
      getErweima();
      //连接登录
      startLogin();
      //自动登录
      if (route.query?.auto) {
        proxy?.$modal.msgWarning('自动登录');
        type.value = 2;
        getLogin();
      }
    }
    if (listenWs.value == false) {
      return false;
    }
    //接收百度语音token
    if (e?.bdapi_token) {
      // console.log("e.bdapi_token", e.bdapi_token)
      let tok = e.bdapi_token;
      localStorage.setItem('tok', tok);
    }
    //获取信息
    if (e?.data?.token) {
      //保存token
      let token = e.data.token;
      localStorage.setItem('token', token);
      let deviceid = e?.data?.deviceid;
      localStorage.setItem('deviceid', deviceid);
      //刷新
      window.location.reload();
    }
  });
};

/**
 * 获取二维码
 */
const getErweima = () => {
  QRCode.toDataURL(`${location.origin}/#/login/mobile?sid=${sid.value}`).then((res: any) => {
    erweima.value = res;
  });
};

// 登录
const getLogin = () => {
  let deviceid = loginForm.value.deviceid;
  let username = loginForm.value.username;
  let password = loginForm.value.password;
  if (!sid.value) {
    proxy?.$modal.msgWarning('SID为空请尝试刷新或重启');
    key.value++;
    return false;
  }
  if (!deviceid || !username || !password) {
    proxy?.$modal.msgWarning('设备ID、账号、密码不能为空');
    key.value++;
    return false;
  }
  loading.value = true;
  proxy?.$modal.loading();
  let params = {
    sid: sid.value,
    deviceid,
    username,
    password
  };
  proxy?.$http.common
    .qrlogin(params)
    .then((res: any) => {
      if (res.access_token) {
        //保存token
        let token = res.access_token;
        let passwordStr = CryptoJS.AES.encrypt(password, 'trops').toString();
        localStorage.setItem('loginType', "2");
        localStorage.setItem('token', token);
        if (deviceid) {
          localStorage.setItem('deviceid', deviceid);
        } else {
          localStorage.removeItem('deviceid');
        }
        localStorage.setItem('username', username);
        localStorage.setItem('password', passwordStr);
      }
    })
    .catch(() => {
      key.value++;
    })
    .finally(() => {
      proxy?.$modal?.closeLoading();
      loading.value = false;
    });
};

/**
 * 切换登录类型
 */
const changeType = (data: number) => {
  type.value = data;
  if (type.value == 2 && sid.value == undefined && !sid.value) {
    proxy?.$modal.msgError('缺少SID，重新获取！');
    //刷新
    window.location.reload();
  }
};

/**
 * 跳转手机登录页
 */
const getMobile = () => {
  let routeUrl: any = router.resolve({ path: '/login/mobile', query: { sid: sid.value } });
  window.open(routeUrl.href, '_blank');
};

onMounted(() => {
  let token = localStorage.getItem('token');
  let deviceid = localStorage.getItem('deviceid');
  let username = localStorage.getItem('username');
  let password = localStorage.getItem('password');
  if (deviceid) {
    loginForm.value.deviceid = deviceid;
  }
  if (username) {
    loginForm.value.username = username;
  }
  if (password) {
    let myPassword = CryptoJS.AES.decrypt(password, 'trops').toString(CryptoJS.enc.Utf8);
    loginForm.value.password = myPassword;
  }
  localStorage.removeItem('ip');
  getHandWs();
});

onBeforeUnmount(() => {
  listenWs.value = false;
});

onMounted(() => {
  //测试环境默认密码
  if (import.meta.env.DEV) {
    // loginForm.value.deviceid = '25821975';
    // loginForm.value.username = 'manage1';
    // loginForm.value.password = 'trops@2022';
  }
});
</script>

<style lang="scss" scoped>
.qrcodeLogin {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .qrcodeLogin-center {
    .login-title {
      text-align: center;

      img {
        width: 8rem;
      }

      margin-bottom: 1.2rem;
    }

    .qrcodeLogin-box {
      background: linear-gradient(41deg, #1d2f3d -83%, #304453 95%);
      box-shadow: inset 0px 1px 0px 2px rgba(255, 255, 255, 0.2);
      border-radius: 1.6rem;

      .tab {
        display: flex;
        font-size: 1.2rem;
        text-align: center;
        height: 4rem;
        line-height: 4rem;

        .li {
          width: 50%;
          color: #ffffff;
          border-bottom: 1px solid #f1f1f1;
          cursor: pointer;
        }

        .current {
          color: #14f287;
          border-bottom: 1px solid #14f287;
        }
      }

      .qrcodeLogin-content {
        width: 13rem;
        height: calc(13rem + 1rem + 2rem);
        padding: 2rem 5rem;

        .qrcodeBox {
          text-align: center;

          .pic {
            width: 100%;
            margin-bottom: 1rem;

            img {
              width: 100%;
            }
          }

          .name {
            color: #ffffff;
            font-size: 1.4rem;
          }
        }

        .login-input-box {
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          width: 100%;

          .login-item {
            width: 100%;
            margin-bottom: 1.2rem;
            display: flex;
            justify-content: center;

            .login-input {
              width: 100%;
              height: 2.9rem;
              line-height: 2.9rem;
              border-radius: 0.83rem;
              padding: 0 1rem;
              text-align: center;
              font-size: 1.65rem;
              opacity: 1;
              background: #eaeaea;
              box-sizing: border-box;
              border: 1px solid #ffffff;
              box-shadow: inset 0px 0px 10px 1px rgba(78, 78, 78, 0.5899);
            }
          }

          .login-btn {
            width: 100%;
            height: 3.59rem;
            line-height: 3.59rem;
            border-radius: 0.83rem;
            font-size: 2rem;
            opacity: 1;
            text-align: center;
            background: radial-gradient(141% 126% at 5% 93%, #8effa9 0%, #07ffe7 100%);
            box-shadow: inset 0px 1px 0px 2px rgba(255, 255, 255, 0.3);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;

            .is-loading {
              margin-right: 5px;
            }
          }
        }
      }
    }
  }
}
</style>
