<template>
  <div class="login-wrap">
    <div class="login-left">
      <div class="logo">
        <img src="../../public/logo2.jpg" width="32" height="32" alt="">
        <span>美牛协同平台</span>
      </div>
      <div class="centers">
        <div class="center-a">登录</div>
        <div class="center-b">登录美牛科技，新鲜之选，只为您的每餐</div>
        <div class="center-c">
          <div class="center-c1 center-c2"></div>
          <div class="center-c1" @click="handleChange(0)">账密登录</div>
          <div class="center-c1" @click="handleChange(1)">短信登录</div>
          <div class="center-c1" @click="handleChange(2)">企业微信登录</div>
        </div>
        <div class="center-d">
          <el-form v-if="type === 0" :model="param" :rules="rules0" ref="login0" label-width="0px" class="ms-content">
            <el-form-item prop="username">
              <b class="bs">用户名</b>
              <el-input class="input" v-model="param.username" placeholder="请输入用户名...">
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <b class="bs">密码</b>
              <el-input
                  class="input"
                  type="password"
                  placeholder="请输入密码..."
                  v-model="param.password"
                  @keyup.enter="submitForm0(login0)"
              >
              </el-input>
            </el-form-item>
            <div class="login-btn">
              <el-button type="primary" @click="submitForm0(login0)">登录</el-button>
            </div>
          </el-form>
          <el-form v-if="type === 1" :model="param" :rules="rules1" ref="login1" label-width="0px" class="ms-content">
            <el-form-item prop="phone">
              <b class="bs">手机号</b>
              <el-input class="input" v-model="param.phone" placeholder="请输入手机号...">
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <b class="bs">验证码</b>
              <el-input class="input" v-model="param.code" placeholder="请输入验证码...">
                <template #append>
                  <span
                    v-if="mobileCodeTimer <= 0" style="cursor: pointer;width: 100px;text-align: center;" @click="sendSmsCaptcha"
                  >
                    发送验证码
                  </span>
                  <span v-if="mobileCodeTimer > 0" style="cursor: pointer;width: 100px;text-align: center;">
                    {{ mobileCodeTimer }}秒后可重新获取
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <div class="login-btn">
              <el-button type="primary" @click="submitForm1(login1)">登录</el-button>
            </div>
          </el-form>
          <span v-show="type===2" id="wxcom-panel" class="ms-content" style="height: 200px;">
            <!-- 二维码将显示在这个容器中 -->
          </span>
        </div>
      </div>
    </div>
    <div class="login-right"></div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import {useTagsStore} from '../store/tags';
import {useRouter} from 'vue-router';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage } from 'element-plus';
import {Lock, Phone, User} from '@element-plus/icons-vue';
import {login as reqLogin, sendSmsCode , smsLogin,wxComLogin } from "../api/login";
import {useBasicStore} from "../store/basic";
import {WWLoginPanelSizeType, createWWLoginPanel,WWLoginType,WWLoginRedirectType,WWLoginSuccessResp,WWLoginErrorResp} from '@wecom/jssdk';
import type { TabsPaneContext } from 'element-plus';


interface LoginInfo {
  username: string;
  password: string;
  phone: string;
  code: string;
  redirectUrl:string;
}

const type = ref<number>(0)

const handleChange = (num:number) => {
  if(num===2) {
    showWWLoginPanel()
  }
  type.value = num
  const c2s = document.getElementsByClassName('center-c2')
  if(c2s.length>0) {
    c2s[0].style.left = (1 + num * 120)+'px';
  }
}

const router = useRouter();
const redirectUrl = (router.currentRoute as any)._value.query?.redirectUrl?.toString();
//console.log(router,'xxxx');
const param = reactive<LoginInfo>({
  username: '',
  password: '',
  phone: '',
  code: '',
  redirectUrl:redirectUrl
});

const rules0: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}]
};

const rules1: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
};

let basicStore = useBasicStore();
const login0 = ref<FormInstance>();
const submitForm0 = (formEl: FormInstance|undefined) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (valid) {
      reqLogin(param).then(res => {
        ElMessage.success('登录成功');
        localStorage.setItem('token', res.data.token);
        basicStore.setUserinfo(res.data);
        if(!redirectToExternalLink()){
          router.push('/');
        }
      });
    } else {
      ElMessage.error('登录失败');
    }
  });
};

const mobileCodeTimer = ref(0)
const login1 = ref<FormInstance>();
const sendSmsCaptcha = () => {
  login1.value?.validateField('phone', (success) => {
    if (success) {
      sendSmsCode(param).then(res => {
          ElMessage.success('验证码发送成功');
          mobileCodeTimer.value = 60;
          const timer = setInterval(() => {
            mobileCodeTimer.value--;
            if (mobileCodeTimer.value === 0) {
              clearInterval(timer);
            }
          }, 1000);
        });
    }
  });
}
const submitForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (valid) {
      smsLogin(param).then(res => {
        ElMessage.success('登录成功');
        localStorage.setItem('token', res.data.token);
        basicStore.setUserinfo(res.data);
        if(!redirectToExternalLink()){
          router.push('/');
        }
      });
    } else {
      ElMessage.error('登录失败');
    }
  });
}

const handleTabClick = (tab: TabsPaneContext, event: Event)=>{
    if(tab.paneName === "wxcom"){
      showWWLoginPanel();
    }
}
const showWWLoginPanel=()=>{
  const wxcomPanel = document.getElementById('wxcom-panel');
  if(wxcomPanel){
    wxcomPanel.innerHTML="";
  }
  console.log("showWWLoginPanel");
  createWWLoginPanel({
    el: '#wxcom-panel',
    params: {
      login_type: WWLoginType.corpApp,
      appid: import.meta.env.VITE_CORP_ID,
      agentid: import.meta.env.VITE_AGENT_ID,
      redirect_uri: import.meta.env.VITE_REDIRECT_URI_WX,
      state:"1",
      redirect_type: WWLoginRedirectType.callback,
      panel_size: WWLoginPanelSizeType.small,
    },
    onLoginSuccess: (res: WWLoginSuccessResp) => {
      wxComLogin(res.code).then(res => {
        console.info(res)
        ElMessage.success('登录成功');
        localStorage.setItem('token', res.data.token);
        basicStore.setUserinfo(res.data);
        if(!redirectToExternalLink()){
          router.push('/');
        }
      });
    },
    onLoginFail: (res: WWLoginErrorResp) => {
      console.error('登录失败:',res.errMsg);
    },
  });
}


const redirectToExternalLink=()=>{
   if(redirectUrl){
    const url = new URL(redirectUrl);
    url.searchParams.append('token',localStorage.getItem('token')||'');
    window.location.href = decodeURIComponent(url?.toString());
    return true;
   }
   return false;
}

const tags = useTagsStore();
tags.clearTags();
</script>

<style scoped>
.login-wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: no-repeat;
  /* background-image: url(../assets/img/login-bg.jpg); */
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.login-left {
  width: 50%;
  height: 100%;
  background: white;
  position: relative;
}
.login-left .logo {
  width: 400px;
  height: 32px;
  /* border: solid pink 1px; */
  position: absolute;
  top: 20px;
  left: 20px;
  display: flex;
  align-items: center;
}
.login-left .logo span {
  font-family: MiSans;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
  color: #101828;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-left: 5px;
  margin-bottom: 3px;
}
.centers {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 490px;
  /* border: solid 1px pink; */
  transform: translate(-50%,-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.centers>div{
  width: 360px;
  /* border: solid 1px green; */
}
.bs {
  font-size: 14px;
  color: #344054;
}
.center-a {
  font-family: Inter;
  font-size: 30px;
  font-weight: 600;
  line-height: 38px;
  text-align: left;
  color: #101828;
  margin: 1px 0px;
}
.center-b {
  font-family: MiSans;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  text-align: left;
  color: #475467;
  margin: 7px 0px;
}
.center-c {
  height: 40px;
  padding: 4px;
  gap: 4px;
  background: #F9FAFB;
  /* background: pink; */
  margin: 25px 0px;
  border-radius: 10px;
  border: 1px;
  opacity: 0px;
  position: relative;
  z-index: 1;
}
.center-c1 {
  width: 104px;
  height: 24px;
  padding: 8px;
  gap: 8px;
  /* background: #FFFFFF; */
  border-radius: 6px;
  opacity: 0px;
  float: left;
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-size: 14px;
  color: #667085;
  z-index: 9999;
}

.center-c2 {
  background: #FFFFFF;
  box-shadow: -2px 2px 4px 0px #1018280F;
  position: absolute;
  top: 4px;
  left: 1px;
  z-index: -1;
}
.center-d {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.login-right {
  width: 50%;
  height: 100%;
  background: no-repeat;
  background-image: url('../../public/img.jpg');
  background-size: 100% 100%;
  background-position-x: 160%;
  /* background: pink; */
}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  border-bottom: 1px solid #ddd;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

.ms-content {
  width: 100%;
  /* padding: 5px 30px; */
}

.input {
  height: 44px;
  padding: 10px, 14px;
  border-radius: 8px;
  border: solid 1px #D0D5DD;
}
.input::placeholder {
  color: #98A2B3;
  font-size: 14px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  border: 0px;
  margin-bottom: 10px;
  background: #D92D20;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
</style>
