"use strict";
const common_vendor = require("../../common/vendor.js");
const common_http = require("../../common/http.js");
function formatDate(d) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}
const _sfc_main = {
  data() {
    const now = /* @__PURE__ */ new Date();
    const start = new Date(now.getFullYear(), now.getMonth(), 1);
    return {
      startDate: formatDate(start),
      endDate: formatDate(now),
      mode: "sale",
      dim: "customer",
      rows: [],
      total: { sales: 0, cost: 0, profit: 0 }
    };
  },
  onLoad(query) {
    try {
      const m = query && query.mode;
      const d = query && query.dim;
      if (m)
        this.mode = m;
      if (d)
        this.dim = d;
    } catch (e) {
    }
    this.refresh();
  },
  computed: {
    profitRate() {
      const { sales, profit } = this.total;
      if (!sales)
        return "0.00%";
      return (profit / sales * 100).toFixed(2) + "%";
    }
  },
  methods: {
    fmt(n) {
      return Number(n || 0).toFixed(2);
    },
    setMode(m) {
      this.mode = m;
      this.dim = m === "sale" ? "customer" : m === "purchase" ? "supplier" : m === "inventory" ? "qty" : "ar";
      this.refresh();
    },
    onStartChange(e) {
      this.startDate = e.detail.value;
      this.refresh();
    },
    onEndChange(e) {
      this.endDate = e.detail.value;
      this.refresh();
    },
    async refresh() {
      if (this.mode === "sale") {
        if (this.dim === "customer")
          return this.loadByCustomer();
        if (this.dim === "product")
          return this.loadByProduct();
      }
      if (this.mode === "purchase") {
        if (this.dim === "supplier")
          return this.loadPurchaseBySupplier();
        if (this.dim === "product")
          return this.loadPurchaseByProduct();
      }
      if (this.mode === "inventory") {
        if (this.dim === "qty")
          return this.loadInventoryByQty();
        if (this.dim === "amount")
          return this.loadInventoryByAmount();
      }
      if (this.mode === "arap") {
        if (this.dim === "ar")
          return this.loadAR();
        if (this.dim === "ap")
          return this.loadAP();
      }
    },
    async loadByCustomer() {
      try {
        const listResp = await common_http.get("/api/orders", { biz: "sale", type: "out", startDate: this.startDate, endDate: this.endDate, page: 1, size: 200 });
        const list = listResp && (listResp.list || listResp) || [];
        const map = /* @__PURE__ */ new Map();
        let totalSales = 0;
        for (const it of list) {
          const name = it.customerName || "未知客户";
          const amount = Number(it.amount || 0);
          totalSales += amount;
          if (!map.has(name))
            map.set(name, { name, sales: 0, cost: 0, profit: 0 });
          const row = map.get(name);
          row.sales += amount;
        }
        const rows = Array.from(map.values()).map((r) => ({ ...r, profit: r.sales - r.cost }));
        const total = { sales: totalSales, cost: 0, profit: totalSales };
        this.rows = rows;
        this.total = total;
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadByProduct() {
      try {
        const listResp = await common_http.get("/api/orders", { biz: "sale", type: "out", startDate: this.startDate, endDate: this.endDate, page: 1, size: 200 });
        const list = listResp && (listResp.list || listResp) || [];
        const agg = /* @__PURE__ */ new Map();
        for (const it of list) {
          try {
            const d = await common_http.get(`/api/orders/${it.id}`);
            const items = d && d.items || [];
            for (const m of items) {
              const key = String(m.productId || m.name);
              if (!agg.has(key))
                agg.set(key, { name: m.name || "#" + key, sales: 0, cost: 0, profit: 0 });
              const row = agg.get(key);
              const sales = Number(m.amount || 0);
              row.sales += sales;
            }
          } catch (_) {
          }
        }
        const rows = Array.from(agg.values()).map((r) => ({ ...r, profit: r.sales - r.cost }));
        const totalSales = rows.reduce((s, r) => s + r.sales, 0);
        this.rows = rows;
        this.total = { sales: totalSales, cost: 0, profit: totalSales };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadPurchaseBySupplier() {
      try {
        const listResp = await common_http.get("/api/purchase-orders", { startDate: this.startDate, endDate: this.endDate, page: 1, size: 200 });
        const list = listResp && (listResp.list || listResp) || [];
        const map = /* @__PURE__ */ new Map();
        let total = 0;
        for (const it of list) {
          const name = it.supplierName || "未知供应商";
          const amount = Number(it.amount || 0);
          total += amount;
          if (!map.has(name))
            map.set(name, { name, sales: 0, cost: 0, profit: 0 });
          const row = map.get(name);
          row.sales += amount;
        }
        this.rows = Array.from(map.values());
        this.total = { sales: total, cost: 0, profit: 0 };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadPurchaseByProduct() {
      try {
        const listResp = await common_http.get("/api/purchase-orders", { startDate: this.startDate, endDate: this.endDate, page: 1, size: 200 });
        const list = listResp && (listResp.list || listResp) || [];
        const agg = /* @__PURE__ */ new Map();
        for (const it of list) {
          try {
            const d = await common_http.get(`/api/purchase-orders/${it.id}`);
            for (const m of (d == null ? void 0 : d.items) || []) {
              const key = String(m.productId || m.name);
              if (!agg.has(key))
                agg.set(key, { name: m.name || "#" + key, sales: 0, cost: 0, profit: 0 });
              const row = agg.get(key);
              row.sales += Number(m.amount || 0);
            }
          } catch (_) {
          }
        }
        const rows = Array.from(agg.values());
        const total = rows.reduce((s, r) => s + r.sales, 0);
        this.rows = rows;
        this.total = { sales: total, cost: 0, profit: 0 };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadInventoryByQty() {
      try {
        const resp = await common_http.get("/api/inventories/logs", { startDate: this.startDate, endDate: this.endDate, page: 1, size: 200 });
        const list = resp && (resp.list || resp) || [];
        const map = /* @__PURE__ */ new Map();
        let totalQty = 0;
        for (const it of list) {
          const key = it.productId || "未知";
          if (!map.has(key))
            map.set(key, { name: String(key), sales: 0, cost: 0, profit: 0 });
          const row = map.get(key);
          const q = Number(it.qtyDelta || 0);
          row.sales += q;
          totalQty += q;
        }
        this.rows = Array.from(map.values());
        this.total = { sales: totalQty, cost: 0, profit: 0 };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadInventoryByAmount() {
      try {
        const resp = await common_http.get("/api/inventories/logs", { startDate: this.startDate, endDate: this.endDate, page: 1, size: 200 });
        const list = resp && (resp.list || resp) || [];
        const map = /* @__PURE__ */ new Map();
        let totalAmt = 0;
        for (const it of list) {
          const key = it.productId || "未知";
          if (!map.has(key))
            map.set(key, { name: String(key), sales: 0, cost: 0, profit: 0 });
          const row = map.get(key);
          const a = Number(it.amount || it.amountDelta || 0);
          row.sales += a;
          totalAmt += a;
        }
        this.rows = Array.from(map.values());
        this.total = { sales: totalAmt, cost: 0, profit: 0 };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadAR() {
      try {
        const res = await common_http.get("/api/customers", { page: 1, size: 100, debtOnly: false });
        const list = Array.isArray(res == null ? void 0 : res.list) ? res.list : Array.isArray(res) ? res : [];
        const rows = list.map((c) => ({ name: c.name, sales: Number(c.receivable || 0), cost: 0, profit: 0 }));
        const total = rows.reduce((s, r) => s + r.sales, 0);
        this.rows = rows;
        this.total = { sales: total, cost: 0, profit: 0 };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    },
    async loadAP() {
      try {
        const res = await common_http.get("/api/suppliers", { page: 1, size: 100 });
        const list = Array.isArray(res == null ? void 0 : res.list) ? res.list : Array.isArray(res) ? res : [];
        const rows = list.map((s) => ({ name: s.name, sales: Number(s.apPayable || 0), cost: 0, profit: 0 }));
        const total = rows.reduce((s, r) => s + r.sales, 0);
        this.rows = rows;
        this.total = { sales: total, cost: 0, profit: 0 };
      } catch (e) {
        common_vendor.index.showToast({ title: "加载失败", icon: "none" });
      }
    }
  }
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: $data.mode === "sale" ? 1 : "",
    b: common_vendor.o(($event) => $options.setMode("sale")),
    c: $data.mode === "purchase" ? 1 : "",
    d: common_vendor.o(($event) => $options.setMode("purchase")),
    e: $data.mode === "inventory" ? 1 : "",
    f: common_vendor.o(($event) => $options.setMode("inventory")),
    g: $data.mode === "arap" ? 1 : "",
    h: common_vendor.o(($event) => $options.setMode("arap")),
    i: common_vendor.t($data.startDate),
    j: $data.startDate,
    k: common_vendor.o((...args) => $options.onStartChange && $options.onStartChange(...args)),
    l: common_vendor.t($data.endDate),
    m: $data.endDate,
    n: common_vendor.o((...args) => $options.onEndChange && $options.onEndChange(...args)),
    o: $data.mode === "sale"
  }, $data.mode === "sale" ? {
    p: $data.dim === "customer" ? 1 : "",
    q: common_vendor.o(($event) => {
      $data.dim = "customer";
      $options.refresh();
    }),
    r: $data.dim === "product" ? 1 : "",
    s: common_vendor.o(($event) => {
      $data.dim = "product";
      $options.refresh();
    })
  } : $data.mode === "purchase" ? {
    v: $data.dim === "supplier" ? 1 : "",
    w: common_vendor.o(($event) => {
      $data.dim = "supplier";
      $options.refresh();
    }),
    x: $data.dim === "product" ? 1 : "",
    y: common_vendor.o(($event) => {
      $data.dim = "product";
      $options.refresh();
    })
  } : $data.mode === "inventory" ? {
    A: $data.dim === "qty" ? 1 : "",
    B: common_vendor.o(($event) => {
      $data.dim = "qty";
      $options.refresh();
    }),
    C: $data.dim === "amount" ? 1 : "",
    D: common_vendor.o(($event) => {
      $data.dim = "amount";
      $options.refresh();
    })
  } : $data.mode === "arap" ? {
    F: $data.dim === "ar" ? 1 : "",
    G: common_vendor.o(($event) => {
      $data.dim = "ar";
      $options.refresh();
    }),
    H: $data.dim === "ap" ? 1 : "",
    I: common_vendor.o(($event) => {
      $data.dim = "ap";
      $options.refresh();
    })
  } : {}, {
    t: $data.mode === "purchase",
    z: $data.mode === "inventory",
    E: $data.mode === "arap",
    J: common_vendor.t($options.fmt($data.total.sales)),
    K: common_vendor.t($options.fmt($data.total.cost)),
    L: common_vendor.t($options.fmt($data.total.profit)),
    M: common_vendor.t($options.profitRate),
    N: common_vendor.f($data.rows, (row, idx, i0) => {
      return common_vendor.e({
        a: row.avatar
      }, row.avatar ? {
        b: row.avatar
      } : {}, {
        c: common_vendor.t(row.name),
        d: common_vendor.t($options.fmt(row.sales)),
        e: common_vendor.t($options.fmt(row.cost)),
        f: common_vendor.t($options.fmt(row.profit)),
        g: idx
      });
    })
  });
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render]]);
wx.createPage(MiniProgramPage);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/report/index.js.map
