<template>
  <div class="pdms-simplify pdms-theme">
    <div class="header-actions">
      <button class="icon-btn" @click="goBack" title="返回">
        <i class="fas fa-arrow-left"></i> 返回分析中心
      </button>
    </div>

    <div class="optimization-header">
      <h2>
        <i class="fas fa-filter"></i>
        PDMS模型简化处理
      </h2>
      <p class="subtitle">按设备类型过滤批量删除内部构件，大幅度实现快速轻量化。</p>
    </div>

    <!-- 任务参数设置区 -->
    <div class="settings-panel" v-if="taskStatus === 'idle' || taskStatus === 'failed'">
      <div class="setting-group checkbox-group">
        <label>保留类别 (Keep Types)</label>
        <div class="checkbox-options">
          <el-checkbox-group v-model="formData.keepTypes">
            <el-checkbox label="SITE">SITE (场地)</el-checkbox>
            <el-checkbox label="ZONE">ZONE (区域)</el-checkbox>
            <el-checkbox label="STRU">STRU (结构)</el-checkbox>
            <el-checkbox label="FRAME">FRAME (框架)</el-checkbox>
            <el-checkbox label="SHELL">SHELL (壳体)</el-checkbox>
            <el-checkbox label="PLAT">PLAT (平台)</el-checkbox>
            <el-checkbox label="WALL">WALL (墙体)</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <div class="setting-group checkbox-group">
        <label>删除类别 (Remove Types)</label>
        <div class="checkbox-options">
          <el-checkbox-group v-model="formData.removeTypes">
            <el-checkbox label="PIPE">PIPE (管道)</el-checkbox>
            <el-checkbox label="BRAN">BRAN (分支)</el-checkbox>
            <el-checkbox label="ELBO">ELBO (弯头)</el-checkbox>
            <el-checkbox label="VALV">VALV (阀门)</el-checkbox>
            <el-checkbox label="FITT">FITT (管件)</el-checkbox>
            <el-checkbox label="NOZZ">NOZZ (管口)</el-checkbox>
            <el-checkbox label="EQUI">EQUI (设备)</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <div class="setting-group parameters-group">
        <div class="param-item">
          <label>包围盒内部补白 (BoundingShell Padding)</label>
          <el-input-number v-model="formData.padding" :min="0" :step="10" />
          <p class="help-text">指定边界包围盒的填充间距，默认 0.0</p>
        </div>
      </div>

      <div class="setting-group">
        <label>区域过滤 (Zone Filters, 可选)</label>
        <el-input 
          v-model="zoneFiltersInput" 
          placeholder="输入要处理的ZONE路径（逗号分隔），为空则全量处理"
        ></el-input>
      </div>

      <div class="setting-group toggle-group">
        <label>高级设置</label>
        <div class="toggle-control" style="margin-bottom: 12px;">
          <span>跳过已连接元素 (Skip Linked)？可大幅减少警告</span>
          <el-switch v-model="formData.skipLinkedElements" active-color="#3b82f6" inactive-color="#ff4949"></el-switch>
        </div>
        <div class="toggle-control">
          <span>开启模拟模式 (Dry Run)？仅模拟不真删</span>
          <el-switch v-model="formData.dryRun" active-color="#3b82f6" inactive-color="#ff4949"></el-switch>
        </div>
      </div>

      <div class="action-bar">
        <button class="primary-btn" @click="startTask" :disabled="isStarting">
          <i class="fas" :class="isStarting ? 'fa-spinner fa-spin' : 'fa-play'"></i>
          {{ isStarting ? '正在处理...' : '执行简化' }}
        </button>
      </div>

      <div v-if="errorMessage" class="error-message">
        <i class="fas fa-exclamation-triangle"></i> {{ errorMessage }}
      </div>
    </div>

    <!-- 任务执行中进度区 -->
    <div class="execution-panel" v-else-if="taskStatus === 'Processing'">
      <h3>
        <i class="fas fa-cog fa-spin"></i>
        正在处理PDMS模型，请耐心等待 (可能需要几分钟)...
      </h3>
      
      <div class="progress-container">
        <div class="progress-bar">
          <div class="progress-fill active"></div>
        </div>
      </div>
    </div>

    <!-- 任务结果区 -->
    <div class="result-panel" v-else-if="taskStatus === 'Completed' && taskResult">
      <div class="success-header">
        <i class="fas fa-check-circle success-icon"></i>
        <h3>模型简化完成</h3>
        <p v-if="taskResult.DryRun" style="color:var(--color-warning);">（本次为模拟运行模式，未真实删除模型）</p>
      </div>

      <div class="metrics-grid">
        <div class="metric-card">
          <div class="metric-icon"><i class="fas fa-trash-alt"></i></div>
          <div class="metric-info">
            <div class="metric-value highlight">{{ taskResult.RemovedCount || 0 }}</div>
            <div class="metric-label">移除类别构件数</div>
          </div>
        </div>
        <div class="metric-card">
          <div class="metric-icon"><i class="fas fa-check"></i></div>
          <div class="metric-info">
            <div class="metric-value">{{ taskResult.KeptCount || 0 }}</div>
            <div class="metric-label">保留构件总数</div>
          </div>
        </div>
        <div class="metric-card">
          <div class="metric-icon"><i class="fas fa-search-plus"></i></div>
          <div class="metric-info">
            <div class="metric-value">{{ taskResult.TotalVisited || 0 }}</div>
            <div class="metric-label">扫描构件总数</div>
          </div>
        </div>
        <div class="metric-card" v-if="taskResult.SkippedLinkedCount !== undefined">
          <div class="metric-icon"><i class="fas fa-link"></i></div>
          <div class="metric-info">
            <div class="metric-value">{{ taskResult.SkippedLinkedCount || 0 }}</div>
            <div class="metric-label">跳过连接构件数</div>
          </div>
        </div>
      </div>

      <div class="details-box">
        <h4>处理信息</h4>
        <p v-if="taskResult.Message" :class="{ 'error-text': taskResult.Errors && taskResult.Errors.length > 0 }">
          {{ taskResult.Errors && taskResult.Errors.length > 0 ? '部分成功/有告警: ' : '' }}{{ taskResult.Message }}
        </p>
        <p v-if="taskResult.StartedAt && taskResult.CompletedAt">
          执行时间: {{ formatTime(taskResult.StartedAt) }} - {{ formatTime(taskResult.CompletedAt) }}
        </p>

        <!-- Zone summaries -->
        <div v-if="taskResult.ZoneSummaries && taskResult.ZoneSummaries.length > 0">
          <h5 style="margin-top:20px; color: var(--color-text-primary);">Zone 处理汇总</h5>
          <ul>
            <li v-for="(summary, idx) in taskResult.ZoneSummaries" :key="idx">
              {{ summary }}
            </li>
          </ul>
        </div>

        <!-- Removed Elements Summary -->
        <div v-if="taskResult.RemovedElements && taskResult.RemovedElements.length > 0">
          <h5 style="margin-top:20px; color: var(--color-text-primary);">移除元件示例</h5>
          <ul>
            <li v-for="(el, idx) in taskResult.RemovedElements.slice(0, 5)" :key="idx">
              {{ el }}
            </li>
            <li v-if="taskResult.RemovedElements.length > 5">...以及其他 {{ taskResult.RemovedElements.length - 5 }} 个元件</li>
          </ul>
        </div>

        <!-- Skipped Linked Elements Summary -->
        <div v-if="taskResult.SkippedLinkedElements && taskResult.SkippedLinkedElements.length > 0">
          <h5 style="margin-top:20px; color: var(--color-text-primary);">跳过连接元件示例</h5>
          <ul>
            <li v-for="(el, idx) in taskResult.SkippedLinkedElements.slice(0, 5)" :key="'s-'+idx">
              {{ el }}
            </li>
            <li v-if="taskResult.SkippedLinkedElements.length > 5">...以及其他 {{ taskResult.SkippedLinkedElements.length - 5 }} 个元件</li>
          </ul>
        </div>

        <!-- Errors -->
        <div v-if="taskResult.Errors && taskResult.Errors.length > 0" class="error-message" style="margin-top:20px;">
          <p><i class="fas fa-exclamation-triangle"></i> 部分处理出错：</p>
          <ul>
            <li v-for="(err, idx) in taskResult.Errors.slice(0, 5)" :key="idx">{{ err }}</li>
            <li v-if="taskResult.Errors.length > 5">...以及其他 {{ taskResult.Errors.length - 5 }} 个错误</li>
          </ul>
        </div>
      </div>

      <div class="result-actions">
        <button class="primary-btn export-report-btn" @click="exportReport" :disabled="isExporting" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
          <i class="fas" :class="isExporting ? 'fa-spinner fa-spin' : 'fa-file-export'"></i> {{ isExporting ? '导出中...' : '导出报告' }}
        </button>
        <button class="primary-btn" @click="resetTask">
          <i class="fas fa-redo"></i> 再次处理
        </button>
        <button class="secondary-btn" @click="goBack">
          <i class="fas fa-home"></i> 返回分析中心
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElNotification } from 'element-plus'
import pdmsApi from '@/services/pdmsApi'

const emit = defineEmits(['page-change'])

// 状态定义
const taskStatus = ref('idle')
const isStarting = ref(false)
const errorMessage = ref('')
const taskResult = ref(null)
const isExporting = ref(false)

const zoneFiltersInput = ref("")

// 默认配置
const DEFAULT_SIMPLIFY_CONFIG = {
  DRY_RUN: false,
  SKIP_LINKED: true,
  KEEP_TYPES: ["SITE", "ZONE", "STRU", "FRAME", "SHELL", "PLAT", "WALL"],
  REMOVE_TYPES: ["PIPE", "BRAN", "ELBO", "VALV", "FITT", "NOZZ", "EQUI"],
  PADDING: 0.0
};

// 表单数据
const formData = reactive({
  dryRun: DEFAULT_SIMPLIFY_CONFIG.DRY_RUN,
  skipLinkedElements: DEFAULT_SIMPLIFY_CONFIG.SKIP_LINKED,
  keepTypes: [...DEFAULT_SIMPLIFY_CONFIG.KEEP_TYPES],
  removeTypes: [...DEFAULT_SIMPLIFY_CONFIG.REMOVE_TYPES],
  padding: DEFAULT_SIMPLIFY_CONFIG.PADDING
})

const goBack = () => {
  emit('page-change', 'analysis-tools')
}

const resetTask = () => {
  taskStatus.value = 'idle'
  taskResult.value = null
  errorMessage.value = ''
}

const formatTime = (timeStr) => {
  if (!timeStr) return ""
  return new Date(timeStr).toLocaleString()
}

const startTask = async () => {
  isStarting.value = true
  errorMessage.value = ''
  taskStatus.value = 'Processing'
  
  try {
    const payload = {
      dryRun: formData.dryRun,
      skipLinkedElements: formData.skipLinkedElements,
      zoneFilters: zoneFiltersInput.value ? zoneFiltersInput.value.split(',').map(s => s.trim()).filter(s => s) : [],
      keepTypes: formData.keepTypes,
      removeTypes: formData.removeTypes,
      boundingShell: {
        padding: formData.padding
      }
    }

    const res = await pdmsApi.executeSimplify(payload)
    if (res && res.data && res.data.code === 0) {
      taskStatus.value = 'Completed'
      taskResult.value = res.data.data || res.data
      ElNotification({
        title: '处理完成',
        message: 'PDMS模型简化处理执行完毕。',
        type: 'success'
      })
    } else {
      taskStatus.value = 'failed'
      errorMessage.value = (res.data && res.data.message) || (res && res.message) || '模型轻量化失败，返回数据异常。'
      ElNotification({
        title: '处理失败',
        message: errorMessage.value,
        type: 'error'
      })
    }
  } catch (err) {
    taskStatus.value = 'failed'
    errorMessage.value = err.response?.data?.message || err.message || '网络请求错误'
    ElNotification({
        title: '处理失败',
        message: errorMessage.value,
        type: 'error'
    })
  } finally {
    isStarting.value = false
  }
}
const exportReport = () => {
  if (isExporting.value || !taskResult.value) return
  isExporting.value = true

  try {
    const reportDate = new Date().toLocaleString('zh-CN')
    
    let zoneSummariesHTML = ''
    if (taskResult.value.ZoneSummaries && taskResult.value.ZoneSummaries.length > 0) {
      zoneSummariesHTML = `
        <h3 style="margin-top:20px;">Zone 处理汇总</h3>
        <ul>
          ${taskResult.value.ZoneSummaries.map(s => `<li>${s}</li>`).join('')}
        </ul>
      `
    }
    
    let errorHTML = ''
    if (taskResult.value.Errors && taskResult.value.Errors.length > 0) {
      errorHTML = `
        <h3 style="margin-top:20px; color:#e74c3c">处理警告与错误</h3>
        <ul style="color:#e74c3c">
          ${taskResult.value.Errors.map(e => `<li>${e}</li>`).join('')}
        </ul>
      `
    }

    const htmlContent = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PDMS模型简化处理报告</title>
  <style>
    :root {
      --primary-color: #3b82f6;
      --success-color: #2ecc71;
      --warning-color: #f39c12;
      --danger-color: #e74c3c;
      --text-main: #2b2b2b;
      --text-light: #7f8c8d;
      --bg-color: #f8f9fa;
      --card-bg: #ffffff;
      --border-color: #e9ecef;
    }
    body {
      font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
      background-color: var(--bg-color);
      color: var(--text-main);
      margin: 0;
      padding: 40px 20px;
    }
    .container {
      max-width: 1000px;
      margin: 0 auto;
      background: var(--card-bg);
      border-radius: 12px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.05);
      overflow: hidden;
    }
    .header {
      background: linear-gradient(135deg, #3b82f6, #1d4ed8);
      color: white;
      padding: 40px;
      text-align: center;
    }
    .header h1 {
      margin: 0 0 10px 0;
      font-size: 32px;
    }
    .content { padding: 40px; }
    .summary-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 24px;
      margin-bottom: 40px;
    }
    .summary-card {
      background: #f8f9fc;
      border: 1px solid var(--border-color);
      border-radius: 10px;
      padding: 24px;
      text-align: center;
    }
    .summary-value {
      font-size: 36px;
      font-weight: 700;
      color: var(--primary-color);
    }
    .details-box {
      background: #f8f9fa;
      padding: 20px;
      border-radius: 8px;
      border: 1px solid #e9ecef;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>PDMS模型简化处理报告</h1>
      <p>生成时间: ${reportDate}</p>
    </div>
    <div class="content">
      <div class="summary-grid">
        <div class="summary-card">
          <div class="summary-value" style="color:var(--danger-color)">${taskResult.value.RemovedCount || 0}</div>
          <div class="summary-label">移除构件数</div>
        </div>
        <div class="summary-card">
          <div class="summary-value" style="color:var(--success-color)">${taskResult.value.KeptCount || 0}</div>
          <div class="summary-label">保留构件数</div>
        </div>
        <div class="summary-card">
          <div class="summary-value">${taskResult.value.TotalVisited || 0}</div>
          <div class="summary-label">扫描总数</div>
        </div>
        <div class="summary-card">
          <div class="summary-value" style="color:var(--warning-color)">${taskResult.value.SkippedLinkedCount || 0}</div>
          <div class="summary-label">跳过连接构件</div>
        </div>
      </div>
      
      <div class="details-box">
        <h3>处理信息概要</h3>
        <p><strong>状态:</strong> ${taskResult.value.DryRun ? '模拟模式 (未真实删除)' : '正式执行'}</p>
        <p><strong>执行时间:</strong> ${formatTime(taskResult.value.StartedAt)} - ${formatTime(taskResult.value.CompletedAt)}</p>
        <p><strong>系统消息:</strong> ${taskResult.value.Message || '处理完毕'}</p>
        ${zoneSummariesHTML}
        ${errorHTML}
      </div>
    </div>
  </div>
</body>
</html>`

    const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `PDMS模型简化处理报告_${new Date().getTime()}.html`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    ElNotification({
      title: '导出成功',
      message: '已成功导出分析报告',
      type: 'success',
      duration: 2000
    })
  } catch (error) {
    console.error('导出报告失败', error)
  } finally {
    isExporting.value = false
  }
}

</script>

<style scoped>
/* Copied from PdmsShrinkwrapPage styling */
.pdms-simplify {
  background: linear-gradient(135deg, var(--color-bg-secondary) 0%, var(--color-bg-primary) 100%);
  border: 1px solid var(--color-border-primary);
  border-radius: 16px;
  padding: 24px;
  backdrop-filter: blur(20px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  animation: slideInUp 0.4s ease-out;
  color: var(--color-text-primary);
  min-height: 100%;
}

.header-actions {
  margin-bottom: 20px;
}

.icon-btn {
  background: transparent;
  border: none;
  color: #3b82f6;
  font-size: 1.1em;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}
.icon-btn:hover {
  transform: translateX(-4px);
  color: #2563eb;
}

.optimization-header {
  text-align: center;
  margin-bottom: 32px;
}

.optimization-header h2 {
  color: #3b82f6;
  font-size: 1.8em;
  font-weight: 600;
  margin: 0 0 12px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.optimization-header .subtitle {
  color: var(--color-text-secondary);
  font-size: 1em;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.6;
}

.settings-panel {
  background: var(--color-bg-card);
  border-radius: 12px;
  padding: 32px;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid var(--color-border-primary);
}

.setting-group {
  margin-bottom: 32px;
}

.setting-group > label {
  display: block;
  font-size: 1.1em;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--color-text-primary);
}

.parameters-group {
    display: flex;
    gap: 32px;
    flex-wrap: wrap;
}

.param-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.param-item label {
    font-weight: 500;
    color: var(--color-text-primary);
}

.param-item .help-text {
    font-size: 0.8em;
    color: var(--color-text-secondary);
    margin: 0;
}

.toggle-group {
  background: var(--color-bg-secondary);
  padding: 16px;
  border-radius: 12px;
}

.toggle-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-bar {
  text-align: center;
  margin-top: 32px;
}

::v-deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
}

::v-deep(.el-checkbox) {
    margin-right: 0;
    color: var(--color-text-primary);
}

.primary-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 14px 40px;
  font-size: 1.1em;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 auto;
}
.primary-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(59, 130, 246, 0.6);
}
.primary-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.secondary-btn {
  background: var(--color-bg-secondary);
  color: var(--color-text-primary);
  border: 1px solid var(--color-border-primary);
  border-radius: 8px;
  padding: 14px 40px;
  font-size: 1.1em;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 10px;
}
.secondary-btn:hover {
  background: var(--color-white-rgb-1);
}

.error-message {
  margin-top: 20px;
  padding: 12px;
  background: rgba(255, 73, 73, 0.1);
  color: #ff4949;
  border-left: 4px solid #ff4949;
  border-radius: 4px;
}

.error-text {
  color: #ff4949;
  font-weight: 500;
}

.execution-panel {
  text-align: center;
  padding: 60px 20px;
}

.execution-panel h3 {
  color: #3b82f6;
  font-size: 1.6em;
  margin-bottom: 40px;
}

.progress-container {
  max-width: 500px;
  margin: 0 auto;
}

.progress-bar {
  height: 8px;
  background: var(--color-border-primary);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #60a5fa);
  width: 50%;
  border-radius: 4px;
}
.progress-fill.active {
  animation: progressIndeterminate 2s infinite ease-in-out;
  transform-origin: 0% 50%;
}

@keyframes progressIndeterminate {
  0% { transform: translateX(-100%) scaleX(0.2); }
  50% { transform: translateX(0) scaleX(1); }
  100% { transform: translateX(200%) scaleX(0.2); }
}

.result-panel {
  max-width: 900px;
  margin: 0 auto;
}

.success-header {
  text-align: center;
  margin-bottom: 40px;
}
.success-icon {
  font-size: 64px;
  color: #3b82f6;
  margin-bottom: 16px;
  text-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
}
.success-header h3 {
  font-size: 1.8em;
  color: var(--color-text-primary);
  margin: 0;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.metric-card {
  background: var(--color-bg-card);
  border: 1px solid var(--color-border-primary);
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
}
.metric-icon {
  font-size: 32px;
  color: #3b82f6;
  width: 60px;
  height: 60px;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.metric-info {
  flex: 1;
}
.metric-value {
  font-size: 1.8em;
  font-weight: 700;
  color: var(--color-text-primary);
}
.metric-value.highlight {
  color: #3b82f6;
}
.metric-label {
  color: var(--color-text-secondary);
  font-size: 0.9em;
  margin-top: 4px;
}

.details-box {
  background: var(--color-bg-card);
  border: 1px solid var(--color-border-primary);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 40px;
}
.details-box h4 {
  margin: 0 0 20px 0;
  color: var(--color-text-primary);
  font-size: 1.2em;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>
