<template>
  <div class="textCenter fs-25 mb-15">
    <span class="mt-5">艺体生 更轻松的报志愿</span>
  </div>
  <div v-show="loginForm.type === 'pwd'" style="min-height: 250px;">
    <el-form ref="loginFormRef" :model="loginForm" status-icon :rules="loginFormRules">
      <el-form-item prop="phone">
        <el-input v-model="loginForm.phone" style="height: 50px;font-size: 30px" :placeholder="t('label.phone')"></el-input>
      </el-form-item>
      <el-form-item  prop="pass">
        <el-input v-model="loginForm.pass" style="height: 50px;font-size: 30px" :placeholder="t('label.password')" type="password" autocomplete="off" />
      </el-form-item>
      <div style="padding: 10px;text-align: center">
        <el-button type="primary" @click="submitForm(loginFormRef)">
          {{ t("button.submit") }}
        </el-button>
        <el-button @click="resetForm(loginFormRef)">
          {{ t("button.reset") }}
        </el-button>
      </div>
    </el-form>
  </div>
  <div v-show="loginForm.type === 'weixin'" style="min-height: 250px;">
    <div class="" style="text-align: center;">
      <div class="w-img">
        <el-avatar id="qrcode" :size="170" @click="getImgQrCode" style="border-radius: 0%"
                  class="">
          <img :src="state.qrcode" alt=""/>
        </el-avatar>
        <div class="w-qr_message" @click="getImgQrCode" v-show="state.qrcode && state.qrcodeStatus !=='NOT_SCAN'">
          <div >{{getQrCodeStatus(state.qrcodeStatus)}}</div>
        </div>
      </div>
      <div class="w-qr-status-text" style="width: 100%;" v-if="state.qrcode">
        <span class="textCenter">请确保使用微信移动客户端版本为6.7.2及以上进行扫描</span>
      </div>
    </div>
  </div>
  <!--loginType-->
  <div style="padding: 10px;text-align: center">
    <el-tooltip class="box-item" effect="light" content="微信登录" placement="bottom">
      <el-button circle style="margin: 0 20px;" @click="switchType('weixin')" v-show="loginForm.type === 'pwd'">
        <svg-icon icon-class="weixin" size="3" />
      </el-button>
    </el-tooltip>
    <el-tooltip class="box-item" effect="light" content="密码登录" placement="bottom">
      <el-button circle style="margin: 0 20px;" @click="switchType('pwd')" v-show="loginForm.type === 'weixin'">
        <svg-icon icon-class="lock" size="3" />
      </el-button>
    </el-tooltip>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import ApiConstant from "@/utils/ApiConstant";
import axiosInstance from '@/utils/http'
import { ElMessage } from "element-plus";
import { getScore } from "@/axios/api";
import { clearUserIocalStorage } from "@/utils/tool";
const { t } = useI18n();
// 路由对象
const router = useRouter();
// 表单数据
const loginFormRef = ref();
const loginForm = reactive({
  phone: "",
  pass: "",
  type: 'pwd',
});
const state = reactive({
  qrcode:'https://i.gifer.com/embedded/download/74H8.gif',//登录二维码
  qrcodeStatus:'START',//二维码状态
  uuid:'',//uuid
})

// 表单规则
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(t("placeholder.password")));
  } else {
    // if (loginForm.checkPass !== "") {
    //   if (!loginFormRef.value) return;
    //   loginFormRef.value.validateField("checkPass", () => null);
    // }
    callback();
  }
};
const loginFormRules = reactive({
  phone: [
    {
      required: true,
      message: t("placeholder.phone"),
      trigger: "blur",
    },
    /*{
      type: "phone",
      message: t("placeholder.phone"),
      trigger: ["blur", "change"],
    },*/
  ],
  pass: [
    {
      required: true,
      validator: validatePass,
      trigger: "blur",
    },
  ],
});

// 表单方法
const submitForm = (formEl: any) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      clearUserIocalStorage();
      axiosInstance({
        url: ApiConstant.User.login,
        method: 'post',
        data: {
          username: loginForm.phone,
          password: loginForm.pass,
          programType: import.meta.env.VITE_PROGRAM_TYPE
        },
        /*showLoading: false,//是否显示加载图标*/
      }).then((response) => {
        return response.data
      }).then((data) => {
        console.log('q')
        if (data.success) {
          //将 用户数据保存到缓存中
          localStorage.setItem('vipInfo', JSON.stringify(data.result.vipInfo))
          localStorage.setItem('userInfo', JSON.stringify(data.result.userInfo))
          localStorage.setItem("X-Access-Token", data.result.token);
          getScore()
          ElMessage.success(
            localStorage.getItem("locale") === "zh_CN" ? "登录成功！" : "Submitted!"
          );
          setTimeout(function () {
            router.push({
              path: "/index"
            });
            window.location.reload()
          }, 1000);
        } else {
          ElMessage.error(data.message);
        }
        //有数据情况下
      }).catch((error: any) => {
        console.log(error);
      }).finally(() => {
      });
      //window.location.reload()
    } else {
      //ElMessage.error(localStorage.getItem("locale") === "zh_CN" ? "登录失败！" : "Oops, error submit!");
      return false;
    }
  });
};
const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
};

const switchType = (type: any) => {
  if (loginForm.type !== type) {
    loginForm.type = type
  }
  if(loginForm.type === 'weixin'){
    getImgQrCode()
  }
}
const time = ref()
//获取微信登录二维码
function getImgQrCode(){
  if(state.qrcodeStatus === 'NULL' || state.qrcodeStatus === 'START'){
    axiosInstance({
      url: "/wx/getQRCode",
      method: 'get',
      params: {},
      showLoading: false,//是否显示加载图标
    }).then((response) => {
      return response.data
    }).then((data) => {
      console.log(data)
      if(data && data.result){
        state.qrcode = data.result.img
        state.uuid = data.result.scene
        state.qrcodeStatus = 'NOT_SCAN'
        clearTimeout(time.value)
        getStatus()
      }
    }).catch((error: any) => {
      console.log(error);
    }).finally(() => {
    });
  }
  
}
function getQrCodeStatus(status:string){
  if(!status){
    return '';
  }else if(status === 'SUCCESS'){
    return '通过';
  }else if(status === 'SCAN'){
    return '扫码成功，请在手机确认';
  }
  // else if(status === 'NOT_SCAN'){
  //   return '请确保使用微信移动客户端版本为6.7.2及以上进行扫描';
  // }
  else if (status ==='NULL'){
    return '已失效，点击刷新';
  }
}
function getStatus(){
  time.value = setInterval(() => {
    axiosInstance({
      url: "/wx/user/getQrCodeStatus/"+state.uuid,
      method: 'get',
      params: {},
      showLoading: false,//是否显示加载图标
    }).then((response) => {
      return response.data
    }).then((data) => {
      if(data && data.result){
        state.qrcodeStatus = data.result.qr_state
        if ('NOT_SCAN' === data.result.qr_state) {
          //等待扫描
          ///document.querySelector('#qrcode')!.className = (`${document.querySelector('#qrcode')!.className} w-qr-dead`)
          //clearTimeout(time.value)
        }else if ('SCAN'  === data.result.qr_state) {
          //已扫码，等待操作
        }else if ('SUCCESS' === data.result.qr_state) {
          //扫描成功
          clearTimeout(time.value)
          //将 用户数据保存到缓存中
          localStorage.setItem('vipInfo',JSON.stringify(data.result.vipInfo))
          localStorage.setItem('userInfo',JSON.stringify(data.result.userInfo))
          localStorage.setItem("X-Access-Token", data.result.token);
          setTimeout(function(){
            getScore()
          }, 100);
          ElMessage.success(
            localStorage.getItem("locale") === "zh_CN" ? "登录成功！" : "Submitted!"
          );
          setTimeout(function(){
            window.location.reload()
          }, 1000);
        }else{
          //已失效
          clearTimeout(time.value)
        }
      }
    }).catch((error: any) => {
      console.log(error);
    }).finally(() => {
    });
  }, 2000)
}
</script>

<style scoped lang="scss">
//二维码 start
.qrcode {
  margin: 50px 0;
}

.qrcode .qrcode-item {
  width: 135px;
  text-align: center;
}

.qrcode .qrcode-item .qrcode-text {
  font-weight: bold;
  color: #000000;
}

//二维码 end
</style>