<template>
  <el-dialog
    v-model="dialogVisible"
    title="下载插件"
    width="1000px"
  >
    <div class="download-plugin-dialog">
      <!-- 加密网关配置 -->
      <div class="section">
        <div class="section-title">加密网关配置(规则拉取插件下载区域)</div>
        <div class="section-content">
          <div class="readonly-input-group">
            <span class="input-label">加密网关平台:</span>
            <el-input v-model="gatewayConfig.url"  class="input-field" />
            <el-input v-model="gatewayConfig.port"  class="input-field port-input" />
            <el-button type="primary" icon="Download" @click="downloadGatewayPlugin">下载</el-button>
          </div>
        </div>
      </div>

      <!-- 服务端加解密 -->
      <div class="section">
        <div class="section-title">服务端加解密(参数展示区域)</div>
        <div class="section-content">
          <div class="readonly-input-group">
            <span class="input-label">项目ID:</span>
            <el-input :value="projectId" disabled class="input-field" />
          </div>
        </div>
      </div>

      <!-- 应用项目配置 -->
      <div class="section">
        <div class="section-title">应用项目配置(规则推送插件下载区域)</div>
        <div class="section-content">
          <div class="add-project-btn">
            <el-button type="primary" plain @click="addProjectConfig">
              <el-icon><Plus /></el-icon>
              点击添加应用项目
            </el-button>
          </div>
          
          <div class="project-config-list">
            <el-table :data="projectConfigs" border style="width: 100%">
              <el-table-column prop="name" label="项目名称" width="180">
                <template #default="{ row, $index }">
                  <el-input v-model="row.name" placeholder="请输入项目名称" />
                </template>
              </el-table-column>
              
              <el-table-column prop="url" label="地址">
                <template #default="{ row, $index }">
                  <el-input v-model="row.url" placeholder="请输入地址 https://xxx.xxx.x.xxx" />
                </template>
              </el-table-column>
              
              <el-table-column prop="port" label="端口" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.port" placeholder="请输入端口 5544" />
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="300" align="center">
                <template #default="{ row, $index }">
                   <el-button type="danger" icon="Delete" @click="removeProjectConfig($index)">删除</el-button>
                  <el-button type="primary" icon="Download" @click="downloadProjectPlugin(row,$index)">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { Download, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
saveProxyJarInfo
} from '@/api/project'

const route = useRoute()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加密网关配置
const gatewayConfig = ref({
  url: '',
  port: ''
})

// 应用项目配置列表
const projectConfigs = ref([])

// 根据项目ID获取网关配置
const fetchGatewayConfig = async () => {
  // 模拟API调用，实际项目中替换为真实API
  return new Promise(resolve => {
    setTimeout(() => {
      // let url = import.meta.env.VITE_APP_BASE_API
      // const httpList = url.split(':')
      resolve({
        url:'',
        port:''
      })
    }, 300)
  })
}

// 添加项目配置
const addProjectConfig = () => {
  console.log('route',location.origin)
  projectConfigs.value.push({
    name: '',
    url: '',
    port: ''
  })
}

// 移除项目配置
const removeProjectConfig = (index) => {
  projectConfigs.value.splice(index, 1)
}

// 下载网关插件
const downloadGatewayPlugin = () => {
  window.open(`${gatewayConfig.value.url}:${gatewayConfig.value.port}/core/encryptionconfig/download?appProjectName=${import.meta.env.VITE_APP_TITLE}'&projectid=${props.projectId}&gatewayUrl=${gatewayConfig.value.url}&gatewayPort=${gatewayConfig.value.port}&appUrl=''&appPort=''`)
  // 实际项目中实现下载逻辑
}

// 下载项目插件
const downloadProjectPlugin = (item,index) => {
  const project = projectConfigs.value[index]
  if (!project.name || !project.url || !project.port) {
    ElMessage.warning('请先填写完整的项目配置')
    return
  }

  window.open(`${gatewayConfig.value.url}:${gatewayConfig.value.port}/core/encryptionconfig/download?appProjectName=${item.name}&projectid=${props.projectId}&gatewayUrl=${gatewayConfig.value.url}&gatewayPort=${gatewayConfig.value.port}&appUrl=${item.url}&appPort=${item.port}`)
}

// 确认操作
const handleConfirm = () => {
  // 验证项目配置
  for (const project of projectConfigs.value) {
    if (!project.name || !project.url || !project.port) {
      ElMessage.warning('请填写完整的项目配置')
      return
    }
  }
  
      saveProxyJarInfo('/core/encryptionconfig/saveProxyJarInfo', {
        gatewayUrl: gatewayConfig.value.url,
        gatewayPort: gatewayConfig.value.port,
        projectId: projectId,
        apps: projectConfigs.value.map( item => {
          return {
            appUrl: item.url,
            appProjectName: item.name,
            appPort: item.port
          }
        })
      }).then(res => {
          ElMessage.success('存储成功！')
          dialogVisible.value = false
      })

}



// 监听项目ID变化，获取网关配置
watch(() => props.projectId, async (newVal) => {
  if (newVal) {
    const config = await fetchGatewayConfig()
    gatewayConfig.value = config
  }
}, { immediate: true })
</script>

<style scoped>
.download-plugin-dialog {
  padding: 10px;
}

.section {
  margin-bottom: 20px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.section-content {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.readonly-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-label {
  width: 120px;
  text-align: right;
  padding-right: 10px;
  font-size: 14px;
}

.input-field {
  flex: 1;
  margin-right: 10px;
}

.port-input {
  width: 100px;
}

.add-project-btn {
  margin-bottom: 15px;
}

.project-config-list {
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.project-config-item {
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #eee;
  position: relative;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 10px;
}
</style>