using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using SkiaSharp;
using ZXing;
using ZXing.Common;
using ZXing.SkiaSharp;
using 常用工具集.Base;

namespace 常用工具集.ViewModel._03图片相关
{
    public class 二维码条形码解析ViewModel : ViewModelBase
    {
        public string ImagePath { get; set; } = "";
        public string Result { get; set; } = "";

        public DelegateCommand SelectPathCmd { get; set; }
        public DelegateCommand GetResultCmd { get; set; }

        public 二维码条形码解析ViewModel()
        {
            SelectPathCmd = new DelegateCommand(SelectPathCmdFunc);
            GetResultCmd = new DelegateCommand(GetResultCmdFunc);
        }



        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="obj"></param>
        private async void SelectPathCmdFunc(object obj)
        {  
            var sp = GlobalValues.StorageProvider;
            if (sp is null) return;
            FilePickerOpenOptions options = new FilePickerOpenOptions();
            options.Title = "选择二维码图片";
            options.AllowMultiple = false;
            options.FileTypeFilter = [
                  FilePickerFileTypes.ImageAll
                 ];
            var result = await sp.OpenFilePickerAsync(options);
            if (result == null || result.Count == 0) return;
            ImagePath = result.FirstOrDefault()?.Path.LocalPath;
        }


        private void GetResultCmdFunc(object obj)
        {
            try
            {
                MultiFormatReader formatReader = new MultiFormatReader();
                Dictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
                hints.Add(DecodeHintType.CHARACTER_SET, Encoding.UTF8.HeaderName);
                // 优化精度 
                hints.Add(DecodeHintType.TRY_HARDER, true);
                // 复杂模式，开启PURE_BARCODE模式 
                hints.Add(DecodeHintType.PURE_BARCODE, true);
                formatReader.Hints = hints;
                SKBitmap bitmap = SKBitmap.Decode(ImagePath);
                LuminanceSource source = new SKBitmapLuminanceSource(bitmap);
                Result result = formatReader.decode(new BinaryBitmap(new HybridBinarizer(source)));
                if (null == result)
                {
                    result = formatReader.decode(new BinaryBitmap(new GlobalHistogramBinarizer(source)));
                }
                bitmap.Dispose();
                if (result != null)
                {
                    Result = result.Text; // 显示解析出的一维码文本内容
                }
                else
                {
                    Result = "未能解析条码";
                }
            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }
        }
    }
}
