<template>
  <div class="app-container">
    <div class="page-header">
      <h2><i class="el-icon-s-finance"></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="fetchPaymentData(inputProductCode)"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchPaymentData(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="paymentDetails.length > 0"
          style="float: right; padding: 3px 0"
          type="text"
          @click="exportData"
        >
          导出数据
        </el-button>
      </div>

      <el-table
        v-if="paymentDetails.length > 0"
        :data="paymentDetails"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="供应商名称" label="供应商名称" min-width="220" show-overflow-tooltip />
        <el-table-column prop="供应商代码" label="供应商代码" width="120" />
        <el-table-column prop="维护状态" label="账期状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.维护状态 === '已维护' ? 'success' : 'danger'" size="mini">
              {{ scope.row.维护状态 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="结算期限" label="结算期限" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.结算期限 || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="账期天数" label="账期天数" width="110" align="right">
          <template slot-scope="scope">
            {{ Number(scope.row.账期天数 || 0).toLocaleString("zh-CN") }}天
          </template>
        </el-table-column>
        <el-table-column prop="账期等级" label="账期等级" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="termLevelType(scope.row.账期等级)" size="mini">
              {{ scope.row.账期等级 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="账期分数" label="账期分数" width="120" align="right">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.账期分数, 2) }}
          </template>
        </el-table-column>
      </el-table>

      <div v-else class="no-data">
        <p v-if="error" class="error">{{ error }}</p>
        <p v-else>{{ emptyText }}</p>
      </div>
    </el-card>
  </div>
</template>

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

export default {
  name: "SupplyPaymentAnalysis",
  data() {
    return {
      inputProductCode: "",
      paymentDetails: [],
      loading: false,
      error: "",
      emptyText: "暂无账期数据，请输入产品编码进行分析",
    };
  },
  created() {
    if (this.$route.query.productCode) {
      this.inputProductCode = this.$route.query.productCode;
      this.fetchPaymentData(this.inputProductCode);
    }
  },
  methods: {
    async fetchPaymentData(code) {
      if (!code) {
        this.$modal.msgError("请输入产品编码");
        return;
      }

      this.loading = true;
      this.error = "";
      this.emptyText = "正在查询账期数据...";

      try {
        const response = await getProductDetails(code);
        const details =
          response && response.payment_details !== undefined
            ? response.payment_details
            : response && response.data && response.data.payment_details !== undefined
              ? response.data.payment_details
              : Array.isArray(response)
                ? response
                : [];

        if (Array.isArray(details)) {
          this.paymentDetails = this.normalizePaymentDetails(details);
          if (this.paymentDetails.length > 0) {
            this.emptyText = "";
            this.$modal.msgSuccess("账期分析完成");
          } else {
            this.emptyText = `产品编码 ${code} 未匹配到账期数据，请确认该产品是否有关联供应商账期记录`;
            this.$modal.msgWarning(this.emptyText);
          }
        } else {
          this.paymentDetails = [];
          this.error = "获取账期数据失败，API响应格式不匹配";
          this.$modal.msgError(this.error);
        }
      } catch (err) {
        console.error("获取账期数据失败:", err);
        this.paymentDetails = [];
        this.error = err.message || "获取账期数据失败";
        this.$modal.msgError(this.error);
      } finally {
        this.loading = false;
      }
    },

    normalizePaymentDetails(rows) {
      return (Array.isArray(rows) ? rows : []).map((row) => {
        const termDays = Number(row.账期天数 || row.termDays || 0);
        const status = row.维护状态 || row.termStatus || (termDays > 0 ? "已维护" : "缺少账期");
        const level = row.账期等级 || row.termLevel || this.termLevel(termDays);

        return {
          ...row,
          供应商代码: row.供应商代码 || row.supplierCode || "-",
          供应商名称: row.供应商名称 || row.supplierName || "-",
          结算期限: row.结算期限 || row.paymentTerms || "",
          账期天数: termDays,
          账期分数: Number(row.账期分数 || row.termScore || 0),
          账期等级: this.normalizeMissingText(level),
          维护状态: this.normalizeMissingText(status),
        };
      });
    },

    normalizeMissingText(value) {
      return value === "未维护" ? "缺少账期" : value;
    },

    formatNumber(value, digits = 2) {
      const number = Number(value);
      return Number.isFinite(number) ? number.toFixed(digits) : "0.00";
    },

    termLevel(days) {
      if (days >= 90) return "优秀";
      if (days >= 60) return "良好";
      if (days >= 30) return "一般";
      if (days > 0) return "偏短";
      return "缺少账期";
    },

    termLevelType(level) {
      if (level === "优秀" || level === "良好") return "success";
      if (level === "一般") return "warning";
      return "danger";
    },

    exportData() {
      if (!this.paymentDetails || this.paymentDetails.length === 0) {
        this.$modal.msgError("暂无数据可导出");
        return;
      }

      const header = ["供应商名称", "供应商代码", "账期状态", "结算期限", "账期天数", "账期等级", "账期分数"].join(",");
      const csvContent = [
        header,
        ...this.paymentDetails.map((row) =>
          [
            `"${row.供应商名称}"`,
            row.供应商代码,
            row.维护状态,
            `"${row.结算期限 || ""}"`,
            row.账期天数,
            row.账期等级,
            this.formatNumber(row.账期分数, 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>
