<template>
  <div class="ip-config-container">
    <div class="config-header">
      <h2>IP检测配置</h2>
      <p class="config-desc">配置允许访问的地区IP范围，控制用户访问权限</p>
    </div>

    <div class="config-content">
      <!-- 开关控制 -->
      <el-card class="config-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>IP检测开关</span>
            <el-switch
              v-model="configData.status"
              :loading="statusLoading"
              active-text="开启"
              inactive-text="关闭"
              @change="handleStatusChange"
            />
          </div>
        </template>
        <div class="status-info">
          <el-alert
            :title="configData.status ? 'IP检测已开启' : 'IP检测已关闭'"
            :type="configData.status ? 'success' : 'info'"
            :description="configData.status ? '系统将根据配置的地区限制用户访问' : '系统不会进行IP地区检测'"
            show-icon
            :closable="false"
          />
        </div>
      </el-card>

      <!-- 重定向URL配置 -->
      <el-card class="config-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>重定向URL</span>
          </div>
        </template>
        <div class="url-config">
          <el-form :model="configData" label-width="100px">
            <el-form-item label="跳转地址" required>
              <el-input
                v-model="configData.toUrl"
                placeholder="请输入重定向URL，如：https://news.qq.com"
                type="url"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-text type="info" size="small">
                当用户IP不在允许地区时，将重定向到此URL
              </el-text>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <!-- 地区配置 -->
      <el-card class="config-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>允许访问地区</span>
            <el-button type="primary" icon="plus" @click="showAddDialog = true">
              添加地区
            </el-button>
          </div>
        </template>

        <div class="region-list">
          <el-empty v-if="!regionList.length" description="暂无配置地区" />
          <div v-else class="region-tags">
            <el-tag
              v-for="(region, index) in regionList"
              :key="index"
              closable
              type="success"
              size="large"
              @close="removeRegion(index)"
              class="region-tag"
            >
              {{ region }}
            </el-tag>
          </div>
        </div>

        <div class="action-buttons">
          <el-button 
            type="primary" 
            :loading="saveLoading"
            @click="saveConfig"
            :disabled="!regionList.length || !configData.toUrl"
          >
            保存配置
          </el-button>
          <el-button @click="resetConfig">重置</el-button>
        </div>
      </el-card>
    </div>

    <!-- 添加地区对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加允许访问地区"
      width="400px"
      destroy-on-close
    >
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="地区名称" required>
          <el-input
            v-model="addForm.region"
            placeholder="请输入地区名称，如：北京、上海、广东"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addRegion" :disabled="!addForm.region.trim()">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getIpCon, setIpCon, setIpStatus } from '@/api/user/index.js'

// 响应式数据
const configData = ref({
  ID: null,
  status: false,
  toUrl: '',
  addrs: ''
})
const statusLoading = ref(false)
const regionList = ref([])
const saveLoading = ref(false)
const showAddDialog = ref(false)
const addForm = ref({ region: '' })

// 获取IP检测配置
async function getIpDetectionConfig() {
  try {
    const res = await getIpCon()
    if (res.code === 0) {
      const data = res.data
      configData.value = {
        ID: data.ID,
        status: data.status,
        toUrl: data.toUrl || '',
        addrs: data.addrs || ''
      }
      // 解析地区字符串为数组
      regionList.value = data.addrs ? data.addrs.split(',').filter(addr => addr.trim()) : []
    }
  } catch (error) {
    console.error('获取IP检测配置失败:', error)
    ElMessage.error('获取IP检测配置失败')
  }
}

// 切换IP检测状态
async function handleStatusChange(value) {
  statusLoading.value = true
  try {
    const res = await setIpStatus({ status: value })
    if (res.code === 0) {
      ElMessage.success(value ? 'IP检测已开启' : 'IP检测已关闭')
      configData.value.status = value
    } else {
      ElMessage.error(res.msg || '状态更新失败')
      configData.value.status = !value // 恢复原状态
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    configData.value.status = !value // 恢复原状态
  } finally {
    statusLoading.value = false
  }
}

// 添加地区
function addRegion() {
  const region = addForm.value.region.trim()
  if (!region) {
    ElMessage.warning('请输入地区名称')
    return
  }
  
  if (regionList.value.includes(region)) {
    ElMessage.warning('该地区已存在')
    return
  }
  
  regionList.value.push(region)
  addForm.value.region = ''
  showAddDialog.value = false
  ElMessage.success('地区添加成功')
}

// 删除地区
function removeRegion(index) {
  ElMessageBox.confirm('确定要删除该地区吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    regionList.value.splice(index, 1)
    ElMessage.success('地区删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 保存完整配置
async function saveConfig() {
  if (!regionList.value.length) {
    ElMessage.warning('请至少添加一个地区')
    return
  }
  
  if (!configData.value.toUrl.trim()) {
    ElMessage.warning('请输入重定向URL')
    return
  }
  
  saveLoading.value = true
  try {
    const saveData = {
      ID: configData.value.ID,
      status: configData.value.status,
      toUrl: configData.value.toUrl.trim(),
      addrs: regionList.value.join(',')
    }
    
    const res = await setIpCon(saveData)
    if (res.code === 0) {
      ElMessage.success('配置保存成功')
      // 更新本地配置数据
      if (res.data && res.data.ID) {
        configData.value.ID = res.data.ID
      }
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 重置配置
function resetConfig() {
  ElMessageBox.confirm('确定要重置所有配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    regionList.value = []
    configData.value.toUrl = ''
    ElMessage.success('配置已重置')
  }).catch(() => {
    // 用户取消重置
  })
}

// 页面初始化
onMounted(() => {
  getIpDetectionConfig()
})
</script>

<style lang="scss" scoped>
.ip-config-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.config-header {
  margin-bottom: 20px;
  
  h2 {
    margin: 0 0 8px 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
  }
  
  .config-desc {
    margin: 0;
    color: #606266;
    font-size: 14px;
  }
}

.config-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.config-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    color: #303133;
  }
  
  .status-info {
    margin-top: 16px;
  }
  
  .url-config {
    margin-top: 16px;
  }
  
  .region-list {
    margin: 16px 0;
    min-height: 60px;
    
    .region-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .region-tag {
        margin: 0;
      }
    }
  }
  
  .action-buttons {
    margin-top: 16px;
    display: flex;
    gap: 12px;
  }
}

:deep(.el-card__header) {
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-alert) {
  border: none;
}
</style>
