<template>
  <div class="login-wrap">
    <div class="logo"></div>
    <div class="ms-login">
      <div class="ms-title">
        <div class="title__text">
          <div>欢迎登录 !</div>
          <div>豫中云平台</div>
        </div>
        <el-button class="title__wchat" hidden>
          <img src="../../assets/img/wx.png" alt="" />
          微信登录
        </el-button>
      </div>
      <div class="g-fx-j tabs">
        <div :class="{ 'tabs-active': isPitch == '1' }" @click="isPitch = '1'">
          账号登录
          <div v-show="isPitch == '1'" class="tabs__line"></div>
        </div>
        <div :class="{ 'tabs-active': isPitch == '2' }" @click="isPitch = '2'">
          验证码登录
          <div v-show="isPitch == '2'" class="tabs__line-s"></div>
        </div>
      </div>
      <el-form v-if="isPitch == '1'" ref="login" :model="param" :rules="rules" label-width="0px" class="ms-content">
        <el-form-item prop="username">
          <el-input v-model="param.userNameOrEmailAddressOrPhoneNumber" placeholder="请输入手机号"> </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <pro-input
            @onSuffixClick="onSuffixClick"
            componentName="eye"
            v-model="param.password"
            :type="passwordType"
            isShowSuffix
            placeholder="请输入密码"
          ></pro-input>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" :loading="submitLoading" @click="submitForm(login)"> 登录 </el-button>
        </div>
      </el-form>
      <el-form
        v-if="isPitch == '2'"
        ref="loginCode"
        :model="formCode"
        :rules="rulesCode"
        label-width="0px"
        class="ms-content"
      >
        <el-form-item prop="phone">
          <pro-input isShowPrefixPhone v-model="formCode.phone" componentName="eye" placeholder="请输入手机号">
          </pro-input>
        </el-form-item>
        <el-form-item prop="code" class="form-item-code">
          <pro-input
            isShowPrefix
            class="verification-code"
            placeholder="请输入验证码"
            v-model="formCode.code"
          ></pro-input>
          <el-button
            :loading="sendLoading"
            style="width: 102px"
            class="code"
            @click="onSendCode"
            :disabled="sendCountDown != 60"
            >{{ sendCountDown == 60 ? '发送验证码' : `等待(${sendCountDown})秒` }}</el-button
          >
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm(login)" :loading="submitLoading"> 登录 </el-button>
        </div>
      </el-form>
    </div>
    <!-- 选择租户对话框 -->
    <el-dialog v-model="modal.open" :title="modal.title" width="450px" align-center>
      <div
        class="user"
        @click="onLogin(item.name)"
        :class="{ 'user-active': tenancyName == item.name }"
        v-for="item in userList.arr"
        :key="item.id"
      >
        {{ item.name }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { fetchUserTenants, userLogin } from '@/api/login'
  import { useModal } from '@/utils/hooks'
  import { useUserInfo } from '@/store/user'

  interface LoginInfo {
    userNameOrEmailAddressOrPhoneNumber: string
    password: string
  }
  interface LoginCodeInfo {
    phone: string
    code: string
  }
  const router = useRouter()
  const modal = useModal('选择租户')
  // 租户id
  const tenancyName = ref('')
  const param = reactive<LoginInfo>({
    userNameOrEmailAddressOrPhoneNumber: '',
    password: ''
  })
  const formCode = reactive<LoginCodeInfo>({
    phone: '',
    code: ''
  })
  const isPitch = ref('1')
  const passwordType = ref('password')
  const submitLoading = ref(false)

  const userList = reactive<any>({
    arr: []
  })
  const onSuffixClick = (v: boolean) => {
    if (!v) {
      passwordType.value = 'password'
    } else {
      passwordType.value = 'text'
    }
  }
  const rules: FormRules = {
    userNameOrEmailAddressOrPhoneNumber: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
      }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }
  const validatorPhone = (rule: any, value: any, callback: any) => {
    const regExp = /^(13[0-9]|14[579]|15[012356789]|16[56]|17[0135678]|18[0-9]|19[89])\d{8}$/
    if (value === '') {
      callback(new Error('请输入手机号'))
    } else if (!regExp.test(value)) {
      callback(new Error('请输入正确的手机号! '))
    } else {
      callback()
    }
  }
  const rulesCode: FormRules = {
    phone: [
      {
        required: true,
        validator: validatorPhone,
        trigger: 'change'
      }
    ],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  }
  const login = ref<FormInstance>()
  const loginCode = ref<any>()
  const sendCountDown = ref(60)
  const sendLoading = ref(false)
  const onSendCode = () => {
    loginCode?.value.validateField('phone').then((res: boolean) => {
      if (res) {
        try {
          sendLoading.value = true
        } finally {
          setTimeout(() => (sendLoading.value = false), 1000)
        }
        ElMessage.success('发送成功')
        sendCountDown.value--
        const time = setInterval(() => {
          sendCountDown.value--

          if (sendCountDown.value == 0) {
            sendCountDown.value = 60
            clearInterval(time)
          }
        }, 1000)
      }
    })
  }
  const userInfo = useUserInfo()

  // 登录
  const onLogin = async (e: string) => {
    localStorage.clear()
    const data: any = await userLogin({ ...param, tenancyName: e, type: 2 })
    localStorage.setItem('yz-Token', data.accessToken)
    localStorage.setItem('user', JSON.stringify(data))
    userInfo.setUser(data)

    ElMessage.success('登录成功')
    router.push('/')
  }
  const submitForm = (formEl: FormInstance | undefined) => {
    if (isPitch.value === '2') {
      loginCode?.value.validateField().then((res: boolean) => {
        if (res) {
          try {
            submitLoading.value = true

            // 验证码登录
          } finally {
            submitLoading.value = false
          }
        }
      })

      return
    }
    if (!formEl) return
    formEl.validate(async (valid: boolean) => {
      if (valid) {
        if (param.userNameOrEmailAddressOrPhoneNumber == '') {
          ElMessage.error('请输入手机号')
          return
        }
        if (param.password == '') {
          ElMessage.error('请输入密码')
          return
        }

        submitLoading.value = true
        try {
          const data = await fetchUserTenants({
            userNameOrEmailAddressOrPhoneNumber: param.userNameOrEmailAddressOrPhoneNumber
          })

          userList.arr = data
          if (userList.arr.length == 0) {
            ElMessage.error('账号不存在！')
            return
          }
          modal.showModal()
          return
          router.push('/')
        } finally {
          submitLoading.value = false
        }
      }
    })
  }
</script>

<style scoped lang="less">
  .logo {
    width: 195px;
    height: 40px;
    background-image: url(../../assets/img/logo.png);
    position: fixed;
    top: 61px;
    left: 87px;
  }

  .login-wrap {
    min-height: 900px;
    width: 100%;
    height: 100%;
    background-image: url(../../assets/img/login-bg.png);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    overflow-y: auto;
  }

  .ms-title {
    width: 100%;
    font-size: 20px;
    color: #fff;
    height: 52px;
    line-height: 35px;
    display: flex;
    justify-content: space-between;

    .title__text {
      div:first-child {
        font-size: 16px;
      }

      div:last-child {
        font-size: 24px;
      }
    }

    .title__wchat {
      background: transparent;
      width: 120px;
      height: 45px;
      line-height: 45px;
      border: 1px solid #69b94b;
      border-radius: 22px;
      font-size: 14px;
      margin-top: 10px;
      font-weight: 400;
      color: #68b84b;
      text-align: center;
      display: flex;
      align-items: center;
      padding: 0 11px;

      img {
        width: 27px;
        height: 27px;
        margin-right: 11px;
      }
    }

    .title__wchat:hover {
      color: #98f576;
      border: 1px solid #98f576;
    }
  }

  .tabs {
    color: #5b6b9b;
    width: 50%;
    font-weight: 400;
    margin-top: 60px;
    text-align: center;

    div {
      cursor: pointer;
    }

    &__line,
    &__line-s {
      width: 62px;
      height: 3px;
      background: #597fda;
      border-radius: 2px;
      margin: 0 auto;
      margin-top: 6px;
    }

    &__line-s {
      width: 80px;
    }

    &-active {
      color: #fff;
    }
  }

  .verification-code {
    width: 60%;
  }

  .code {
    float: right;
    height: 46px;
  }

  .ms-login {
    position: absolute;
    left: 400px;
    top: 23%;
    width: 450px;
    height: 550px;
    border-radius: 5px;
    background-image: url(../../assets/img/login-form-bg.png);
    padding: 40px 50px;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    box-sizing: border-box;
  }

  :deep(.ms-content) {
    .el-input {
      height: 50px;
      border-radius: 10px;
    }

    .el-input__wrapper {
      box-shadow: 0 0 0 1px #597fda inset;
    }

    .is-focus {
      box-shadow: 0 0 0 1px #c4d1f9 inset;
    }

    .el-input__inner {
      color: #7887ba;
    }

    .el-input__wrapper {
      background-color: transparent;
      border-radius: 10px;
    }

    .el-form-item__error {
      top: 111%;
      left: 5px;
    }

    .form-item-code {
      .el-form-item__content {
        display: flex;
        justify-content: space-between;
      }
    }
  }

  .user {
    height: 40px;
    line-height: 40px;
    text-align: center;
    background-color: #dbe0ed;
    margin-bottom: 5px;
    border-radius: 6px;
    cursor: pointer;

    &-active {
      background-color: #92aef5;
    }

    &:hover {
      background-color: #2b65f7;
      color: #fff;
    }
  }

  .ms-content {
    padding: 30px 0px;

    .el-form-item {
      margin-bottom: 30px;
    }
  }

  .login-btn {
    text-align: center;
    height: 50px;
  }

  .login-btn button {
    width: 100%;
    height: 50px;
    margin-top: 28px;
    border-radius: 10px;
  }
</style>
