(function quoteTemplateConstraintModule(global) {
  "use strict";

  global.quoteTemplateConstraintForCurrentProduct = function quoteTemplateConstraintForCurrentProduct() {
    const matchedEntry = quoteCatalogEntry() || quoteCatalogFindProduct(val("quoteProduct"));
    if (!matchedEntry) return null;
    return { ...quoteCatalogLegacyProfile(matchedEntry), product: matchedEntry.name };
  };

  global.setActiveQuoteTemplate = function setActiveQuoteTemplate(category, templateName) {
    const templates = industryCategories[category] || [];
    if (!templates.includes(templateName)) return false;
    if (currentIndustryCategory() !== category) activateIndustryQuoteProfile(category, templateName);
    const template = productTemplates[templateName] || productTemplates["通用加工"];
    Object.assign(state.settings, {
      industryCategory: category,
      factoryType: templateName,
      productType: templateName,
      defaultMaterial: template.material
    });
    return true;
  };

  global.renderQuoteTemplateOptions = function renderQuoteTemplateOptions() {
    const select = document.getElementById("quoteTemplate");
    if (!select) return;
    const templates = currentCategoryTemplates();
    const constraint = quoteTemplateConstraintForCurrentProduct();
    const compatibleTemplate = constraint?.category === currentIndustryCategory() && templates.includes(constraint.template)
      ? constraint.template
      : "";
    select.innerHTML = templates.map(name =>
      `<option value="${name}" ${compatibleTemplate && name !== compatibleTemplate ? "disabled" : ""}>${name}${compatibleTemplate && name === compatibleTemplate ? "（当前产品）" : ""}</option>`
    ).join("");
    select.value = compatibleTemplate || (templates.includes(state.settings.factoryType) ? state.settings.factoryType : templates[0]);
    if (compatibleTemplate) setActiveQuoteTemplate(constraint.category, compatibleTemplate);
    const help = document.getElementById("quoteTemplateHelp");
    if (help) help.textContent = compatibleTemplate
      ? `已按“${constraint.product}”自动匹配“${compatibleTemplate}”；其他模板与当前产品不一致，已禁用。`
      : constraint
        ? `“${constraint.product}”属于“${constraint.category}”，请先切换到对应行业价格表。`
        : "自定义产品可手动选择成本模板；选择目录产品后会自动匹配并禁用不适用模板。";
  };

  global.applyProductTemplate = function applyProductTemplate() {
    const constraint = quoteTemplateConstraintForCurrentProduct();
    if (constraint) {
      if (constraint.category !== currentIndustryCategory()) {
        renderQuoteTemplateOptions();
        setQuoteIndustryWarning(`产品“${constraint.product}”属于“${constraint.category}”，当前价格表不适用。`, constraint.category, constraint.template);
        return;
      }
      setActiveQuoteTemplate(constraint.category, constraint.template);
      renderQuoteTemplateOptions();
      saveState();
      renderIndustryQuoteCostFields();
      renderQuoteMaterialCostCheck(true);
      setQuoteIndustryWarning("");
      return;
    }
    quoteCatalogProductId = "";
    renderQuoteProductPicker();
    renderQuoteProductConfigurator();
    const name = val("quoteTemplate") || state.settings.factoryType || "包装彩盒";
    const template = productTemplates[name] || productTemplates["通用加工"];
    Object.assign(state.settings, {
      industryCategory: categoryForTemplate(name),
      factoryType: name,
      productType: name,
      defaultMaterial: template.material
    });
    saveState();
    renderIndustryCategories();
    renderQuoteTemplateOptions();
    applyTemplateToQuoteFields(name, true);
    renderIndustryQuoteCostFields();
    renderQuoteMaterialCostCheck(true);
    setQuoteIndustryWarning("");
  };
})(window);
