<template>
  <el-dialog title="一键部署" :visible.sync="visible" width="680px" append-to-body @close="handleClose">
    <!-- Step 1: Upload -->
    <div v-if="step === 1">
      <el-upload
        ref="uploadRef"
        drag
        :auto-upload="false"
        :limit="1"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        action="">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将 ipole 文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <el-divider></el-divider>

      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="目标网关">{{ gid }}</el-descriptions-item>
        <el-descriptions-item label="当前版本">{{ currentVersion || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="文件名">{{ fileInfo.name || '--' }}</el-descriptions-item>
        <el-descriptions-item label="文件大小">{{ fileInfo.size || '--' }}</el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 16px; text-align: right">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="!fileInfo.name" @click="step = 2">下一步</el-button>
      </div>
    </div>

    <!-- Step 2: Confirm -->
    <div v-if="step === 2">
      <el-alert title="确认部署信息" type="warning" :closable="false" show-icon style="margin-bottom: 16px">
        <div>即将把 <strong>{{ gid }}</strong> 升级到新版本</div>
        <div style="margin-top: 4px; font-size: 12px; color: #909399">
          部署期间网关将短暂离线，goforever 会自动重启新版本
        </div>
      </el-alert>

      <el-descriptions :column="1" border size="small">
        <el-descriptions-item label="文件">{{ fileInfo.name }} ({{ fileInfo.size }})</el-descriptions-item>
        <el-descriptions-item label="MD5">{{ fileInfo.md5 || '--' }}</el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 16px; text-align: right">
        <el-button @click="step = 1">上一步</el-button>
        <el-button type="primary" :loading="pushing" @click="handlePush">确认下发</el-button>
      </div>
    </div>

    <!-- Step 3: Result -->
    <div v-if="step === 3">
      <div style="text-align: center; padding: 20px 0">
        <el-steps :active="pipelineStep" finish-status="success" align-center>
          <el-step title="上传"></el-step>
          <el-step title="下发"></el-step>
          <el-step title="P1检测"></el-step>
          <el-step title="P2检测"></el-step>
        </el-steps>
      </div>

      <div v-if="deployResult" style="margin-top: 16px">
        <el-alert
          :title="deployResult.success ? '部署成功' : '部署失败'"
          :type="deployResult.success ? 'success' : 'error'"
          :closable="false" show-icon>
        </el-alert>

        <!-- Phase 1 检测项 -->
        <div style="margin-top: 12px" v-if="deployResult.phase1Checks && deployResult.phase1Checks.length">
          <p style="font-size:13px;color:#909399;margin-bottom:4px">Phase 1 — 基础设施检测</p>
          <div v-for="check in deployResult.phase1Checks" :key="check.Name"
               style="display:flex;align-items:center;padding:6px 0">
            <i :class="check.Status === 'ok' ? 'el-icon-success' : 'el-icon-error'"
               :style="{color: check.Status === 'ok' ? '#67c23a' : '#f56c6c'}"></i>
            <span style="margin-left: 8px">{{ checkLabels[check.Name] || check.Name }}</span>
            <span style="margin-left: auto; font-size: 12px; color: #909399">{{ check.Detail }}</span>
          </div>
        </div>

        <!-- Phase 2 检测项 -->
        <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #eee"
             v-if="deployResult.phase2Checks && deployResult.phase2Checks.length">
          <p style="font-size:13px;color:#909399;margin-bottom:4px">Phase 2 — 业务恢复确认</p>
          <div v-for="check in deployResult.phase2Checks" :key="check.Name"
               style="display:flex;align-items:center;padding:6px 0">
            <i :class="check.Status === 'ok' ? 'el-icon-success' : 'el-icon-error'"
               :style="{color: check.Status === 'ok' ? '#67c23a' : '#f56c6c'}"></i>
            <span style="margin-left: 8px">{{ checkLabels[check.Name] || check.Name }}</span>
            <span style="margin-left: auto; font-size: 12px; color: #909399">{{ check.Detail }}</span>
          </div>
        </div>
        <div v-else-if="deployResult.success"
             style="margin-top:12px;padding:8px;background:#fff3e0;border-radius:4px;font-size:12px;color:#e65100">
          ⏳ Phase 2 业务恢复检测将在约5分钟后完成，请稍后刷新...
        </div>
      </div>

      <div v-if="!deployResult" style="text-align: center; padding: 20px; color: #909399">
        <i class="el-icon-loading" style="font-size: 24px"></i>
        <p>等待网关响应...</p>
        <p style="font-size: 12px">网关正在重启并运行健康检测</p>
      </div>

      <div style="margin-top: 16px; text-align: right">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { deployUpload, deployPush, deployStatus } from '@/api/longchi/device/gatewayconfig.js'

export default {
  name: 'DeployDialog',
  props: {
    gid: { type: String, required: true },
    tenant: { type: String, required: true },
    currentVersion: { type: String, default: '' }
  },
  data() {
    return {
      visible: false,
      step: 1,
      fileInfo: {},
      pushing: false,
      pipelineStep: 0,
      deployResult: null,
      pollTimer: null,
      p2Timer: null,
      checkLabels: {
        mqtt: 'MQTT连接',
        redis: 'Redis',
        serial: '串口',
        modbus: '设备采集',
        device_online: '设备在线'
      }
    }
  },
  methods: {
    open() {
      this.visible = true
      this.step = 1
      this.fileInfo = {}
      this.deployResult = null
    },
    handleFileChange(file) {
      this.fileInfo = {
        name: file.name,
        size: this.formatSize(file.size),
        file: file.raw
      }
    },
    handleFileRemove() {
      this.fileInfo = {}
    },
    formatSize(bytes) {
      if (bytes < 1024) return bytes + ' B'
      if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
      return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
    },
    async handlePush() {
      this.pushing = true
      try {
        // 1. Upload
        this.pipelineStep = 0
        const uploadRes = await deployUpload(this.fileInfo.file, this.gid, this.tenant)
        if (uploadRes.data.code !== 0) {
          this.$message.error('上传失败: ' + (uploadRes.data.message || '未知错误'))
          this.pushing = false
          return
        }
        this.pipelineStep = 1
        this.fileInfo.md5 = uploadRes.data.data.md5

        // 2. Push
        const pushRes = await deployPush(
          this.gid, this.tenant, '', 'ipole',
          uploadRes.data.data.path, uploadRes.data.data.md5
        )
        if (pushRes.data.code !== 0) {
          this.$message.error('下发失败: ' + (pushRes.data.message || '未知错误'))
          this.pushing = false
          return
        }
        this.pipelineStep = 2

        // 3. Poll results
        this.step = 3
        this.pollResult()
      } catch (e) {
        this.$message.error('部署失败: ' + (e.message || e))
      }
      this.pushing = false
    },
    pollResult() {
      let attempts = 0
      this.pollTimer = setInterval(async () => {
        attempts++
        try {
          const res = await deployStatus(this.gid)
          if (res.data.code === 0 && res.data.data) {
            const d = res.data.data
            // status !== 0 说明部署已结束，但需等 phase1Result 有值（health 数据晚于 ack 到达）
            if (d.status !== 0 && d.phase1Result) {
              clearInterval(this.pollTimer)
              const p1 = JSON.parse(d.phase1Result)
              const p2 = d.phase2Result ? JSON.parse(d.phase2Result) : null
              this.deployResult = {
                success: d.status === 1,
                phase1Checks: p1 ? p1.Checks : [],
                phase2Checks: p2 ? p2.Checks : []
              }
              this.pipelineStep = p2 ? 5 : 4
              // P1 有数据但 P2 为空，继续慢速轮询等 P2
              if (!p2) {
                this.pollPhase2()
              }
            }
            // 部署失败（status=2/3），无需等 health，直接展示
            if (d.status === 2 || d.status === 3) {
              clearInterval(this.pollTimer)
              const p1 = d.phase1Result ? JSON.parse(d.phase1Result) : null
              this.deployResult = {
                success: false,
                phase1Checks: p1 ? p1.Checks : [],
                phase2Checks: [],
                error: d.errorMsg
              }
            }
          }
        } catch (e) {
          // continue polling
        }
        if (attempts > 120) {
          clearInterval(this.pollTimer)
          this.$message.warning('等待超时，请手动检查网关状态')
        }
      }, 3000)
    },
    pollPhase2() {
      let attempts = 0
      this.p2Timer = setInterval(async () => {
        attempts++
        try {
          const res = await deployStatus(this.gid)
          if (res.data.code === 0 && res.data.data && res.data.data.phase2Result) {
            clearInterval(this.p2Timer)
            const p2 = JSON.parse(res.data.data.phase2Result)
            this.deployResult.phase2Checks = p2.Checks || []
            this.pipelineStep = 5
          }
        } catch (e) {
          // continue
        }
        if (attempts > 40) { // 10s × 40 = ~7min
          clearInterval(this.p2Timer)
        }
      }, 10000)
    },
    handleClose() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer)
      }
      if (this.p2Timer) {
        clearInterval(this.p2Timer)
      }
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    }
  }
}
</script>
