<template>
  <div class="app-container supply-dashboard-page">
    <div class="page-header">
      <h2><i class="el-icon-s-opportunity"></i> 供应商交付分析</h2>
      <p class="page-desc">分析各供应商针对特定产品的交付表现</p>
    </div>

    <!-- 搜索框 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-search"></i> 查询产品交付分析</span>
      </div>
      <el-form :inline="true" class="form-inline">
        <el-form-item label="产品编码">
          <el-input
            v-model="inputProductCode"
            placeholder="请输入产品编码（如:20220606J0100MR4）"
            style="width: 300px"
            @keyup.enter.native="fetchDeliveryData(inputProductCode)"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchDeliveryData(inputProductCode)"
            >分析交付</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格数据 -->
    <el-card v-loading="loading" class="box-card">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-document"></i> 交付详情表格</span>
        <el-button
          v-if="deliveryDetails.length > 0"
          style="float: right; padding: 3px 0"
          type="text"
          @click="exportData"
        >
          导出数据
        </el-button>
      </div>

      <el-table
        v-if="deliveryDetails.length > 0"
        :data="deliveryDetails"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="供应商名称" label="供应商名称" min-width="220" />
        <el-table-column prop="履约状态" label="履约状态" width="110" align="center">
          <template slot-scope="scope">
            <el-tag :type="statusType(scope.row.履约状态)" size="mini">
              {{ scope.row.履约状态 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="风险等级" label="风险等级" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="riskType(scope.row.风险等级)" size="mini">
              {{ scope.row.风险等级 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="交付分数" label="交付分数" width="110" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.交付分数, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="D1_准时率" label="准时率" width="100" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.D1_准时率, 2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="D4_满足率" label="满足率" width="100" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.D4_满足率, 2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="计划数量" label="计划数量" width="120" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.计划数量, 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="实际入库数量" label="实际入库数量" width="130" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.实际入库数量, 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="未满足数量" label="未满足数量" width="120" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.未满足数量, 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="匹配行数" label="匹配行数" width="100" align="right" />
        <el-table-column prop="准时行数" label="准时行数" width="100" align="right" />
        <el-table-column prop="延迟行数" label="延迟行数" width="100" align="right" />
        <el-table-column prop="D2_平均偏差" label="平均偏差(天)" width="130" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.D2_平均偏差, 2) }}
          </template>
        </el-table-column>
        <el-table-column prop="D3_最长延迟" label="最长延迟(天)" width="130" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.D3_最长延迟, 2) }}
          </template>
        </el-table-column>      </el-table>

      <div v-else class="no-data">
        <p v-if="error" class="error">{{ error }}</p>
        <p v-else>暂无交付数据，请输入产品编码进行分析</p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { saveAs } from "file-saver";
import { getProductDetails } from "@/api/supply";

export default {
  name: "SupplyDeliveryAnalysis",
  data() {
    return {
      inputProductCode: "",
      deliveryDetails: [],
      loading: false,
      error: "",
    };
  },
  created() {
    // 如果有传入的 productCode，则自动触发分析
    if (this.$route.query.productCode) {
      this.inputProductCode = this.$route.query.productCode;
      this.fetchDeliveryData(this.inputProductCode);
    }
  },
  methods: {
    // 获取交付数据
    async fetchDeliveryData(code) {
      if (!code) {
        this.$modal.msgError("请输入产品编码");
        return;
      }

      this.loading = true;
      this.error = "";

      try {
        // 使用项目标准的request方式调用API
        const response = await getProductDetails(code);

        // Flask API通常直接返回数据，没有code字段
        if (response && response.delivery_details !== undefined) {
          this.deliveryDetails = this.enrichDeliveryDetails(response.delivery_details || []);
          this.$modal.msgSuccess("交付分析完成");
        } else {
          // 尝试其他可能的数据结构
          if (response && Array.isArray(response)) {
            this.deliveryDetails = this.enrichDeliveryDetails(response || []);
            this.$modal.msgSuccess("交付分析完成");
          } else {
            this.error = "获取交付数据失败，API响应格式不匹配";
            this.$modal.msgError(this.error);
          }
        }
      } catch (err) {
        console.error("获取交付数据失败:", err);
        this.error = err.message || "获取交付数据失败";
        this.$modal.msgError(this.error);
      } finally {
        this.loading = false;
      }
    },

    enrichDeliveryDetails(rows) {
      const list = Array.isArray(rows) ? rows : [];
      return list.map((row) => {
        const planQty = this.firstNumber(row.计划数量, row.planQty);
        const receiptQty = this.firstNumber(row.实际入库数量, row.receiptQty);
        const onTimeRate = this.firstNumber(row.D1_准时率, row.准时率, row.onTimeRate);
        const fulfillmentRate = this.firstNumber(row.D4_满足率, row.满足率, row.fulfillmentRate);
        const maxDelayDays = this.firstNumber(row.D3_最长延迟, row.最长延迟, row.maxDelayDays);
        const shortageQty = Math.max(0, planQty - receiptQty);
        return {
          ...row,
          计划数量: planQty,
          实际入库数量: receiptQty,
          未满足数量: this.firstNumber(row.未满足数量, row.shortageQty, shortageQty),
          匹配行数: this.firstNumber(row.匹配行数, row.matchedLines),
          准时行数: this.firstNumber(row.准时行数, row.onTimeLines),
          延迟行数: this.firstNumber(row.延迟行数, row.delayedLines),
          履约状态: row.履约状态 || row.deliveryStatus || this.deliveryStatus(onTimeRate, fulfillmentRate, maxDelayDays),
          风险等级: row.风险等级 || row.riskLevel || this.riskLevel(onTimeRate, fulfillmentRate, maxDelayDays),
        };
      });
    },

    firstNumber(...values) {
      for (const value of values) {
        const number = Number(value);
        if (Number.isFinite(number)) return number;
      }
      return 0;
    },

    formatNumber(value, digits = 2) {
      return this.firstNumber(value).toLocaleString("zh-CN", {
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
      });
    },

    deliveryStatus(onTimeRate, fulfillmentRate, maxDelayDays) {
      if (fulfillmentRate < 80 || maxDelayDays >= 30) return "严重异常";
      if (fulfillmentRate < 95) return "数量不足";
      if (onTimeRate < 80 || maxDelayDays > 0) return "存在延迟";
      return "正常";
    },

    riskLevel(onTimeRate, fulfillmentRate, maxDelayDays) {
      if (fulfillmentRate < 80 || onTimeRate < 60 || maxDelayDays >= 30) return "高";
      if (fulfillmentRate < 95 || onTimeRate < 90 || maxDelayDays > 0) return "中";
      return "低";
    },

    statusType(status) {
      if (status === "正常") return "success";
      if (status === "存在延迟" || status === "数量不足") return "warning";
      return "danger";
    },

    riskType(level) {
      if (level === "低") return "success";
      if (level === "中") return "warning";
      return "danger";
    },
    // 导出数据
    exportData() {
      if (!this.deliveryDetails || this.deliveryDetails.length === 0) {
        this.$modal.msgError("暂无数据可导出");
        return;
      }

      // 创建CSV内容
      const header = [
        "供应商名称",
        "履约状态",
        "风险等级",
        "交付分数",
        "准时率(%)",
        "满足率(%)",
        "计划数量",
        "实际入库数量",
        "未满足数量",
        "匹配行数",
        "准时行数",
        "延迟行数",
        "平均偏差(天)",
        "最长延迟(天)",
      ].join(",");
      const csvContent = [
        header,
        ...this.deliveryDetails.map((row) =>
          [
            `"${row.供应商名称}"`,
            row.履约状态,
            row.风险等级,
            this.formatNumber(row.交付分数, 2),
            this.formatNumber(row.D1_准时率, 2),
            this.formatNumber(row.D4_满足率, 2),
            row.计划数量,
            row.实际入库数量,
            row.未满足数量,
            row.匹配行数,
            row.准时行数,
            row.延迟行数,
            this.formatNumber(row.D2_平均偏差, 2),
            this.formatNumber(row.D3_最长延迟, 2),
          ].join(",")
        ),
      ].join("\n");

      // 下载文件
      const blob = new Blob(["\ufeff" + csvContent], {
        type: "text/csv;charset=utf-8;",
      });
      saveAs(blob, `供应商交付分析_${new Date().getTime()}.csv`);
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;

  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;

    i {
      margin-right: 8px;
      color: #409eff;
    }
  }

  .page-desc {
    color: #909399;
    font-size: 14px;
    margin: 0;
  }
}

.box-card {
  margin-bottom: 20px;
}

.form-inline {
  display: flex;
  align-items: center;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;

  .error {
    color: #f56c6c;
  }
}

::v-deep .el-card__header {
  font-weight: bold;
}
</style>
