<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <link rel="icon" href="{{ site_branding.favicon_url }}">
  <title>{{ page_title }} - {{ site_branding.browser_title }}</title>
  <link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
  <style>
    * { box-sizing:border-box; }
    body { margin:0; font-family:Arial, "Microsoft YaHei", sans-serif; background:#f5f5f7; color:#222; }
    a { text-decoration:none; color:inherit; }
    .topbar { background:#111; color:#fff; padding:14px 24px; border-bottom:1px solid rgba(255,255,255,.06); }
    .topbar-inner { width:1200px; max-width:calc(100vw - 48px); margin:0 auto; display:flex; justify-content:space-between; align-items:center; gap:24px; }
    .topbar-brand a { color:#fff; font-size:20px; font-weight:800; }
    .topbar-links { display:flex; gap:18px; align-items:center; flex-wrap:wrap; justify-content:flex-end; }
    .topbar-links a, .topbar-links span { color:#f3f3f3; font-size:14px; white-space:nowrap; }
    .topbar-user { display:inline-flex; align-items:center; gap:8px; padding:6px 12px 6px 8px; background:rgba(255,255,255,.08); border-radius:999px; }
    .topbar-avatar { width:28px; height:28px; border-radius:50%; object-fit:cover; background:#eee; }
    .page { width:1200px; max-width:calc(100vw - 48px); margin:24px auto; }
    .panel { background:#fff; border-radius:18px; padding:24px; box-shadow:0 2px 10px rgba(0,0,0,.05); margin-bottom:18px; }
    .flash { padding:12px 14px; border-radius:12px; margin-bottom:14px; font-size:14px; line-height:1.8; }
    .flash.success { background:#ecfdf5; color:#166534; }
    .flash.error { background:#fef2f2; color:#991b1b; }
    .row { margin-bottom:16px; }
    label { display:block; font-weight:700; margin-bottom:8px; }
    input[type="text"], input[type="number"], select {
      width:100%; box-sizing:border-box; padding:10px 12px; border:1px solid #ddd; border-radius:10px; font-size:14px;
    }
    .btn-row { display:flex; gap:10px; flex-wrap:wrap; }
    .btn { display:inline-flex; align-items:center; justify-content:center; padding:10px 16px; border-radius:10px; background:#111; color:#fff; border:none; font-size:14px; cursor:pointer; }
    .btn-light { background:#efefef; color:#222; }
    .thumb { width:160px; height:160px; object-fit:cover; border-radius:14px; border:1px solid #ddd; background:#fafafa; display:block; margin-bottom:12px; }
    .muted { color:#666; font-size:14px; line-height:1.8; }
    #editor { height: 360px; background:#fff; }
    .ql-toolbar.ql-snow { border-radius:12px 12px 0 0; }
    .ql-container.ql-snow { border-radius:0 0 12px 12px; font-size:15px; line-height:1.8; }
    .editor-size-box {
      display:inline-flex;
      align-items:center;
      gap:8px;
      margin:0 10px;
      padding:0 10px;
      height:32px;
      border:1px solid #ddd;
      border-radius:8px;
      background:#fff;
      vertical-align:middle;
    }
    .editor-size-aa {
      font-size:18px;
      font-weight:700;
      color:#444;
      line-height:1;
      user-select:none;
    }
    .editor-size-input {
      width:72px;
      border:none;
      outline:none;
      font-size:14px;
      color:#222;
      background:transparent;
    }
    .editor-size-input::placeholder {
      color:#999;
    }
  </style>
</head>
<body>
  <div class="topbar">
    <div class="topbar-inner">
      <div class="topbar-brand"><a href="/">{{ site_branding.site_name }}</a></div>
      <div class="topbar-links">
        <a href="/merchant/dashboard">商家后台</a>
        <a href="/merchant/products">商品管理</a>
        <a href="/account">用户主页</a>
        <span class="topbar-user">
          <img class="topbar-avatar" src="{{ session.get('biz_avatar_url') or '/uploads/avatars/default-avatar.png' }}" alt="头像">
          <span>你好，{{ session.get("biz_display_name") }}</span>
        </span>
        <a href="/logout">退出</a>
      </div>
    </div>
  </div>

  <div class="page">
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        {% for category, message in messages %}
          <div class="flash {{ category }}">{{ message }}</div>
        {% endfor %}
      {% endif %}
    {% endwith %}

    <div class="panel">
      <h1 style="margin:0 0 8px; font-size:30px; font-weight:800;">{{ page_title }}</h1>
      <div class="muted" style="margin-bottom:18px;">当前店铺：{{ merchant_ctx.shop_name }}</div>

      <form id="productForm" method="post" enctype="multipart/form-data">
        <div class="row">
          <label>商品名称</label>
          <input type="text" name="product_name" value="{{ (form_data.get('product_name') if form_data else (product.product_name if product else '')) }}">
        </div>

        <div class="row">
          <label>商品分类</label>
          {% set selected_category = form_data.get('category_id') if form_data else ((product.category_id|string) if product and product.category_id else '') %}
          <select name="category_id">
            <option value="">未分类</option>
            {% for c in categories %}
              <option value="{{ c.category_id }}" {% if selected_category == c.category_id|string %}selected{% endif %}>{{ c.category_name }}</option>
            {% endfor %}
          </select>
        </div>

        <div class="row">
          <label>价格</label>
          <input type="number" step="0.01" min="0" name="price" value="{{ (form_data.get('price') if form_data else (product.price if product else '')) }}">
        </div>

        <div class="row">
          <label>库存</label>
          <input type="number" step="1" min="0" name="stock" value="{{ (form_data.get('stock') if form_data else (product.stock if product else '')) }}">
        </div>

        <div class="row">
          <label>商品说明</label>
          <div id="editor"></div>
          <input type="hidden" name="description" id="descriptionField">
          <textarea id="descriptionInitial" style="display:none;">{{ (form_data.get('description') if form_data else (product.description if product and product.description else '')) }}</textarea>
          <div class="muted" style="margin-top:8px;">这里直接编辑正式商品说明。工具栏支持标题、字号、加粗、列表、引用、代码块、对齐和图片上传。</div>
        </div>

        <div class="row">
          <label>商品主图</label>
          {% if product and product.cover_url %}
            <img class="thumb" src="{{ product.cover_url }}" alt="当前主图">
          {% endif %}
          <input type="file" name="cover_image" accept=".png,.jpg,.jpeg,.webp,image/png,image/jpeg,image/webp">
        </div>

        <div class="btn-row">
          <button class="btn" type="submit">保存</button>
          <a class="btn btn-light" href="{{ url_for('merchant_products') }}">返回商品管理</a>
        </div>
      </form>
    </div>
  </div>

  <script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
  <script>
    var Parchment = Quill.import('parchment');
    var CustomSizeStyle = new Parchment.Attributor.Style('size', 'font-size', {
      scope: Parchment.Scope.INLINE
    });
    Quill.register(CustomSizeStyle, true);

    var quill = new Quill('#editor', {
      theme: 'snow',
      modules: {
        toolbar: {
          container: [
            [{ 'header': [1, 2, 3, false] }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'align': [] }],
            ['blockquote', 'code-block', 'link', 'image'],
            ['clean']
          ],
          handlers: {
            image: function() {
              var input = document.createElement('input');
              input.setAttribute('type', 'file');
              input.setAttribute('accept', 'image/*');
              input.click();

              input.onchange = async function() {
                var file = input.files[0];
                if (!file) return;

                var maxBytes = 2 * 1024 * 1024;
                if (file.size > maxBytes) {
                  alert('说明图片文件过大，当前限制为 2 MB。');
                  input.value = '';
                  return;
                }

                var fd = new FormData();
                fd.append('image', file);

                try {
                  var resp = await fetch('/merchant/editor/upload-image', {
                    method: 'POST',
                    body: fd
                  });

                  var data = await resp.json().catch(function() {
                    return {};
                  });

                  var imageUrl =
                    (data && data.data && data.data.url) ||
                    (data && data.url) ||
                    '';

                  var errorMsg =
                    (data && (data.message || data.error)) ||
                    '图片上传失败';

                  if (!resp.ok || !imageUrl || (typeof data.errno !== 'undefined' && data.errno !== 0) || data.ok === false) {
                    alert(errorMsg);
                    return;
                  }

                  var range = quill.getSelection(true);
                  quill.insertEmbed(range.index, 'image', imageUrl);
                  quill.setSelection(range.index + 1);
                } catch (e) {
                  alert('图片上传失败，请稍后重试');
                }
              }
            }
          }
        }
      }
    });


    function installFontSizeInput(quill) {
      var toolbar = quill.getModule('toolbar').container;
      var sizeBox = document.createElement('span');
      sizeBox.className = 'editor-size-box';
      sizeBox.innerHTML = '<span class="editor-size-aa">Aa</span><input class="editor-size-input" type="number" min="12" max="96" step="1" value="16" placeholder="字号(px)" title="字号（px）">';

      var toolbarChildren = toolbar.children;
      if (toolbarChildren.length >= 2) {
        toolbar.insertBefore(sizeBox, toolbarChildren[1].nextSibling);
      } else {
        toolbar.appendChild(sizeBox);
      }

      var input = sizeBox.querySelector('input');

      function normalizeSize(value) {
        var n = parseInt(String(value || '').replace(/[^0-9]/g, ''), 10);
        if (!Number.isFinite(n)) n = 16;
        if (n < 12) n = 12;
        if (n > 96) n = 96;
        return n;
      }

      function syncSizeFromSelection() {
        var range = quill.getSelection();
        if (!range) return;

        var fmt = quill.getFormat(range);
        var size = fmt.size;
        if (Array.isArray(size)) size = size[0];

        var match = String(size || '').match(/(\d+)/);
        input.value = match ? match[1] : 16;
      }

      function applyTypedSize() {
        var size = normalizeSize(input.value);
        input.value = size;

        quill.focus();
        var range = quill.getSelection(true);
        if (!range) {
          quill.setSelection(quill.getLength(), 0, 'user');
        }
        quill.format('size', size + 'px', 'user');
      }

      input.addEventListener('change', applyTypedSize);
      input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          applyTypedSize();
        }
      });

      quill.on('selection-change', syncSizeFromSelection);
      syncSizeFromSelection();
    }


    installFontSizeInput(quill);

    var initialHtml = document.getElementById('descriptionInitial').value || '';
    if (initialHtml) {
      quill.clipboard.dangerouslyPasteHTML(initialHtml);
    }

    document.getElementById('productForm').addEventListener('submit', function () {
      document.getElementById('descriptionField').value = quill.root.innerHTML;
    });
  </script>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const maxBytes = 2 * 1024 * 1024;

  document.querySelectorAll("form").forEach(function (form) {
    const fileInput = form.querySelector('input[type="file"][name="cover_image"]');
    if (!fileInput) return;

    form.addEventListener("submit", function (e) {
      const file = fileInput.files && fileInput.files[0];
      if (!file) return;

      if (file.size > maxBytes) {
        e.preventDefault();
        alert("商品主图文件过大，当前限制为 2 MB。");
        fileInput.value = "";
      }
    });
  });
});
</script>

</body>
</html>
