/**
 * 定价工具控制层（全局变量版本，不使用import）
 */
window.PricingToolController = class {
  #pricingData = null;
  #targetSellingPriceInput = null;

  async init(targetInput) {
    this.#targetSellingPriceInput = targetInput;
    window.PricingToolView.createModal();
    
    await new Promise((resolve) => {
      const checkElements = setInterval(() => {
        if (window.PricingToolView.elements) {
          clearInterval(checkElements);
          resolve();
        }
      }, 100);
    });

    this.#pricingData = await window.PricingStorage.getPricingData();
    window.PricingToolView.renderForm(this.#pricingData);
    this.#bindEvents();
  }

  #bindEvents() {
    const { elements } = window.PricingToolView;
    if (!elements) return;

    elements.closeBtn.addEventListener("click", () => window.PricingToolView.hideModal());
    elements.overlay.addEventListener("click", (e) => {
      if (e.target === elements.overlay) window.PricingToolView.hideModal();
    });

    elements.fillBtn.addEventListener("click", () => {
      if (this.#targetSellingPriceInput && this.#pricingData.recommendedPrice) {
        this.#targetSellingPriceInput.value = this.#pricingData.recommendedPrice.toFixed(2);
        this.#targetSellingPriceInput.dispatchEvent(new Event("input", { bubbles: true }));
      }
      window.PricingToolView.hideModal();
    });

    const calcInputs = [
      elements.costInput,
      elements.discountInput,
      elements.platformCommissionInput,
      elements.allianceCommissionInput,
      elements.transactionFeeInput,
      elements.coinMarketingInput,
      elements.activityDiscountInput,
      elements.profitRatioInput
    ];
    calcInputs.forEach((input) => {
      input.addEventListener("change", async () => {
        this.#updatePricingFromInput();
        this.#calculateRecommendedPrice();
        window.PricingToolView.renderForm(this.#pricingData);
        await window.PricingStorage.savePricingData(this.#pricingData);
      });
    });

    elements.recommendedPriceInput.addEventListener("blur", async () => {
      this.#updatePricingFromInput();
      this.#calculateProfitRatio();
      window.PricingToolView.renderForm(this.#pricingData);
      await window.PricingStorage.savePricingData(this.#pricingData);
    });

    elements.currencyRadios.forEach((radio) => {
      radio.addEventListener("change", async () => {
        this.#pricingData.currency = radio.value;
        window.PricingToolView.updateExchangeRate(this.#pricingData.currency, this.#pricingData.exchangeRate);
        await window.PricingStorage.savePricingData(this.#pricingData);
      });
    });
  }

  #updatePricingFromInput() {
    const { elements } = window.PricingToolView;
    if (!elements) return;

    this.#pricingData.cost = parseFloat(elements.costInput.value) || 0;
    this.#pricingData.discount = parseFloat(elements.discountInput.value) || 0;//店铺优惠
    this.#pricingData.platformCommission = parseFloat(elements.platformCommissionInput.value) || 0;//平台佣金
    this.#pricingData.allianceCommission = parseFloat(elements.allianceCommissionInput.value) || 0;//联盟佣金
    this.#pricingData.transactionFee = parseFloat(elements.transactionFeeInput.value) || 0;//交易服务费
    this.#pricingData.coinMarketing = parseFloat(elements.coinMarketingInput.value) || 0;//金币营销
    this.#pricingData.activityDiscount = parseFloat(elements.activityDiscountInput.value) || 0;//活动折扣
    this.#pricingData.profitRatio = parseFloat(elements.profitRatioInput.value) || 0;//利润成本比
    this.#pricingData.recommendedPrice = parseFloat(elements.recommendedPriceInput.value) || 0;//推荐售价

    Object.keys(this.#pricingData).forEach((key) => {
      if (typeof this.#pricingData[key] === "number") {
        this.#pricingData[key] = parseFloat(this.#pricingData[key].toFixed(2));
      }
    });
  }

  #calculateRecommendedPrice() {
    const {
      cost,
      discount,
      profitRatio,
      platformCommission,
      allianceCommission,
      transactionFee,
      coinMarketing,
      activityDiscount
    } = this.#pricingData;

    const totalRatio =
      platformCommission + allianceCommission + transactionFee + coinMarketing;
    const denominator = 1 - totalRatio / 100;
    if (denominator <= 0) {
      alert("总比例不能超过100%，请调整各比例值！");
      return;
    }

    const recommendedPrice = (cost * (1 + profitRatio / 100))/ (1 - activityDiscount / 100) / denominator + discount;
    this.#pricingData.recommendedPrice = parseFloat(recommendedPrice.toFixed(2));
  }

  #calculateProfitRatio() {
    const {
      cost,
      discount,
      recommendedPrice,
      platformCommission,
      allianceCommission,
      transactionFee,
      coinMarketing,
      activityDiscount
    } = this.#pricingData;

    if (cost <= 0) {
      alert("产品成本不能为0，请输入有效成本！");
      this.#pricingData.profitRatio = 0;
      return;
    }

    activityDiscount//活动折扣 
    const totalRatio =
       platformCommission + allianceCommission + transactionFee + coinMarketing ;
    const profit = (recommendedPrice - discount) * (1 - activityDiscount/100) * (1 - totalRatio/100) -  cost;
    const profitRatio = (profit / cost) * 100;
    this.#pricingData.profitRatio = parseFloat(profitRatio.toFixed(2));
  }

  showModal() {
    window.PricingToolView.showModal();
  }
};