<script setup>
import bg from '/images/login.png'
import weixin from '/images/weixin.png'
import { user, webInfo } from '~/store/index'
import { verityPhone, verityPhoneRule } from '~/utils/reg'
import { ArrowLeftBold } from '@element-plus/icons-vue'

window.location.href = "https://jltweb.bozedu.net/#/login?t=" + webInfo?.value?.js_code

if (localStorage.getItem('userInfo')) {
  user.value = {};
  localStorage.removeItem('userInfo');
}

const baseUrl = ref(window.GLOBAL_CONFIG.uc)
const router = useRouter()
const showLogin = ref(1);
const commonLogin = ref(true);

const ruleForm = ref({
  user_name: '',
  user_password: '',
})

const codeRef = ref();
const codeForm = ref({
  PhoneNumbers: '',
  vcode: '',
})

const sendVcode = ref('')
const sendToken = ref('')
const modifyUserId = ref('')
function verityVcode(rule, _value, callback) {
  if (_value !== '') {
    if (sendVcode.value !== _value)
      callback(new Error('验证码错误，请重新输入'))
    else
      callback()
  } else {
    callback(new Error('验证码错误，请重新输入'))
  }
}

function verityPwd(rule, _value, callback) {
  if (_value !== '') {
    // let reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z]{8,10}$/ 不包含特殊字符
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/
    if (!reg.test(_value))
      callback(new Error('密码格式不正确，请重新输入'))
    else
      callback()
  } else {
    callback(new Error('请输入新密码'))
  }
}

function verityConfirmPwd(rule, _value, callback) {
  if (_value !== '') {
    if (modifyForm.value.user_password !== modifyForm.value.user_confirm_password)
      callback(new Error('两次密码输入不匹配，请重新输入'))
    else
      callback()
  } else {
    callback(new Error('请输入确认新密码'))
  }
}

function verityUsernameRule(rule, _value, callback) {
  if (_value !== '') {
    callback()
  } else {
    callback(new Error('请输入您的平台账号'))
  }
}

const infoRules = reactive({
  username: [{ validator: verityUsernameRule, trigger: 'blur' }],
  PhoneNumbers: [{ validator: verityPhoneRule, trigger: 'blur' }],
  vcode: [{ validator: verityVcode, trigger: 'blur' }],
  user_password: [{ validator: verityPwd, trigger: 'blur' }],
  user_confirm_password: [{ validator: verityConfirmPwd, trigger: 'blur' }],
})


const seconds = ref(60)
const second = ref(60)
async function handleSend(type, PhoneNumbers, username) {
  if (second.value !== seconds.value || !verityPhone(PhoneNumbers))
    return

  const { code, data } = await request({ baseURL: baseUrl.value, url: 'openapi/sms/send.php', data: { type, PhoneNumbers, username } })
  if (code === '1') {
    sendVcode.value = String(data.vcode)
    sendToken.value = data.token;
    modifyUserId.value = data.uid;

    const inval = setInterval(() => {
      if (second.value === 0) {
        second.value = seconds.value
        clearInterval(inval)
      } else {
        second.value--
      }
    }, 1000)
  }
}

function linkTo() {
  router.replace('/home')
}
// baseUrl.value
async function login() {
  if (commonLogin.value) {
    const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.api, url: '/user/main/login', data: ruleForm.value })
    if (code === '1') {
      user.value = data
      linkTo()
    }
  } else {
    codeRef.value?.validate(async (valid, fields) => {
      if (valid) {
        const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.api, url: '/user/main/login', data: { token: sendToken.value } })
        if (code === '1') {
          user.value = data
          linkTo()
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }
}

const verifyFormRef = ref()
const verifyForm = ref({
  username: '',
  PhoneNumbers: '',
  vcode: '',
})
const modifyFormRef = ref()
const modifyForm = ref({
  user_password: '',
  user_confirm_password: '',
})
function modifyPwd() {
  if (showLogin.value === 2) {
    verifyFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        showLogin.value++;
      } else {
        console.log('error submit!', fields)
      }
    })
  } else if (showLogin.value === 3) {
    modifyFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        const { code, data } = await request({ baseURL: baseUrl.value, url: '/user/main/edit', data: { user_id: modifyUserId.value, user_main: { user_password: modifyForm.value.user_password } } })
        if (code === '1') {
          ElMessageBox.alert('<div class="p-30px">密码修改成功，请返回重新登录</div>', '', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            center: true,
            customStyle: { "width": "auto", "border-radius": "24px", "padding": "5px 10px 30px" },
            confirmButtonClass: 'w-full h-48px',
            callback: (action) => {
              ElMessage.success('修改成功！')
              showLogin.value = 1;
            },
          })
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }
}

function initParams() {
  for (let key in ruleForm.value) {
    ruleForm.value[key] = '';
  }
  for (let key in codeForm.value) {
    codeForm.value[key] = '';
  }
  for (let key in verifyForm.value) {
    verifyForm.value[key] = '';
  }
  for (let key in modifyForm.value) {
    modifyForm.value[key] = '';
  }

  seconds.value = 60;
  second.value = 60;
}

watch(
  () => [showLogin.value, commonLogin.value], (val) => {
    initParams();
  },
)
</script>

<template>
  <div class="loginDiv h-full flex">
    <div class="flex-1 p-10 pr-0">
      <img :src="bg" alt="" class="h-full w-full">
    </div>
    <div v-if="showLogin === 1" class="loginCon w-3/5 flex items-center p-20">
      <div class="w-full pb-120px">
        <div class="m-auto w-500px">
          <div class="title mb-80px text-center text-5xl">
            欢迎登录博智数字教师！
          </div>
          <div class="px-50px">
            <el-form v-if="commonLogin" label-position="top" :model="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="账号">
                <el-input v-model="ruleForm.user_name" placeholder="请输入账号" />
              </el-form-item>
              <el-form-item class="mt-40px" label="密码">
                <el-input v-model="ruleForm.user_password" type="password" placeholder="请输入密码" show-password />
              </el-form-item>
            </el-form>
            <el-form ref="codeRef" v-else label-position="top" :model="codeForm" :rules="infoRules" label-width="100px"
              class="demo-ruleForm">
              <el-form-item label="手机号" prop="PhoneNumbers">
                <el-input v-model="codeForm.PhoneNumbers" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item class="mt-40px" label="验证码" prop="vcode">
                <el-input v-model="codeForm.vcode" placeholder="请输入验证码" />
                <el-button class="absolute bottom-10px right-15px h-32px w-72px" type="primary"
                  :disabled="seconds === second && verityPhone(codeForm.PhoneNumbers) ? false : true"
                  @click="handleSend('login', codeForm.PhoneNumbers)">
                  发送
                </el-button>
                <el-button v-if="second !== seconds" class="h-32px w-72px absolute bottom-10px -right-85px" type="info">
                  {{ second }}s
                </el-button>
              </el-form-item>
            </el-form>
            <div class="flex justify-between mb-30px">
              <div class="cursor-pointer text-hex-04A4D0 border-b border-hex-04A4D0" @click="commonLogin = !commonLogin">{{
                commonLogin ? '手机号登录' : '账号密码登录' }} </div>
              <div class="cursor-pointer text-hex-04A4D0 border-b border-hex-04A4D0" @click="showLogin = 2">忘记密码</div>
              <!-- <div>手机号登录</div>
              <div class="">忘记密码</div> -->
            </div>
            <el-button class="h-52px w-full" size="large" type="primary" @click="login">
              登录
            </el-button>
          </div>
        </div>
        <!-- <el-divider />
        <div class="text-center">
          <div>其他登录</div>
          <div class="other m-auto mt-20px inline-block cursor-pointer rounded-16px px-43px py-12px">
            <a :href="`${baseUrl}/wxqrscan.html?site=aimk`">
              <img :src="weixin" alt="">
            </a>
          </div>
        </div> -->
      </div>
    </div>
    <div v-else class="loginCon w-3/5 p-10 flex flex-col">
      <div class="h-40px inline-flex items-center text-lg cursor-pointer" @click="showLogin--">
        <el-icon class="mr-10px" size="29">
          <ArrowLeftBold />
        </el-icon>返回
      </div>
      <div class="w-full pb-200px flex-1 flex items-center">
        <div class="m-auto w-500px">
          <div class="title mb-80px text-center text-5xl">
            {{ showLogin === 2 ? "忘记密码" : "修改密码" }}
          </div>
          <div class="px-50px">
            <el-form v-if="showLogin === 2" ref="verifyFormRef" label-position="top" :model="verifyForm" :rules="infoRules"
              label-width="100px" class="demo-ruleForm">
              <el-form-item label="请输入您的平台账号" prop="username">
                <el-input v-model="verifyForm.username" placeholder="请输入账号" />
              </el-form-item>
              <el-form-item class="mt-40px" label="请输入您与平台绑定的手机号" prop="PhoneNumbers">
                <el-input v-model="verifyForm.PhoneNumbers" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item class="mt-40px" label="验证码" prop="vcode">
                <el-input v-model="verifyForm.vcode" placeholder="请输入验证码" />
                <el-button class="absolute bottom-10px right-15px h-32px w-72px" type="primary"
                  :disabled="seconds === second && verifyForm.username && verityPhone(verifyForm.PhoneNumbers) ? false : true"
                  @click="handleSend('forgotpwd', verifyForm.PhoneNumbers, verifyForm.username)">
                  发送
                </el-button>
                <el-button v-if="second !== seconds" class="h-32px w-72px absolute bottom-10px -right-85px" type="info">
                  {{ second }}s
                </el-button>
              </el-form-item>
            </el-form>
            <el-form ref="modifyFormRef" v-else label-position="top" :model="modifyForm" :rules="infoRules"
              label-width="100px" class="demo-ruleForm">
              <el-form-item label="新密码" prop="user_password">
                <el-input v-model="modifyForm.user_password" type="password" show-password />
              </el-form-item>
              <el-form-item label="确认密码" prop="user_confirm_password">
                <el-input v-model="modifyForm.user_confirm_password" type="password" show-password />
              </el-form-item>
            </el-form>
            <el-button class="h-52px w-full mt-30px" size="large" type="primary" @click="modifyPwd">
              确定
            </el-button>
            <div v-if="showLogin === 3" class="tip mt-20px text-hex-111">
              密码要求：字母数字结合，最少设置8个字符，包含字母大小写和数字特殊符号（所有密码通用设置）
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.loginDiv {
  font-size: 14px;

  .loginCon {
    min-width: 700px;

    :deep() .el-input {
      height: 52px;
      border-radius: 8px;

      .el-input__wrapper {
        background: #f7f7f7;
        box-shadow: none;
      }
    }

    .other {
      background: #f7f7f7;
    }

    .el-divider--horizontal {
      margin: 40px 0;
    }
  }
}</style>
