<template>
  <el-form
    v-show="getShow"
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row style="margin-right: -10px; margin-left: -10px">
      <!-- <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col> -->
      <!-- <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
          <el-input
            v-model="loginData.loginForm.tenantName"
            :placeholder="t('login.tenantNamePlaceholder')"
            :prefix-icon="iconHouse"
            link
            type="primary"
          />
        </el-form-item>
      </el-col> -->
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px; margin-top: 10px">
        <el-form-item prop="username">
          <el-input
            v-model="loginData.loginForm.username"
            :placeholder="t('login.usernamePlaceholder')"
            class="custom-input"
          >
            <template #prefix>
              <img src="@/assets/imgs/login/user.png" class="custom-prefix-icon" alt="自定义图标" />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="password">
          <el-input
            v-model="loginData.loginForm.password"
            :placeholder="t('login.passwordPlaceholder')"
            show-password
            type="password"
            class="custom-input"
            @keyup.enter="getCode()"
          >
            <template #prefix>
              <img
                src="@/assets/imgs/login/password.png"
                class="custom-prefix-icon"
                alt="自定义图标"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item class="verify-code-item" prop="verificationCode">
          <div class="verify-code-input">
            <el-input
              v-model="loginData.loginForm.verificationCode"
              class="custom-input"
              placeholder="请输入验证码"
              style="width: 220px"
            />
            <img :src="imageUrl" class="tp_yzm" alt="验证码" @click="getCaptcha()" />
          </div>
        </el-form-item>
      </el-col> -->
      <el-col
        v-if="!isMobile"
        :span="24"
        style="padding-right: 10px; padding-left: 10px; margin-top: -16px; margin-bottom: -20px"
      >
        <el-form-item>
          <el-row justify="space-between" style="width: 100%">
            <el-col :span="6">
              <el-checkbox v-model="loginData.loginForm.rememberMe">
                <span class="jzmm">记住密码</span>
              </el-checkbox>
            </el-col>
            <!-- <el-col :offset="6" :span="12">
              <el-link
                style="float: right"
                type="primary"
                @click="setLoginState(LoginStateEnum.RESET_PASSWORD)"
              >
                <span class="wjmm">{{ t('login.forgetPassword') }}</span>
              </el-link>
            </el-col> -->
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px; margin-top: 12px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            title="登 录"
            class="w-[100%] s_btn"
            type="primary"
            @click="getCode()"
          />
        </el-form-item>
      </el-col>
      <Verify
        v-if="loginData.captchaEnable === 'true'"
        ref="verify"
        :captchaType="captchaType"
        :imgSize="{ width: '400px', height: '200px' }"
        mode="pop"
        @success="handleLogin"
      />
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
const route = useRoute() // 路由
import { useIcon } from '@/hooks/web/useIcon'
import * as OAuth2Api from '@/api/login/oauth2'
import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

import FeishuLogin from './FeishuLogin.vue'
// import FeishuLogin1 from './FeishuLogin1.vue'
// const feishuAppId = import.meta.env.VITE_FEISHU_APP_ID || 'cli_a834fd65ed3e100e'
// const feishuRedirectUri =
//   import.meta.env.VITE_FEISHU_REDIRECT_URI || 'http://122.152.216.7/business-app'
const redirectUri1 = import.meta.env.VITE_REDIRECT_URI || ''
console.log('redirectUri1', redirectUri1)

defineOptions({ name: 'LoginForm' })

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { setLoginState, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('clickWord') // blockPuzzle 滑块 clickWord 点击文字
const isMobile = ref(false)
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)
const imageUrl = ref()
const verificationCode = ref() //图片验证码
const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required],
  verificationCode: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    verificationCode: '',
    validationCode: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

interface queryType {
  responseType: string
  clientId: string
  redirectUri: string
  state: string
  scopes: string[]
}
const queryParams = reactive<queryType>({
  // URL 上的 client_id、scope 等参数
  responseType: '',
  clientId: '',
  redirectUri: '',
  state: '',
  scopes: [] // 优先从 query 参数获取；如果未传递，从后端获取
})
const client = ref({
  // 客户端信息
  name: '',
  logo: ''
})
interface formType {
  scopes: string[]
}
const formData = reactive<formType>({
  scopes: [] // 已选中的 scope 数组
})
const socialList = [
  { icon: 'ant-design:wechat-filled', type: 30 },
  { icon: 'ant-design:dingtalk-circle-filled', type: 20 },
  { icon: 'ant-design:github-filled', type: 0 },
  { icon: 'ant-design:alipay-circle-filled', type: 0 }
]

// 获取验证码
const getCode = async () => {
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}
// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    authUtil.setTenantId(res)
  }
}
// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}
// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  const website = location.host
  const res = await LoginApi.getTenantByWebsite(website)
  if (res) {
    loginData.loginForm.tenantName = res.name
    authUtil.setTenantId(res.id)
  }
}
const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params: any) => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }
    const loginDataLoginForm = { ...loginData.loginForm }
    loginDataLoginForm.captchaVerification = params.captchaVerification
    // loginDataLoginForm.validationCode = params.validationCode
    const res = await LoginApi.login(loginDataLoginForm)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginDataLoginForm.rememberMe) {
      authUtil.setLoginForm(loginDataLoginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    // console.log(666, redirect.value)
    // console.log(123, redirect.value, !redirect.value, redirect.value.indexOf('sso') !== -1)

    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      console.log('999999999999', window.location.href.replace('/login?redirect=', ''))
      // handleAuthorize(true)
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      // await push({ path: redirect.value || permissionStore.addRouters[0].path })
      // 登录成功后跳转到指定的SSO主页

      // await push({ path: '/' })
      await push({ path: '/home/index' })
    }
  } finally {
    loginLoading.value = false
    loading.value.close()
  }
}

/** 处理授权的提交 */
const handleAuthorize = async (approved) => {
  // 计算 checkedScopes + uncheckedScopes
  let checkedScopes
  let uncheckedScopes
  if (approved) {
    // 同意授权，按照用户的选择
    checkedScopes = formData.scopes
    uncheckedScopes = queryParams.scopes.filter((item) => checkedScopes.indexOf(item) === -1)
  } else {
    // 拒绝，则都是取消
    checkedScopes = []
    uncheckedScopes = queryParams.scopes
  }
  // 提交授权的请求
  // formLoading.value = true
  try {
    const data = await doAuthorize(false, checkedScopes, uncheckedScopes)
    if (!data) {
      return
    }
    location.href = data
  } finally {
    // formLoading.value = false
  }
}
/** 调用授权 API 接口 */
const doAuthorize = (autoApprove, checkedScopes, uncheckedScopes) => {
  console.log(
    100,
    queryParams.responseType,
    queryParams.clientId,
    queryParams.redirectUri,
    queryParams.state,
    autoApprove,
    checkedScopes,
    uncheckedScopes
  )

  return OAuth2Api.authorize(
    queryParams.responseType,
    queryParams.clientId,
    queryParams.redirectUri,
    queryParams.state,
    autoApprove,
    checkedScopes,
    uncheckedScopes
  )
}
// 社交登录
const doSocialLogin = async (type: number) => {
  window.location.href = 'http://122.152.216.7/admin-api/oauthApi/authCode' // 跳转到飞书
  // message.warning('该功能暂未开放')
  return
  if (type === 0) {
    message.error('此方式未配置')
  } else {
    loginLoading.value = true
    if (loginData.tenantEnable === 'true') {
      // 尝试先通过 tenantName 获取租户
      await getTenantId()
      // 如果获取不到，则需要弹出提示，进行处理
      if (!authUtil.getTenantId()) {
        try {
          const data = await message.prompt('请输入租户名称', t('common.reminder'))
          if (data?.action !== 'confirm') throw 'cancel'
          const res = await LoginApi.getTenantIdByName(data.value)
          authUtil.setTenantId(res)
        } catch (error) {
          if (error === 'cancel') return
        } finally {
          loginLoading.value = false
        }
      }
    }
    // 计算 redirectUri
    // 注意: type、redirect 需要先 encode 一次，否则钉钉回调会丢失。
    // 配合 social-login.vue#getUrlValue() 使用
    const redirectUri =
      location.origin +
      '/social-login?' +
      encodeURIComponent(`type=${type}&redirect=${redirect.value || '/'}`)

    // 进行跳转
    window.location.href = await LoginApi.socialAuthRedirect(type, encodeURIComponent(redirectUri))
  }
}

const toLogin = async (code) => {
  try {
    let redirectUri = redirectUri1
    await getTenantId()
    const res = await LoginApi.feishuLogin({ code, redirectUri })
    console.log(res)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // if (loginDataLoginForm.rememberMe) {
    //   authUtil.setLoginForm(loginDataLoginForm)
    // } else {
    //   authUtil.removeLoginForm()
    // }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }

    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      // await push({ path: redirect.value || permissionStore.addRouters[0].path })
      // 登录成功后跳转到指定的SSO主页
      await push({ path: '/' })
    }
  } finally {
    loading.value.close()
  }
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    console.log(9199, route)

    redirect.value = route?.query?.redirect as string
    // redirect.value = route.path
    // console.log(9199999, redirect.value)
  },
  {
    immediate: true
  }
)
const getCaptcha = async () => {
  const res = await LoginApi.createCaptcha()
  // console.log('res:', res.imageData)
  // const blob = new Blob([res], {
  //   // type: 'application/png;charset=utf-8'
  //   type: 'image/jpeg'
  // })
  // const url = window.URL.createObjectURL(blob)
  // console.log(999, blob, url)
  // imageUrl.value = url
  // const data = await res.imageData
  imageUrl.value = res.imageData

  loginData.loginForm.validationCode = res.validationCode
}
/** 初始化授权信息 */
const init = async () => {
  // console.log(9998888, route.query.client_id)

  // 防止在没有登录的情况下循环弹窗
  // if (typeof route.query.client_id === 'undefined') return
  // 解析参数
  // 例如说【自动授权不通过】：client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read%20user.write
  // 例如说【自动授权通过】：client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read
  const url = window.location.href
  const responseTypeMatch = url.match(/[?&]response_type=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const response_type = responseTypeMatch ? responseTypeMatch[1] : ''
  queryParams.responseType = response_type

  const clientIdMatch = url.match(/[?&]client_id=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const client_id = clientIdMatch ? clientIdMatch[1] : ''
  queryParams.clientId = client_id

  const redirectUriMatch = url.match(/[?&]redirect_uri=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const redirectUri = redirectUriMatch ? redirectUriMatch[1] : ''
  queryParams.redirectUri = redirectUri

  const stateMatch = url.match(/[?&]state=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const state = stateMatch ? stateMatch[1] : ''
  queryParams.state = state

  const scopeMatch = url.match(/[?&]scope=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const scope = scopeMatch ? scopeMatch[1] : ''
  console.log('scopescope', scope)

  // queryParams.scopes = scope

  if (scope) {
    queryParams.scopes = scope.split(' ')
  }
  // if (route.query.scope) {
  //   queryParams.scopes = (route.query.scope as string).split(' ')
  // }
  console.log(666, queryParams)

  // 如果有 scope 参数，先执行一次自动授权，看看是否之前都授权过了。
  if (queryParams.scopes.length > 0) {
    const data = await doAuthorize(true, queryParams.scopes, [])

    // console.log(191919, data)
    // debugger
    if (data) {
      location.href = data
      return
    }
  }

  // 获取授权页的基本信息
  const data = await OAuth2Api.getAuthorize(queryParams.clientId)
  client.value = data.client
  // 解析 scope
  let scopes
  // 1.1 如果 params.scope 非空，则过滤下返回的 scopes
  if (queryParams.scopes.length > 0) {
    scopes = []
    for (const scope of data.scopes) {
      if (queryParams.scopes.indexOf(scope.key) >= 0) {
        scopes.push(scope)
      }
    }
    // 1.2 如果 params.scope 为空，则使用返回的 scopes 设置它
  } else {
    scopes = data.scopes
    for (const scope of scopes) {
      queryParams.scopes.push(scope.key)
    }
  }
  // 生成已选中的 checkedScopes
  for (const scope of scopes) {
    if (scope.value) {
      formData.scopes.push(scope.key)
    }
  }
}

onMounted(() => {
  // getCaptcha()

  const url = window.location.href
  const ssoMatch = url.match(/[?&]sso=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  const ssoValue = ssoMatch ? ssoMatch[1] : null
  console.log('ssoValue', ssoValue, url.indexOf('/sso'))

  // if (url.indexOf('/sso')) {
  //   init()
  // }
  // const codeMatch = url.match(/[?&]code=([^&]+)/) // 匹配 ?code=xxx 或 &code=xxx
  // const codeValue = codeMatch ? codeMatch[1] : null
  // console.log('Code value:', codeValue) // "0wWiB3b3zA66AbFJF8Adw7x3FA0dH0Cy"
  // // const hasCode = new URLSearchParams(window.location.search).has('code')
  // // console.log('code', hasCode)
  // if (codeValue && !url.indexOf('/sso')) {
  //   toLogin(codeValue) // 处理回调逻辑
  // }

  checkMobile()
  window.addEventListener('resize', checkMobile)

  getLoginFormCache()
  getTenantByWebsite()
})

// 响应式检测
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}
.custom-input :deep(.el-input__wrapper) {
  border: 1px solid #6da0f0; /* 自定义边框颜色 */
  border-radius: 4px; /* 可选：调整圆角 */
  padding: 0 12px; /* 可选：调整内边距 */
  box-shadow: none; /* 移除默认阴影 */
  border-radius: 8px;
  font-size: 14px;
}
.custom-input :deep(.el-input__inner) {
  /* 如果使用非包装器版本（旧版） */
  height: 48px; /* 直接设置高度 */
  line-height: 48px; /* 垂直居中文本 */
}
.jzmm {
  font-family: OPPOSans;
  font-weight: 400;
  font-style: Medium;
  font-size: 14px;
  line-height: 100%;
  letter-spacing: 0%;
  color: #999999;
}
.wjmm {
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  font-style: Regular;
  font-size: 14px;
  // line-height: 100%;
  // letter-spacing: 0%;
  color: #999999;
}

:deep(.s_btn) {
  /* 修改边框 */
  border: 1px solid #0118a3; /* 边框颜色 */
  border-radius: 8px; /* 圆角 */
  height: 50px;
  /* 修改背景色 */
  background-color: #0118a3; /* 默认背景色 */
  /* 修改文字样式 */
  color: #ffffff; /* 文字颜色 */
  font-size: 18px; /* 文字大小 */
}

.verify-code-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.verify-code {
  flex-shrink: 0;
  width: 80px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  text-align: center;
  font-weight: bold;
}
.tp_yzm {
  width: 153px;
  height: 46px;
  margin-left: 2px;
  cursor: pointer;
}
</style>
