<template>
  <div class="login-config-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>登录配置</span>
        </div>
      </template>
      
      <el-form :model="form" label-width="200px" v-loading="loading">
        <el-form-item label="PC端验证码登录">
          <el-switch
            v-model="form.sms_login_pc_enabled"
            active-text="开启"
            inactive-text="关闭"
            @change="handleUpdate('sms_login_pc_enabled', $event)"
          />
          <div class="form-tip">开启后，PC端登录页将显示短信验证码登录选项</div>
        </el-form-item>

        <el-form-item label="手机端验证码登录">
          <el-switch
            v-model="form.sms_login_mobile_enabled"
            active-text="开启"
            inactive-text="关闭"
            @change="handleUpdate('sms_login_mobile_enabled', $event)"
          />
          <div class="form-tip">开启后，移动端登录页将显示短信验证码登录选项</div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { getAllConfigs, updateConfig } from '../../../api/systemConfig'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const form = reactive({
  sms_login_pc_enabled: false,
  sms_login_mobile_enabled: false
})

const fetchConfigs = async () => {
  loading.value = true
  try {
    const res = await getAllConfigs() as any
    // Map array to object
    if (res.data) {
        // Find specific keys
        const pcConfig = res.data.find((c: any) => c.key === 'sms_login_pc_enabled')
        const mobileConfig = res.data.find((c: any) => c.key === 'sms_login_mobile_enabled')
        
        if (pcConfig) {
            form.sms_login_pc_enabled = pcConfig.value === 'true'
        }
        if (mobileConfig) {
            form.sms_login_mobile_enabled = mobileConfig.value === 'true'
        }
    }
  } catch (error) {
    console.error('Failed to fetch configs', error)
  } finally {
    loading.value = false
  }
}

const handleUpdate = async (key: string, value: boolean) => {
  try {
    await updateConfig({
      key: key,
      value: value ? 'true' : 'false',
      description: key === 'sms_login_pc_enabled' ? 'Enable SMS login for PC' : 'Enable SMS login for Mobile'
    })
    ElMessage.success('配置已更新')
  } catch (error) {
    ElMessage.error('更新失败')
    // Revert switch
    if (key === 'sms_login_pc_enabled') {
        form.sms_login_pc_enabled = !value
    } else {
        form.sms_login_mobile_enabled = !value
    }
  }
}

onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.login-config-container {
  padding: 20px;
}
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.2;
}
</style>

