<template>
  <el-drawer
    v-model="dialogVisible"
    title="自动比价"
    direction="rtl"
    size="100%"
    :close-on-press-escape="true"
    :destroy-on-close="true"
  >
    <div class="mobile-compare" v-loading="loading">
      <!-- 比价单信息 -->
      <div class="mobile-compare__section">
        <div class="mobile-compare__section-title">比价单信息</div>
        <div class="mobile-compare__info-row">
          <span class="mobile-compare__info-label">比价单号</span>
          <span>{{ inquiryData?.no }}</span>
        </div>
        <div class="mobile-compare__info-row">
          <span class="mobile-compare__info-label">产品名称</span>
          <span>{{ inquiryData?.productName }}</span>
        </div>
        <div class="mobile-compare__info-row">
          <span class="mobile-compare__info-label">需求数量</span>
          <span>{{ inquiryData?.requireCount }}</span>
        </div>
      </div>

      <!-- 权重配置 -->
      <div class="mobile-compare__section">
        <div class="mobile-compare__section-title">
          评分权重配置
          <el-tag size="small" :type="totalWeight === 100 ? 'success' : 'danger'" style="margin-left: 8px">
            合计: {{ totalWeight }}%
          </el-tag>
        </div>
        <el-form :model="weightConfig" label-position="top">
          <div class="mobile-compare__weight-grid">
            <el-form-item label="价格权重">
              <el-input-number v-model="weightConfig.priceWeight" :min="0" :max="100" :precision="0" controls-position="right" style="width: 100%" />
            </el-form-item>
            <el-form-item label="质量权重">
              <el-input-number v-model="weightConfig.qualityWeight" :min="0" :max="100" :precision="0" controls-position="right" style="width: 100%" />
            </el-form-item>
            <el-form-item label="交付权重">
              <el-input-number v-model="weightConfig.deliveryWeight" :min="0" :max="100" :precision="0" controls-position="right" style="width: 100%" />
            </el-form-item>
            <el-form-item label="服务权重">
              <el-input-number v-model="weightConfig.serviceWeight" :min="0" :max="100" :precision="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 供应商报价评分卡片 -->
      <div class="mobile-compare__section">
        <div class="mobile-compare__section-title">供应商报价评分</div>
        <div class="mobile-compare__card-list">
          <div
            v-for="(row, idx) in quoteList"
            :key="idx"
            class="mobile-compare__card"
            :class="{ 'mobile-compare__card--best': row.isSelected }"
          >
            <div class="mobile-compare__card-header">
              <span class="mobile-compare__card-name">{{ row.supplierName || '-' }}</span>
              <el-tag v-if="row.isSelected" type="success" size="small">推荐</el-tag>
            </div>
            <div class="mobile-compare__card-info">
              <div class="mobile-compare__info-row">
                <span class="mobile-compare__info-label">单价</span>
                <span>{{ row.unitPrice?.toFixed(2) ?? '-' }}</span>
              </div>
              <div class="mobile-compare__info-row">
                <span class="mobile-compare__info-label">总价</span>
                <span>{{ row.totalPrice?.toFixed(2) ?? '-' }}</span>
              </div>
              <div class="mobile-compare__info-row">
                <span class="mobile-compare__info-label">交货周期</span>
                <span>{{ row.deliveryCycle != null ? row.deliveryCycle + '天' : '-' }}</span>
              </div>
            </div>
            <div class="mobile-compare__card-scores">
              <div class="mobile-compare__score-input-group">
                <div class="mobile-compare__score-input">
                  <span class="mobile-compare__score-input-label">质量评分</span>
                  <el-input-number v-model="row.qualityScore" :min="0" :max="100" :precision="0" size="small" controls-position="right" style="width: 100%" />
                </div>
                <div class="mobile-compare__score-input">
                  <span class="mobile-compare__score-input-label">服务评分</span>
                  <el-input-number v-model="row.serviceScore" :min="0" :max="100" :precision="0" size="small" controls-position="right" style="width: 100%" />
                </div>
              </div>
              <div class="mobile-compare__score-results">
                <div class="mobile-compare__score-item">
                  <span class="mobile-compare__score-item-label">价格</span>
                  <span>{{ row.priceScore?.toFixed(1) ?? '-' }}</span>
                </div>
                <div class="mobile-compare__score-item">
                  <span class="mobile-compare__score-item-label">交付</span>
                  <span>{{ row.deliveryScore?.toFixed(1) ?? '-' }}</span>
                </div>
                <div class="mobile-compare__score-item mobile-compare__score-item--total">
                  <span class="mobile-compare__score-item-label">综合</span>
                  <el-tag v-if="row.totalScore != null" :type="row.isSelected ? 'success' : 'info'" size="small">{{ row.totalScore?.toFixed(2) }}</el-tag>
                  <span v-else style="color:#c0c4cc">-</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="mobile-compare__tips">
          <p>* 价格得分：价格越低得分越高（最低价得100分）</p>
          <p>* 交付得分：周期越短得分越高（最短周期得100分）</p>
          <p>* 质量/服务评分：手动输入（0-100），未填按0分计</p>
        </div>
      </div>

      <!-- 比价结果 -->
      <el-alert
        v-if="bestQuote"
        :title="`推荐: ${bestQuote.supplierName}，综合得分: ${bestQuote.totalScore?.toFixed(2)}`"
        type="success"
        show-icon
        :closable="false"
        style="margin-bottom: 12px"
      />
    </div>
    <template #footer>
      <el-button @click="handleCompare" type="primary">开始比价</el-button>
      <el-button @click="handleSave" type="success" :disabled="!bestQuote">保存结果</el-button>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { PurchaseInquiryApi, PurchaseInquiryVO, PurchaseInquiryQuoteVO } from '@/api/erp/purchase/inquiry'

defineOptions({ name: 'AutoCompareDialog' })

const message = useMessage()
const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const loading = ref(false)
const inquiryData = ref<PurchaseInquiryVO | null>(null)
const quoteList = ref<PurchaseInquiryQuoteVO[]>([])

/** 权重配置 */
const weightConfig = reactive({
  priceWeight: 40,
  qualityWeight: 25,
  deliveryWeight: 20,
  serviceWeight: 15
})

/** 计算权重合计 */
const totalWeight = computed(() => {
  return weightConfig.priceWeight + weightConfig.qualityWeight +
         weightConfig.deliveryWeight + weightConfig.serviceWeight
})

/** 最佳报价供应商 */
const bestQuote = ref<PurchaseInquiryQuoteVO | null>(null)

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  loading.value = true
  bestQuote.value = null
  try {
    inquiryData.value = await PurchaseInquiryApi.getPurchaseInquiry(id)
    quoteList.value = inquiryData.value?.quotes || []
    // 自动计算各项得分
    calculateScores()
  } finally {
    loading.value = false
  }
}
defineExpose({ open })

/** 自动计算各项得分 */
const calculateScores = () => {
  if (!quoteList.value || quoteList.value.length === 0) return

  // 计算总价
  const requireCount = inquiryData.value?.requireCount || 1
  quoteList.value.forEach(quote => {
    if (quote.unitPrice != null && quote.unitPrice > 0) {
      quote.totalPrice = quote.unitPrice * requireCount
    } else {
      quote.totalPrice = 0
    }
  })

  // 计算价格得分（价格越低得分越高）
  const prices = quoteList.value.filter(q => q.unitPrice != null && q.unitPrice > 0).map(q => q.unitPrice!)
  if (prices.length > 0) {
    const minPrice = Math.min(...prices)
    quoteList.value.forEach(quote => {
      if (quote.unitPrice != null && quote.unitPrice > 0) {
        quote.priceScore = (minPrice / quote.unitPrice) * 100
      } else {
        quote.priceScore = 0
      }
    })
  }

  // 计算交付得分（交货周期越短得分越高）
  const cycles = quoteList.value.filter(q => q.deliveryCycle != null && q.deliveryCycle > 0).map(q => q.deliveryCycle!)
  if (cycles.length > 0) {
    const minCycle = Math.min(...cycles)
    quoteList.value.forEach(quote => {
      if (quote.deliveryCycle != null && quote.deliveryCycle > 0) {
        quote.deliveryScore = (minCycle / quote.deliveryCycle) * 100
      } else {
        quote.deliveryScore = 0
      }
    })
  } else {
    quoteList.value.forEach(quote => {
      quote.deliveryScore = 0
    })
  }

  // 计算综合得分
  quoteList.value.forEach(quote => {
    quote.totalScore =
      (quote.priceScore || 0) * (weightConfig.priceWeight / 100) +
      (quote.qualityScore || 0) * (weightConfig.qualityWeight / 100) +
      (quote.deliveryScore || 0) * (weightConfig.deliveryWeight / 100) +
      (quote.serviceScore || 0) * (weightConfig.serviceWeight / 100)
  })
}

/** 开始比价 */
const handleCompare = () => {
  // 校验权重合计
  if (totalWeight.value !== 100) {
    message.warning('权重合计必须等于100%')
    return
  }

  // 校验是否有报价
  if (quoteList.value.length < 2) {
    message.warning('至少需要2个供应商报价才能进行比价')
    return
  }

  // 校验是否有单价
  const noPriceQuotes = quoteList.value.filter(q => q.unitPrice == null || q.unitPrice <= 0)
  if (noPriceQuotes.length > 0) {
    message.warning('所有供应商必须填写单价')
    return
  }

  // 使用已有的价格得分和交付得分（在明细中已自动计算），根据自定义权重重新计算综合得分
  quoteList.value.forEach(quote => {
    quote.totalScore =
      (quote.priceScore || 0) * (weightConfig.priceWeight / 100) +
      (quote.qualityScore || 0) * (weightConfig.qualityWeight / 100) +
      (quote.deliveryScore || 0) * (weightConfig.deliveryWeight / 100) +
      (quote.serviceScore || 0) * (weightConfig.serviceWeight / 100)
  })

  // 找出得分最高的供应商
  const sortedQuotes = [...quoteList.value].sort((a, b) =>
    (b.totalScore || 0) - (a.totalScore || 0)
  )
  bestQuote.value = sortedQuotes[0]

  // 标记选中状态
  quoteList.value.forEach(quote => {
    quote.isSelected = quote === bestQuote.value
  })

  message.success(`比价完成，推荐供应商: ${bestQuote.value.supplierName}`)
}

/** 保存比价结果 */
const handleSave = async () => {
  if (!inquiryData.value || !bestQuote.value) {
    return
  }
  
  loading.value = true
  try {
    // 更新比价单数据
    const data = {
      ...inquiryData.value,
      quotes: quoteList.value
    }
    await PurchaseInquiryApi.updatePurchaseInquiry(data)
    message.success('保存成功')
    dialogVisible.value = false
    emit('success')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.mobile-compare {
  padding: 12px;
  &__section {
    background: #fff;
    border-radius: 10px;
    padding: 14px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  }
  &__section-title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
  }
  &__info-row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 13px;
    color: #606266;
  }
  &__info-label {
    color: #909399;
    flex-shrink: 0;
    margin-right: 10px;
  }
  &__weight-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  &__card-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  &__card {
    border: 2px solid #f0f0f0;
    border-radius: 8px;
    overflow: hidden;
    transition: border-color 0.2s;
    &--best {
      border-color: #67c23a;
      background: #f0f9eb;
    }
  }
  &__card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 12px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }
  &__card-name {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
  }
  &__card-info {
    padding: 8px 12px;
  }
  &__card-scores {
    padding: 8px 12px;
    border-top: 1px dashed #e4e7ed;
  }
  &__score-input-group {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 8px;
  }
  &__score-input-label {
    font-size: 12px;
    color: #909399;
    display: block;
    margin-bottom: 4px;
  }
  &__score-results {
    display: flex;
    justify-content: space-around;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
  }
  &__score-item {
    text-align: center;
    font-size: 13px;
    &--total {
      font-weight: 600;
    }
  }
  &__score-item-label {
    display: block;
    font-size: 11px;
    color: #909399;
    margin-bottom: 2px;
  }
  &__tips {
    margin-top: 10px;
    font-size: 11px;
    color: #909399;
    line-height: 1.6;
    p { margin: 0; }
  }
}
</style>
