<template>
  <div class="section basic-info-section">
    <div class="section-header">
      <span class="section-icon">&#128176;</span>
      <span class="section-title">成本信息</span>
    </div>
    <div class="section-body">
      <el-descriptions :column="3" border size="small">
        <el-descriptions-item label="囤积成本">
          <span class="cost-value">{{ hoardingCost }}</span>
          <span class="cost-unit">t&#183;天</span>
        </el-descriptions-item>
        <el-descriptions-item label="囤积天数">
          <span>{{ hoardingDays }} 天</span>
        </el-descriptions-item>
        <el-descriptions-item label="钢卷净重">
          <span>{{ coilInfo.netWeight || 0 }} t</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="costReport" label="产线类型">
          <el-tag size="mini">{{ lineTypeName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="costReport" label="投入量">
          <span>{{ costReport.inputWeight || 0 }} t</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="costReport" label="产出量">
          <span>{{ costReport.outputWeight || 0 }} t</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="costReport" label="报表日期">
          <span>{{ costReport.reportDate }}</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="costReport" label="报表名称">
          <span>{{ costReport.reportTitle }}</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="totalCost != null" label="当班总成本">
          <span class="cost-value">{{ totalCost }}</span>
          <span class="cost-unit"> 元</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 成本明细表格 -->
      <div v-if="costRows && costRows.length" class="cost-table-wrap">
        <div class="cost-table-title">当日生产成本明细</div>
        <el-table :data="costRows" border stripe size="mini" style="width:100%">
          <el-table-column label="日期" prop="detailDate" width="100" align="center" />
          <template v-for="item in costItems">
            <el-table-column v-if="item.itemCode" :key="'i' + item.itemId"
              :label="item.itemName + (item.unit ? '(' + item.unit + ')' : '')" width="110" align="center">
              <template slot-scope="s">
                {{ formatVal(s.row['q_' + item.itemCode]) }}
              </template>
            </el-table-column>
          </template>
          <template v-for="m in costMetrics">
            <el-table-column v-if="m.metricName" :key="'m' + m.metricId" :label="m.metricName" width="100"
              align="center">
              <template slot-scope="s">
                {{ formatVal(s.row['mv_' + m.metricName]) }}
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import costDataService from '@/views/cost/costDataService'

/**
 * 仓库ID -> 成本产线类型映射
 * 酸连轧成品库 -> 2，镀锌成品库 -> 1
 */
const WAREHOUSE_LINE_TYPE_MAP = {
  '1988150099140866050': '2',
  '1988150323162836993': '1'
}

const LINE_TYPE_NAME_MAP = {
  '2': '酸轧',
  '1': '镀锌'
}

export default {
  name: 'CostInfoSection',
  props: {
    coilInfo: { type: Object, default: () => ({}) },
    traceResult: { type: Object, default: null },
    hoardingDays: { type: Number, default: 0 },
    hoardingCost: { type: [String, Number], default: '0.00' }
  },
  data() {
    return {
      costData: null,
      loadingCost: false
    }
  },
  computed: {
    lineType() {
      return WAREHOUSE_LINE_TYPE_MAP[this.coilInfo.warehouseId] || null
    },
    lineTypeName() {
      return this.lineType ? (LINE_TYPE_NAME_MAP[this.lineType] || this.lineType) : ''
    },
    costReport() {
      return this.costData ? this.costData.report : null
    },
    costMetrics() {
      return this.costData ? this.costData.metrics : []
    },
    costItems() {
      if (!this.costData) return []
      return this.costData.items.filter(item => this.costData.detailMap[item.itemId])
    },
    costRows() {
      return this.costData ? this.costData.data : []
    },
    totalCost() {
      if (!this.costRows || !this.costRows.length) return null
      for (const row of this.costRows) {
        for (const key of Object.keys(row)) {
          if (key.startsWith('mv_') && row[key] != null) {
            return row[key]
          }
        }
      }
      return null
    }
  },
  watch: {
    'coilInfo.warehouseId': {
      immediate: true,
      handler() {
        this.fetchCostData()
      }
    }
  },
  methods: {
    formatVal(val) {
      return val != null ? val : '-'
    },
    async fetchCostData() {
      console.log(this.coilInfo.warehouseId)
      console.log(this.lineType)
      if (!this.lineType) return
      const createTime = this.coilInfo.createTime
      if (!createTime) return
      const date = createTime.slice(0, 10)
      this.loadingCost = true
      try {
        console.log(date, this.lineType, '获取成本数据')
        this.costData = await costDataService.getCostDataByDate(date, this.lineType)
        console.log(this.costData, '成本数据')
      } catch (e) {
        console.error('获取成本数据失败:', e)
      } finally {
        this.loadingCost = false
      }
    }
  }
}
</script>

<style scoped>
.cost-value {
  font-weight: 600;
  color: #f56c6c;
}

.cost-unit {
  font-size: 12px;
  color: #909399;
  margin-left: 2px;
}

.cost-table-wrap {
  margin-top: 10px;
}

.cost-table-title {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  padding: 6px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 6px;
}
</style>
