<template>
    <div v-loading="detailLoading">
      <v-card v-if="order" outlined>
        <v-card-text>
          <v-row>
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">标题：</span>
                <span class="value">{{ order.title }}</span>
              </div>
            </v-col>
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">订单编号：</span>
                <span class="value">{{ order.order_no }}</span>
              </div>
            </v-col>
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">状态：</span>
                <v-chip :color="getStatusColor(order.status)" small>{{ order.status_label }}</v-chip>
              </div>
            </v-col>
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">需求描述：</span>
                <div class="value description-text">{{ order.description }}</div>
              </div>
            </v-col>

            <!-- 连通性分析 -->
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">图谱连通性：</span>
                <span class="value">
                  <v-chip v-if="order.can_connect === true" color="success" small>可连通</v-chip>
                  <v-chip v-else-if="order.can_connect === false" color="error" small>不可连通</v-chip>
                  <span v-else>未分析</span>
                </span>
              </div>
            </v-col>
            <v-col v-if="order.extraction_purpose" cols="12" md="6">
              <div class="detail-item">
                <span class="label">数据用途：</span>
                <span class="value">{{ order.extraction_purpose }}</span>
              </div>
            </v-col>

            <!-- LLM 提取结果 -->
            <v-col v-if="order.extracted_domains && order.extracted_domains.length" cols="12">
              <div class="detail-item">
                <span class="label">提取的业务领域：</span>
                <span class="value">
                  <v-chip
                    v-for="domain in order.extracted_domains"
                    :key="domain"
                    small
                    class="mr-2 mb-2"
                  >
                    {{ domain }}
                  </v-chip>
                </span>
              </div>
            </v-col>
            <v-col v-if="order.extracted_fields && order.extracted_fields.length" cols="12">
              <div class="detail-item">
                <span class="label">提取的数据字段：</span>
                <span class="value">
                  <v-chip
                    v-for="field in order.extracted_fields"
                    :key="field"
                    small
                    class="mr-2 mb-2"
                  >
                    {{ field }}
                  </v-chip>
                </span>
              </div>
            </v-col>

            <!-- 驳回原因 -->
            <v-col v-if="order.reject_reason" cols="12">
              <v-alert type="error" dense>{{ order.reject_reason }}</v-alert>
            </v-col>

            <!-- 关联结果 -->
            <v-col v-if="order.result_product_id" cols="12" md="6">
              <div class="detail-item">
                <span class="label">生成的数据产品：</span>
                <v-btn
                  text
                  color="primary"
                  small
                  @click="goToProduct(order.result_product_id)"
                >
                  查看数据产品 #{{ order.result_product_id }}
                </v-btn>
              </div>
            </v-col>
            <v-col v-if="order.result_dataflow_id" cols="12" md="6">
              <div class="detail-item">
                <span class="label">生成的数据流程：</span>
                <v-btn
                  text
                  color="primary"
                  small
                  @click="goToDataflow(order.result_dataflow_id)"
                >
                  查看数据流程 #{{ order.result_dataflow_id }}
                </v-btn>
              </div>
            </v-col>

            <!-- 审计信息 -->
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">创建人：</span>
                <span class="value">{{ order.created_by }}</span>
              </div>
            </v-col>
            <v-col cols="12" md="6">
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDateTime(order.created_at) }}</span>
              </div>
            </v-col>
            <v-col v-if="order.processed_by" cols="12" md="6">
              <div class="detail-item">
                <span class="label">处理人：</span>
                <span class="value">{{ order.processed_by }}</span>
              </div>
            </v-col>
            <v-col v-if="order.processed_at" cols="12" md="6">
              <div class="detail-item">
                <span class="label">处理时间：</span>
                <span class="value">{{ formatDateTime(order.processed_at) }}</span>
              </div>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>

      <!-- 操作按钮 -->
      <div v-if="order" class="mt-4 d-flex justify-end">
        <!-- 待处理/待人工处理/待补充：可编辑和分析 -->
        <v-btn v-if="canAnalyze(order.status)" color="primary" :loading="analyzeLoading" class="ml-2 half-button" @click="handleAnalyze">分析</v-btn>
        <!-- 待审批/待人工处理：可审批和驳回 -->
        <v-btn v-if="canApprove(order.status)" color="success" :loading="approveLoading" class="ml-2 half-button" @click="handleApprove">审批通过</v-btn>
        <v-btn v-if="canApprove(order.status)" color="error" :loading="rejectLoading" class="ml-2 half-button" @click="handleReject">驳回</v-btn>
        <!-- 数据产品就绪：可完成 -->
        <v-btn v-if="order.status === 'onboard'" color="success" :loading="completeLoading" class="ml-2 half-button" @click="handleComplete">完成</v-btn>
      </div>
    </div>
</template>

<script>
import { api } from '@/api/dataOrder'
import { formatDate } from '@/utils/date'

export default {
  name: 'OrderDetailDialog',
  props: {
    orderId: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      order: null,
      detailLoading: false,
      analyzeLoading: false,
      approveLoading: false,
      rejectLoading: false,
      completeLoading: false
    }
  },
  created () {
    this.fetchDetail()
  },
  methods: {
    async fetchDetail () {
      if (!this.orderId) return
      this.detailLoading = true
      try {
        const { data } = await api.getOrderDetail(this.orderId)
        this.order = data
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.detailLoading = false
      }
    },
    // 分析
    async handleAnalyze () {
      this.analyzeLoading = true
      try {
        const { data } = await api.analyzeOrder(this.orderId)
        if (data.can_connect) {
          this.$snackbar.success('分析完成，实体可连通！')
        } else {
          this.$snackbar.warning('分析完成，部分实体无法连通')
        }
        this.$emit('refresh')
        this.$emit('close')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.analyzeLoading = false
      }
    },
    // 审批通过
    async handleApprove () {
      this.approveLoading = true
      try {
        await api.approveOrder(this.orderId)
        this.$snackbar.success('审批通过')
        this.$emit('refresh')
        this.$emit('close')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.approveLoading = false
      }
    },
    // 驳回
    async handleReject () {
      this.$emit('reject', this.orderId)
    },
    // 完成
    async handleComplete () {
      this.completeLoading = true
      try {
        await api.completeOrder(this.orderId)
        this.$snackbar.success('完成成功')
        this.$emit('refresh')
        this.$emit('close')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.completeLoading = false
      }
    },
    // 状态判断函数
    canAnalyze (status) {
      return ['pending', 'manual_review', 'need_supplement'].includes(status)
    },
    canApprove (status) {
      return ['pending_approval', 'manual_review'].includes(status)
    },
    goToProduct (productId) {
      this.$router.push('/dataService/dataProduct')
    },
    goToDataflow (dataflowId) {
      this.$router.push('/data-governance/data-process')
    },
    getStatusColor (status) {
      const colors = {
        pending: 'info',
        analyzing: 'warning',
        pending_approval: 'primary',
        processing: 'primary',
        onboard: 'success',
        completed: 'success',
        rejected: 'error',
        need_supplement: 'warning',
        manual_review: 'warning'
      }
      return colors[status] || 'info'
    },
    formatDateTime (dateStr) {
      return formatDate(dateStr)
    }
  }
}
</script>

<style scoped>
.detail-item {
  margin-bottom: 12px;
}

.label {
  font-weight: 600;
  color: #666;
  margin-right: 8px;
}

.value {
  color: #333;
}

.description-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}
</style>
