using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace Ounibo.Catalog.App
{
    /// <summary>
    /// 购物车条目 (清单式批量导出; 2026-08-24 与网页版语义一致)。
    /// Qty 仅体现在 BOM 数量列, zip 中每型号只打包一份。
    /// </summary>
    public class CartItem : INotifyPropertyChanged
    {
        public string ModelCode;      // 型号编码
        public string SeriesCode;     // 系列代码
        public string SeriesName;     // 系列名
        public string StepPath;       // 包内 STEP 路径 (非标档位为 null, 打包时跳过并注明)
        public string ParamsSummary;  // 参数摘要 "key=value; ..."
        public bool IsStandard = true;// 非标档位标记 (参数化引擎, 2026-08-25)
        public Dictionary<string, object> Params;   // 参数原始值 (非标批量在线生成提交用, 二期)
        int _qty = 1;
        public int Qty { get { return _qty; } set { _qty = Math.Max(1, value); OnChanged("Qty"); } }
        public event PropertyChangedEventHandler PropertyChanged;
        void OnChanged(string n) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(n)); }
    }

    /// <summary>清单窗口 (非模态; 购物车数据在主窗口, 本窗口只是视图)。</summary>
    public class CartWindow : Window
    {
        List<CartItem> _cart;
        Action _onChanged;                    // 数量/删除/清空后回写角标
        Func<System.Threading.Tasks.Task<string>> _onDownload;   // 打包回调 (异步, 含在线生成), 返回 null 成功 / 错误提示
        DataGrid _grid;
        TextBlock _countText;

        public CartWindow(List<CartItem> cart, Action onChanged, Func<System.Threading.Tasks.Task<string>> onDownload)
        {
            _cart = cart;
            _onChanged = onChanged;
            _onDownload = onDownload;
            Title = "我的清单 My Cart";
            Width = 800; Height = 500; MinWidth = 580; MinHeight = 320;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            Owner = Application.Current != null ? Application.Current.MainWindow : null;

            var root = new DockPanel { Margin = new Thickness(10) };
            var top = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 8) };
            _countText = new TextBlock { VerticalAlignment = VerticalAlignment.Center, FontWeight = FontWeights.Bold, FontSize = 14 };
            top.Children.Add(_countText);
            DockPanel.SetDock(top, Dock.Top);
            root.Children.Add(top);

            var bottom = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 8, 0, 0) };
            var btnClear = new Button { Content = "清空 Clear All", Width = 100, Margin = new Thickness(0, 0, 8, 0) };
            btnClear.Click += (s, e) => { _cart.Clear(); Refresh(); };
            var btnDownload = new Button { Content = "下载全部 (zip + BOM)", Width = 190, Padding = new Thickness(12, 6, 12, 6), FontSize = 14 };
            btnDownload.Click += async (s, e) =>
            {
                if (_cart.Count == 0) { MessageBox.Show("清单为空, 请先加入型号", Title); return; }
                btnDownload.IsEnabled = false;
                try
                {
                    var err = await _onDownload();
                    if (err != null) MessageBox.Show(err, Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                finally { btnDownload.IsEnabled = true; }
            };
            bottom.Children.Add(btnClear); bottom.Children.Add(btnDownload);
            DockPanel.SetDock(bottom, Dock.Bottom);
            root.Children.Add(bottom);

            _grid = new DataGrid { AutoGenerateColumns = false, IsReadOnly = false, CanUserAddRows = false, CanUserDeleteRows = false };
            _grid.Columns.Add(new DataGridTextColumn { Header = "型号 Model", Binding = new System.Windows.Data.Binding("ModelCode"), Width = 150, IsReadOnly = true });
            _grid.Columns.Add(new DataGridTextColumn { Header = "系列 Series", Binding = new System.Windows.Data.Binding("SeriesName"), Width = new System.Windows.Controls.DataGridLength(1, System.Windows.Controls.DataGridLengthUnitType.Star), IsReadOnly = true });
            _grid.Columns.Add(new DataGridTextColumn { Header = "规格 Params", Binding = new System.Windows.Data.Binding("ParamsSummary"), Width = 200, IsReadOnly = true });
            _grid.Columns.Add(new DataGridTextColumn { Header = "数量 Qty", Binding = new System.Windows.Data.Binding("Qty") { UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.LostFocus }, Width = 70 });
            var delCol = new DataGridTemplateColumn { Header = "操作", Width = 80 };
            delCol.CellTemplate = MakeTemplate(item => { _cart.Remove(item); Refresh(); });
            _grid.Columns.Add(delCol);
            _grid.CellEditEnding += (s, e) => { Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(Refresh)); };
            root.Children.Add(_grid);

            Content = root;
            Refresh();
        }

        System.Windows.DataTemplate MakeTemplate(Action<CartItem> del)
        {
            var fact = new System.Windows.FrameworkElementFactory(typeof(Button));
            fact.SetValue(Button.ContentProperty, "删除");
            fact.SetValue(Button.PaddingProperty, new Thickness(6, 2, 6, 2));
            fact.SetValue(Button.FontSizeProperty, 12.0);
            fact.SetValue(Button.FocusableProperty, false);   // 不抢焦点, 避免干扰网格行交互
            fact.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) =>
            {
                var dc = ((FrameworkElement)s).DataContext as CartItem;   // 模板列取 DataContext 删行
                if (dc != null) del(dc);
                e.Handled = true;
            }));
            var tpl = new System.Windows.DataTemplate();
            tpl.VisualTree = fact;
            return tpl;
        }

        public void Refresh()
        {
            _countText.Text = "共 " + _cart.Count + " 项 | 数量只在 BOM 中体现, zip 每型号一份";
            _grid.ItemsSource = null;
            _grid.ItemsSource = _cart;
            if (_onChanged != null) _onChanged();
        }
    }
}
