<template>
  <div class="purchased-machine-detail">
    <div class="toolbar">
      <div class="left-area">
        <el-button 
          type="text" 
          icon="el-icon-arrow-left" 
          @click="handleBack"
          class="back-btn"
        >
          返回
        </el-button>
        <h2 class="page-title">已购商品详情</h2>
      </div>
    </div>

    <div class="detail-content" v-loading="loading">
      <!-- 基本信息卡片 -->
      <el-card v-if="detailData" class="detail-card">
        <div slot="header" class="card-header">
          <span>基本信息</span>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="挖矿账户">
            {{ detailData.poolUser || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="矿池名称">
            {{ detailData.pool || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="矿池挖矿地址">
            <div class="address-item" v-if="detailData.poolUrl">
              <span class="mono-ellipsis">{{ detailData.poolUrl }}</span>
              <el-button 
                type="text" 
                size="mini" 
                icon="el-icon-document-copy" 
                @click="handleCopy(detailData.poolUrl, '矿池挖矿地址')"
                class="copy-btn"
              >
                复制
              </el-button>
            </div>
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="矿池所挖币种">
            {{ detailData.coin || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="币种对应算法">
            {{ detailData.algorithm || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="收款钱包">
            <div class="address-item" v-if="detailData.walletAddress">
              <span class="mono-ellipsis" style="font-family: monospace;">{{ detailData.walletAddress }}</span>
              <el-button 
                type="text" 
                size="mini" 
                icon="el-icon-document-copy" 
                @click="handleCopy(detailData.walletAddress, '收款钱包')"
                class="copy-btn"
              >
                复制
              </el-button>
            </div>
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="挖矿信息页面地址" v-if="detailData.watchUrl">
            <div class="address-item">
              <span class="mono-ellipsis">{{ detailData.watchUrl }}</span>
              <el-button 
                type="text" 
                size="mini" 
                icon="el-icon-document-copy" 
                @click="handleCopy(detailData.watchUrl, '挖矿信息页面地址')"
                class="copy-btn"
              >
                复制
              </el-button>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 已购矿机信息列表 -->
      <el-card v-if="detailData" class="detail-card">
        <div slot="header" class="card-header">
          <span>已购矿机信息</span>
        </div>
        <el-table
          :data="purchasedMachinesList"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{ textAlign: 'left' }"
          :cell-style="{ textAlign: 'left' }"
          v-if="purchasedMachinesList && purchasedMachinesList.length > 0"
        >
          <el-table-column prop="workerId" label="矿工号" min-width="120">
            <template #default="scope">
              <span>{{ scope.row.workerId || '—' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="power" label="实时算力" min-width="140">
            <template #default="scope">
              <span>{{ scope.row.power || '—' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="recordTime" label="最近实时算力记录时间" min-width="180">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.recordTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="挖矿开始时间" min-width="160">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.startTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="挖矿结束时间" min-width="160">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.endTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="140">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="empty-table">
          <p>暂无矿机信息</p>
        </div>
      </el-card>

      <div v-if="!loading && !detailData" class="empty-state">
        <p>未找到详情信息</p>
      </div>
    </div>
  </div>
</template>

<script>
import { getPurchasedInfoV2 } from '../../api/order'

export default {
  name: 'PurchasedMachineDetail',
  data() {
    return {
      loading: false,
      detailData: null
    }
  },
  created() {
    this.fetchDetail()
  },
  computed: {
    /**
     * 已购矿机列表（从 detailData.purchasedMachines 中提取）
     */
    purchasedMachinesList() {
      if (!this.detailData) return []
      return Array.isArray(this.detailData.purchasedMachines) ? this.detailData.purchasedMachines : []
    }
  },
  methods: {
    /**
     * 获取详情数据
     */
    async fetchDetail() {
      const id = this.$route.params.id
      if (!id) {
        this.$message.error('缺少ID参数')
        this.handleBack()
        return
      }

      this.loading = true
      try {
        const params = {
          id: id
        }
        const res = await getPurchasedInfoV2(params)
        if (res && (res.code === 0 || res.code === 200)) {
          // 接口返回的数据可能在 res.data 中
          this.detailData = res.data || res
          
          if (!this.detailData) {
            this.$message.warning('未找到对应的详情信息')
          }
        } else {
          const errorMsg = (res && res.msg) || '获取详情失败'
          this.$message.error(errorMsg)
        }
      } catch (e) {
        console.error('获取详情失败', e)
        this.$message.error('获取详情失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    /**
     * 返回上一页
     */
    handleBack() {
      this.$router.go(-1)
    },
    /**
     * 格式化日期时间
     * @param {string|number} value - 日期时间值
     * @returns {string} 格式化后的日期时间字符串
     */
    formatDateTime(value) {
      if (!value) return '—'
      try {
        const str = String(value)
        return str.includes('T') ? str.replace('T', ' ') : str
      } catch (e) {
        return String(value)
      }
    },
    /**
     * 复制文本到剪贴板
     * @param {string} text - 需要复制的内容
     * @param {string} label - 语义标签，用于提示文案
     */
    async handleCopy(text, label = '内容') {
      if (!text) {
        this.$message({
          message: `${label}为空，无法复制`,
          type: 'warning',
          showClose: true
        })
        return
      }
      
      try {
        const value = String(text).trim()
        if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
          await navigator.clipboard.writeText(value)
          this.$message({
            message: `${label}已复制到剪贴板`,
            type: 'success',
            showClose: true
          })
        } else {
          // 备用复制方法
          const textArea = document.createElement('textarea')
          textArea.value = value
          textArea.style.position = 'fixed'
          textArea.style.left = '-9999px'
          document.body.appendChild(textArea)
          textArea.focus()
          textArea.select()
          try {
            document.execCommand('copy')
            this.$message({
              message: `${label}已复制到剪贴板`,
              type: 'success',
              showClose: true
            })
          } catch (err) {
            this.$message({
              message: '复制失败，请手动复制',
              type: 'error',
              showClose: true
            })
          }
          document.body.removeChild(textArea)
        }
      } catch (e) {
        console.error('复制失败', e)
        this.$message({
          message: '复制失败，请手动复制',
          type: 'error',
          showClose: true
        })
      }
    },
    /**
     * 获取状态文本
     * @param {number|boolean} status - 状态值
     * @returns {string} 状态文本
     */
    getStatusText(status) {
      const statusNum = Number(status)
      if (statusNum === 0) return '租约已到期'
      if (statusNum === 1) return '挖矿中'
      if (statusNum === 2) return '卖家矿机启动中'
      // 兼容旧数据（boolean类型）
      if (status === true) return '挖矿中'
      return '未知状态'
    },
    /**
     * 获取状态标签类型
     * @param {number|boolean} status - 状态值
     * @returns {string} el-tag 的类型
     */
    getStatusType(status) {
      const statusNum = Number(status)
      if (statusNum === 0) return 'info'      // 租约已到期 - 灰色
      if (statusNum === 1) return 'success'  // 挖矿中 - 绿色
      if (statusNum === 2) return 'warning'  // 卖家矿机启动中 - 黄色
      // 兼容旧数据（boolean类型）
      if (status === true) return 'success'
      return 'info'
    }
  }
}
</script>

<style scoped>
.purchased-machine-detail {
  padding: 4px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.left-area {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  padding: 0;
  font-size: 14px;
  color: #409eff;
}

.back-btn:hover {
  color: #66b1ff;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.detail-content {
  margin-top: 16px;
}

.detail-card {
  margin-bottom: 16px;
}

.card-header {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.address-item {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.address-item .mono-ellipsis {
  font-family: monospace;
  color: #303133;
  line-height: 1.5;
  word-break: break-all;
  flex: 1;
  min-width: 0;
}

.copy-btn {
  flex-shrink: 0;
  padding: 0 8px;
  color: #409eff;
}

.copy-btn:hover {
  color: #66b1ff;
}

.mono-ellipsis {
  font-family: monospace;
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.empty-state {
  padding: 40px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.empty-table {
  padding: 40px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style>

