<template>
  <div class="app-container">
    <el-card class="mb20">
      <template #header>
        <div class="card-header">
          <span>{{ productDetail.productName }} - 产品详情</span>
          <el-button type="primary" plain size="small" @click="handleBack">返回列表</el-button>
        </div>
      </template>
      <div class="product-info">
        <div class="info-item">
          <span class="label">产品名称：</span>
          <span class="value">{{ productDetail.productName }}</span>
        </div>
        <div class="info-item">
          <span class="label">产品规格：</span>
          <span class="value">{{ productDetail.spec }}</span>
        </div>
        <div class="info-item">
          <span class="label">产品型号：</span>
          <span class="value">{{ productDetail.model }}</span>
        </div>
        <div class="info-item">
          <span class="label">产品单价：</span>
          <span class="value">{{ formatDecimal(productDetail.unitPrice) }} 元</span>
        </div>
        <div class="info-item">
          <span class="label">备注：</span>
          <span class="value">{{ productDetail.remark || '无' }}</span>
        </div>
      </div>
      <!-- 产品附加属性 -->
      <div class="product-addition" v-if="productAdditionList.length > 0">
        <h4>产品附加属性</h4>
        <el-table :data="productAdditionList" style="width: 100%" border>
          <el-table-column prop="attrName" label="属性名" width="150" />
          <el-table-column prop="attrValue" label="属性值" />
        </el-table>
      </div>
      <div class="product-images" v-if="productDetail.productImages && productDetail.productImages.trim()">
        <h4>产品图片</h4>
        <div class="image-list">
          <el-image
            v-for="(image, index) in productDetail.productImages.split(',').filter(img => img.trim())"
            :key="index"
            :src="image"
            :preview-src-list="productDetail.productImages.split(',').filter(img => img.trim())"
            style="width: 100px; height: 100px; margin-right: 10px;"
          />
        </div>
      </div>
      <div class="product-pdfs" v-if="pdfDisplayList.length > 0">
        <h4>产品说明书</h4>
        <div class="pdf-list">
          <div
            v-for="(pdf, index) in pdfDisplayList"
            :key="index"
            class="pdf-item"
          >
            <el-icon class="pdf-icon"><Document /></el-icon>
            <span class="pdf-name" :title="pdf.name">{{ pdf.name }}</span>
            <el-button type="primary" link size="small" @click="previewPdf(pdf)">预览</el-button>
            <el-button type="success" link size="small" @click="downloadPdf(pdf)">下载</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>材料明细</span>
        </div>
      </template>
      
      <!-- 主材部分 -->
      <div class="material-section">
        <h3 class="section-title">主材</h3>
        <el-table :data="mainMaterials" style="width: 100%" border>
          <el-table-column prop="materialName" label="配料名称" width="150" />
          <el-table-column prop="spec" label="材料规格" width="150" />
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column prop="price" label="价格" width="100" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="小计" width="100" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.subtotal) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="section-summary" v-if="mainMaterials.length > 0">
          <span>主材小计：{{ formatDecimal(mainMaterials.reduce((sum, item) => sum + item.subtotal, 0)) }} 元</span>
        </div>
      </div>

      <!-- 辅材部分 -->
      <div class="material-section">
        <h3 class="section-title">辅材</h3>
        <el-table :data="auxiliaryMaterials" style="width: 100%" border>
          <el-table-column prop="materialName" label="配料名称" width="150" />
          <el-table-column prop="spec" label="材料规格" width="150" />
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column prop="price" label="价格" width="100" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="小计" width="100" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.subtotal) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="section-summary" v-if="auxiliaryMaterials.length > 0">
          <span>辅材小计：{{ formatDecimal(auxiliaryMaterials.reduce((sum, item) => sum + item.subtotal, 0)) }} 元</span>
        </div>
      </div>

      <!-- 工价部分 -->
      <div class="material-section">
        <h3 class="section-title">工价</h3>
        <el-table :data="laborMaterials" style="width: 100%" border>
          <el-table-column prop="materialName" label="项目名称" width="150" />
          <el-table-column prop="spec" label="规格" width="150" />
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column prop="price" label="价格" width="100" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="小计" width="100" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.subtotal) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="section-summary" v-if="laborMaterials.length > 0">
          <span>工价小计：{{ formatDecimal(laborMaterials.reduce((sum, item) => sum + item.subtotal, 0)) }} 元</span>
        </div>
      </div>

      <div class="material-section" v-if="productLaborList.length > 0">
        <h3 class="section-title">工价（手动）</h3>
        <el-table :data="productLaborList" style="width: 100%" border>
          <el-table-column prop="laborName" label="工价说明" />
          <el-table-column prop="laborPrice" label="金额" width="140" align="center">
            <template #default="scope">
              {{ formatDecimal(scope.row.laborPrice) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="section-summary">
          <span>工价（手动）小计：{{ formatDecimal(productLaborList.reduce((sum, item) => sum + (Number(item.laborPrice) || 0), 0)) }} 元</span>
        </div>
      </div>

      <!-- 总计部分 -->
      <div class="total-section">
        <div class="total-item">
          <span class="total-label">合计：</span>
          <span class="total-value">{{ formatDecimal(totalAmount) }} 元</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="ProductDetail">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getProduct } from "@/api/mat/product";
import { listProductMaterialRelation } from "@/api/mat/productMaterialRelation";
import { getMaterial } from "@/api/mat/material";
import { listProductAddition } from "@/api/mat/productAddition";
import { listProductLabor } from "@/api/mat/productLabor";
import { listByIds, listOss } from "@/api/system/oss";
import { formatDecimal } from '@/utils/gear';
import { Document } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();

const productDetail = ref({});
const loading = ref(true);
const materialLoading = ref(false);
const additionLoading = ref(false);
const pdfFiles = ref([]);
const pdfUrlFiles = ref([]);

// 材料明细数据
const productMaterialRelationList = ref([]);

// 产品附加属性数据
const productAdditionList = ref([]);
const productLaborList = ref([]);

// 计算主材、辅材和工本
const mainMaterials = computed(() => {
  // 主材（材料类型为2）
  return productMaterialRelationList.value
    .filter(item => item.material && item.material.materialType === 2)
    .map(item => ({
      materialName: item.material.materialName,
      spec: item.material.spec,
      quantity: item.materialNum + (item.material.unit || ''),
      price: item.material.unitPrice || 0,
      subtotal: (item.materialNum * (item.material.unitPrice || 0)) || 0
    }));
});

const auxiliaryMaterials = computed(() => {
  // 辅材（材料类型为1）
  return productMaterialRelationList.value
    .filter(item => item.material && item.material.materialType === 1)
    .map(item => ({
      materialName: item.material.materialName,
      spec: item.material.spec,
      quantity: item.materialNum + (item.material.unit || ''),
      price: item.material.unitPrice || 0,
      subtotal: (item.materialNum * (item.material.unitPrice || 0)) || 0
    }));
});

const laborMaterials = computed(() => {
  // 工价（材料类型为3）
  return productMaterialRelationList.value
    .filter(item => item.material && item.material.materialType === 3)
    .map(item => ({
      materialName: item.material.materialName,
      spec: item.material.spec,
      quantity: item.materialNum + (item.material.unit || ''),
      price: item.material.unitPrice || 0,
      subtotal: (item.materialNum * (item.material.unitPrice || 0)) || 0
    }));
});

// 计算总金额
const totalAmount = computed(() => {
  const mainTotal = mainMaterials.value.reduce((sum, item) => sum + item.subtotal, 0);
  const auxiliaryTotal = auxiliaryMaterials.value.reduce((sum, item) => sum + item.subtotal, 0);
  const laborTotal = laborMaterials.value.reduce((sum, item) => sum + item.subtotal, 0);
  const manualLaborTotal = productLaborList.value.reduce((sum, item) => {
    const price = item && item.laborPrice !== undefined && item.laborPrice !== null ? Number(item.laborPrice) : 0;
    return sum + (Number.isFinite(price) ? price : 0);
  }, 0);
  return mainTotal + auxiliaryTotal + laborTotal + manualLaborTotal;
});

const isOssIdList = (val) => {
  if (val === null || val === undefined) return false;
  const str = String(val).trim();
  return /^[0-9]+(,[0-9]+)*$/.test(str);
};

const pdfDisplayList = computed(() => {
  const raw = String(productDetail.value.productPdfs || '').trim();
  if (!raw) return [];
  if (isOssIdList(raw)) return pdfFiles.value;
  return pdfUrlFiles.value;
});

// 获取产品详情
function getProductDetail() {
  const productId = route.params.id;
  if (productId) {
    loading.value = true;
    getProduct(productId).then(response => {
      productDetail.value = response.data;
      loading.value = false;
      resolvePdfFiles();
      // 获取材料明细
      getMaterialDetail(productId);
      // 获取产品附加属性
      getProductAddition(productId);
      getProductLabor(productId);
    }).catch(error => {
      console.error('获取产品详情失败:', error);
      loading.value = false;
    });
  }
}

// 获取产品附加属性
function getProductAddition(productId) {
  additionLoading.value = true;
  listProductAddition({ productId }).then(response => {
    productAdditionList.value = response.rows || [];
    additionLoading.value = false;
  }).catch(error => {
    console.error('获取产品附加属性失败:', error);
    additionLoading.value = false;
  });
}

// 获取材料明细
function getMaterialDetail(productId) {
  materialLoading.value = true;
  listProductMaterialRelation({ productId }).then(response => {
    const relations = response.rows;
    // 为每个配方项获取物料详细信息，包括物料类型
    const promises = relations.map(item => {
      return getMaterial(item.materialId).then(materialResponse => {
        item.material = materialResponse.data;
        return item;
      });
    });
    return Promise.all(promises);
  }).then(relationsWithMaterial => {
    productMaterialRelationList.value = relationsWithMaterial;
    materialLoading.value = false;
  }).catch(error => {
    console.error('获取材料明细失败:', error);
    materialLoading.value = false;
  });
}

function getProductLabor(productId) {
  listProductLabor({ productId }).then(response => {
    productLaborList.value = response.rows || [];
  }).catch(() => {
    productLaborList.value = [];
  });
}

function resolvePdfFiles() {
  const raw = String(productDetail.value.productPdfs || '').trim();
  if (!raw) {
    pdfFiles.value = [];
    pdfUrlFiles.value = [];
    return;
  }
  if (isOssIdList(raw)) {
    pdfUrlFiles.value = [];
    listByIds(raw).then(res => {
      const list = res.data || [];
      pdfFiles.value = list.map(oss => ({
        name: oss.originalName || oss.fileName || String(oss.ossId),
        url: oss.url,
        ossId: oss.ossId
      }));
    }).catch(() => {
      pdfFiles.value = [];
    });
    return;
  }

  pdfFiles.value = [];
  const urls = raw.split(',').map(s => String(s).trim()).filter(Boolean);
  Promise.all(urls.map((url) =>
    listOss({ url, pageNum: 1, pageSize: 1 })
      .then(r => (r && r.rows && r.rows[0]) ? r.rows[0] : null)
      .catch(() => null)
  )).then(rows => {
    pdfUrlFiles.value = urls.map((url, index) => {
      const row = rows[index];
      return {
        name: (row && (row.originalName || row.fileName)) || getFileName(url),
        url: (row && row.url) || url,
        ossId: row && row.ossId
      };
    });
  }).catch(() => {
    pdfUrlFiles.value = urls.map(url => ({ name: getFileName(url), url }));
  });
}

// 返回列表
function handleBack() {
  router.back();
}

// 获取文件名
function getFileName(url) {
  if (!url) return '';
  return url.substring(url.lastIndexOf('/') + 1);
}

// 预览PDF
function previewPdf(pdf) {
  if (!pdf || !pdf.url) return;
  window.open(pdf.url, '_blank');
}

// 下载PDF
function downloadPdf(pdf) {
  if (!pdf || !pdf.url) return;
  const link = document.createElement('a');
  link.href = pdf.url;
  link.download = pdf.name || getFileName(pdf.url);
  link.click();
}

onMounted(() => {
  getProductDetail();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  font-weight: bold;
  min-width: 80px;
}

.product-images {
  margin-top: 20px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.product-pdfs {
  margin-top: 20px;
}

.pdf-list {
  margin-top: 10px;
}

.pdf-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

.pdf-icon {
  font-size: 24px;
  color: #409eff;
}

.pdf-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.material-section {
  margin: 20px 0;
}

.section-title {
  background-color: #f5f7fa;
  padding: 10px;
  border-left: 4px solid #409eff;
  margin-bottom: 10px;
}

.section-summary {
  text-align: right;
  padding: 10px;
  background-color: #f9f9f9;
  border-top: 1px solid #e4e7ed;
  margin-top: -1px;
  font-weight: bold;
}

.total-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f0f9eb;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
}

.total-item {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.total-label {
  font-size: 18px;
  font-weight: bold;
}

.total-value {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}
</style>
