<template>
  <div>
    <div class="title">登录巡检助手账号</div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="手机登录" name="first">
        <div class="div_from">
          <el-form
            ref="formRef"
            style="max-width: 600px"
            :model="loginByPhoneForm"
            status-icon
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item prop="phoneNumber">
              <el-input
                v-model="loginByPhoneForm.phoneNumber"
                type="string"
                autocomplete="off"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>
            <el-form-item prop="verifyCode">
              <el-input
                v-model="loginByPhoneForm.verifyCode"
                type="string"
                placeholder="请输入验证码"
              >
              </el-input>
              <el-button
                type="primary"
                @click="sendVerifyCode"
                :disabled="countdown != 60"
                class="button-verify"
              >
                {{
                  countdown > 0 && countdown < 60
                    ? `${countdown}秒后重试`
                    : '发送验证码'
                }}
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="el-button_one"
                @click="loginByPhone"
              >
                立即登录
              </el-button>
              <div class="div_one_from_check">
                <el-checkbox
                  v-model="isRememberMe"
                  label="下次自动登录"
                  size="large"
                  @change="checkedChange"
                />
                <div @click="forgetPas">忘记密码？</div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="账号登录" name="second">
        <div class="div_from">
          <el-form
            ref="formRef1"
            style="max-width: 600px"
            :model="loginByUserForm"
            status-icon
            :rules="loginRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginByUserForm.username"
                type="string"
                autocomplete="on"
                placeholder="请输入邮箱账号"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginByUserForm.password"
                type="password"
                autocomplete="on"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="el-button_one"
                @click="loginByUser"
              >
                立即登录
              </el-button>
              <div class="div_one_from_check">
                <el-checkbox
                  v-model="isRememberMe"
                  label="下次自动登录"
                  size="large"
                />
                <div @click="forgetPas">忘记密码？</div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <Vcode :show="isShow" @success="onSuccess" @close="onClose" />
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import Vcode from 'vue3-puzzle-vcode'
import { loginByUsername, verifyCode, logout } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken, removeToken, setToken } from '@/utils/auth'
const userStore = useUserStore()
const router = useRouter()
onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value)
  }
})
const emit = defineEmits(['forget-password'])
const activeName = ref('first')
const type = ref('')
const loginDevice = ref('pc')
const loginByPhoneForm = reactive({
  phoneNumber: '',
  verifyCode: '',
})
const rules = {
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}
const loginByUserForm = reactive({
  username: '1@qq.com',
  password: '123456',
})
const loginRules = {
  username: [
    { required: true, message: '登录账号不能为空', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址格式',
      trigger: 'blur,change',
    },
  ],
  password: [{ required: true, message: '登录密码不能为空', trigger: 'blur' }],
}
const isRememberMe = ref(false)
const checkedChange = () => {
  console.log(isRememberMe.value)
}
const isShow = ref(false)
const countdown = ref(60)
const intervalId = ref(null)

const handleClick = () => {
  // console.log('切换登录方式')
}
const startCountdown = () => {
  intervalId.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(intervalId.value)
      intervalId.value = null
      countdown.value = 60
    }
  }, 1000)
}
const onShow = () => {
  isShow.value = true
}

const onClose = () => {
  isShow.value = false
}

const onSuccess = () => {
  onClose()
  if (type.value == 1) {
    startCountdown()
  } else {
    console.log(loginByUserForm, '用户名登录')
    loginByUserApi()
  }
}

const sendVerifyCode = () => {
  console.log('发送验证码')
  type.value = 1
  onShow()
}

const formRef = ref(null)
const loginByPhone = () => {
  console.log('手机号登录')
  formRef.value.validate(valid => {
    if (valid) {
      return true
    } else {
      return false
    }
  })
}
const formRef1 = ref(null)
const loginByUser = () => {
  console.log('密码登录')
  formRef1.value.validate(valid => {
    if (valid) {
      onShow()
    } else {
      return false
    }
  })
}
//登录接口
const loginByUserApi = () => {
  console.log('登录接口')
loginByUsername(
    loginByUserForm.username,
    loginByUserForm.password,
    Number(isRememberMe.value),
    loginDevice.value,
  ).then(res => {
    console.log(res)
    if (res.data.code == 200) {
      setToken(res.data.data.token)
      console.log('res.data.data.token',res.data.data.token)
      userStore.userId = res.data.data.userId
      if (res.data.data.hasCompany == true) {
        if (res.data.data.hasMoreCompany == true) {
          userStore.departmentList = res.data.data.departmentList
          console.log('企业', userStore.departmentList)
          emit('forget-password', 2)
        }else {
router.push("/dashboard")
}
      } else {
        ElMessageBox.alert('您的账号还没有关联的公司，请联系管理员', '提示', {
          confirmButtonText: '确定',
          callback: () => {},
        })
      }
    }
  })
}

const forgetPas = () => {
  console.log('忘记密码')
  emit('forget-password', 1)
}

onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value)
  }
})
</script>

<style scoped lang="scss">
/* 将相关样式放在这里 */


</style>
