<template>
  <!-- 只有当启用登录时才显示登录界面 -->
  <div v-if="isLoginEnabled" class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>设备监控系统</h2>
        <p>欢迎登录</p>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" size="large" prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" size="large" prefix-icon="Lock"
            show-password @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" :loading="loading" @click="handleLogin" class="login-btn">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { CreateData, ExecDatabase, type ParameterTuple } from '../utils/webApiCall'

const router = useRouter()

// ==================== 配置开关 ====================
// 控制是否启用登录验证
// 设置为 true: 显示登录界面，需要验证
// 设置为 false: 不显示界面，直接进入系统
const isLoginEnabled = ref(true)  // 改为 true 启用登录
// ==================== 配置开关结束 ====================

const loginFormRef = ref<FormInstance>()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
})

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

// ==================== 免登录直接进入系统 ====================
const enterSystemWithoutLogin = () => {
  // 设置登录状态
  localStorage.setItem('isAuthenticated', 'true')
  localStorage.setItem('username', '访客用户')
  // 免登录模式下，不修改 MQTT Topic，使用配置文件中的默认值
  // localStorage.setItem('mqttTopic', 'default/topic') // 注释掉这行，不设置 mqttTopic

  // 根据屏幕方向跳转
  const width = window.innerWidth
  const height = window.innerHeight
  const routeName = width > height ? 'Landscape' : 'Portrait'

  router.push({ name: routeName })
}

// ==================== 登录验证相关代码（取消注释） ====================

// 创建数据库请求数据
const createLoginRequestData = (username: string, password: string) => {
  const param = []
  param.push(['TableName', '基础_登陆数据'])
  param.push(['PageNumber', '1'])
  param.push(['PageSize', '10'])
  param.push(['FieldsToSelect', '用户名,密码,mqttTopic'])
  param.push(['WhereConditions', `用户名 = '${username}' AND 密码 = '${password}'`])
  param.push(['SortField', 'ID'])
  param.push(['SortDirection', 'ASC'])
  param.push(['GroupByFields', null])

  return CreateData('11', param)
}

// 验证用户登录
const validateUser = async (
  username: string,
  password: string,
): Promise<{ success: boolean; message?: string; mqttTopic?: string }> => {
  try {
    const requestData = createLoginRequestData(username, password)
    // console.log('发送登录请求数据:', requestData)

    const response = await ExecDatabase(requestData)
    // console.log('登录验证响应:', response)

    if (response && response.data) {
      if (Array.isArray(response.data) && response.data.length > 0) {
        // 检查是否是错误响应
        if (response.data[0].hasOwnProperty('result')) {
          return {
            success: false,
            message: response.data[0].result || '登录验证失败',
          }
        } else {
          // 找到匹配的用户
          const user = response.data.find(
            (item: any) => item.用户名 === username && item.密码 === password,
          )

          if (user) {
            console.log('用户:', user)
            return {
              success: true,
              message: '登录成功',
              mqttTopic: user.mqttTopic || '',
            }
          } else {
            return {
              success: false,
              message: '用户名或密码错误',
            }
          }
        }
      } else {
        return {
          success: false,
          message: '用户名或密码错误',
        }
      }
    } else {
      return {
        success: false,
        message: '登录验证失败，请稍后重试',
      }
    }
  } catch (error: any) {
    // console.error('登录验证失败:', error)
    return {
      success: false,
      message: `登录过程出现错误: ${error.message}`,
    }
  }
}


// ==================== 登录处理函数 ====================
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    // 验证表单
    await loginFormRef.value.validate()
    loading.value = true

    // ========== 修改1：启用数据库验证 ==========
    // 调用数据库验证方法
    const result = await validateUser(loginForm.username, loginForm.password)

    if (result.success) {
      // 保存登录状态
      localStorage.setItem('isAuthenticated', 'true')
      localStorage.setItem('username', loginForm.username)

      // 更新 MQTT Topic
      if (result.mqttTopic) {
        localStorage.setItem('mqttTopic', 'SCADAMain/' + result.mqttTopic)
        // 更新全局配置中的 mqttTopic
        if (window.updateMqttTopic) {
          window.updateMqttTopic('SCADAMain/' + result.mqttTopic)
        } else {
          // 如果全局方法不存在，直接更新配置
          window.dt_Config.mqttTopic = 'SCADAMain/' + result.mqttTopic
        }
      }

      ElMessage.success(result.message || '登录成功')

      // 跳转到竖屏页面
      redirectAfterLogin()
    } else {
      ElMessage.error(result.message || '登录失败')
    }
    // ========== 修改结束 ==========

    // ========== 注释掉原来的测试账户代码 ==========
    /*
    // 临时跳过数据库验证 - 添加测试账户
    if (loginForm.username === 'admin' && loginForm.password === 'admin') {
      // 保存登录状态
      localStorage.setItem('isAuthenticated', 'true')
      localStorage.setItem('username', loginForm.username)
      // 测试账户使用默认的 MQTT Topic
      // localStorage.setItem('mqttTopic', 'default/topic') // 注释掉这行

      ElMessage.success('登录成功（测试模式）')

      // 跳转到主页面
      redirectAfterLogin()
      return
    }

    // 如果没有匹配的测试账户，显示错误
    ElMessage.error('当前数据库不可用，请使用测试账户 admin/admin')
    */
    // ========== 注释结束 ==========

  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录过程出现错误')
  } finally {
    loading.value = false
  }
}

// ==================== 登录成功后的重定向 ====================
const redirectAfterLogin = () => {
  // 根据屏幕方向决定跳转到哪个页面
  const width = window.innerWidth
  const height = window.innerHeight
  const routeName = width > height ? 'Landscape' : 'Portrait'

  router.push({ name: routeName })
}

// 组件挂载时
onMounted(() => {
  // 如果是免登录模式，直接进入系统
  if (!isLoginEnabled.value) {
    enterSystemWithoutLogin()
  } else {
    // 如果启用了登录，检查是否已经登录过
    const isAuthenticated = localStorage.getItem('isAuthenticated')
    if (isAuthenticated) {
      // 如果已经登录，直接跳转
      redirectAfterLogin()
    }
    // 否则显示登录界面
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #0f0d8a 100%);
  background-size: cover;
  overflow-y: auto;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 10px;
  font-size: 24px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}
</style>
