using HandyControl.Collections;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Input;
using WCS.BLL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel.MatBaseInfo;
using 智慧物流软件系统.Api;
using 智慧物流软件系统.Tool;
using 智慧物流软件系统.Views.Controls;

namespace 智慧物流软件系统.ViewModel
{
    public class MatBaseInoScanGenarateMatInfoViewModel : BindableBase
    {
        public MatBaseInoScanGenarateMatInfoViewModel()
        {

        }

        #region Property
        private string matCode;
        public string MatCode
        {
            get => matCode; set
            {
                SetProperty(ref matCode, value);

                App.Current.Dispatcher.Invoke(() =>
                {
                    FilterItems(value);
                });

                if (matCode.Length >= 8
                    || matCodes.Where(t => t.MatCode == matCode).Any() )
                {
                    GetMatBaseInfoRequest();
                }
            }
        }
        public ManualObservableCollection<DataModel> Items { get; set; } = new();
        private List<DataModel> matCodes = new List<DataModel>();
        private void FilterItems(string key)
        {
            //至少输入三个字符 避免删除或输入时界面变卡
            if (string.IsNullOrEmpty(key) || key.Length < 3)
            {
                Items.Clear();
                return;
            }
            key = key.ToUpper();
            Items.CanNotify = false;
            Items.Clear();
            foreach (var matCode in matCodes)
            {
                if (matCode.MatCode.ToUpper().Contains(key))
                {
                    Items.Add(matCode);
                }
            }
            Items.CanNotify = true;
        }
        public class DataModel
        {
            public string MatCode { get; set; }
        }

        public void InitMatCode()
        {
            //调用接口更新！
            Task.Run(() =>
            {
                var body = new GetMatCodeListRequest()
                {
                    IsFromBaseData = true,
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                };

                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<List<string>>>(LocalFile.Config.ApiIpHost + "matBaseInfo/getMatCodeList", body, "POST");
                if (Result != null && Result.Data != null && Result.Data.Count() > 0)
                {
                    matCodes = Result.Data.Select(t => new DataModel()
                    {
                        MatCode = t
                    }).ToList();
                }
            });
        }

        private string matName;
        public string MatName
        {
            get => matName;
            set { SetProperty(ref matName, value); }
        }

        private string matSpec;
        public string MatSpec
        {
            get => matSpec;
            set { SetProperty(ref matSpec, value); }
        }

        private int matQty;
        public int MatQty
        {
            get => matQty;
            set { SetProperty(ref matQty, value); }
        }


        private int totalPan = 1;
        public int TotalPan
        {
            get => totalPan; set
            {
                SetProperty(ref totalPan, value);
                UpdateMatSN();
            }
        }


        private string matBatch;
        public string MatBatch
        {
            get => matBatch;
            set
            {
                SetProperty(ref matBatch, value);
                UpdateMatSN();
            }
        }


        private string reservedCode;
        public string ReservedCode
        {
            get => reservedCode; set
            {
                SetProperty(ref reservedCode, value);
                UpdateMatSN();
            }
        }

        private string changelessCode;
        public string ChangelessCode
        {
            get => changelessCode; set
            {
                SetProperty(ref changelessCode, value);
                UpdateMatSN();
            }
        }

        private List<string> matSNs = new List<string>();

        public List<string> MatSNs { get => matSNs; set { SetProperty(ref matSNs, value); } }


        private string matSNsStr;
        public string MatSNsStr
        {
            get => matSNsStr;
            set { SetProperty(ref matSNsStr, value); }
        }


        public MatBaseInfoModel MatBaseInfo { get; set; } = null;
        public List<MatInfoModel> MatInfos { get; set; } = null;
        #endregion

        #region Command
        //public ICommand BtnGenerateCommand { get => new DelegateCommand(BtnGenerate); }
        //public void BtnGenerate()
        //{
        //    #region 调用接口获取物料 MatBaseInfo
        //    try
        //    {
        //        var body = new JinChuanCommitMatInfoRequest()
        //        {
        //            MatId = MatBaseInfo.Id,
        //            CurrentSerilNumber = MatBaseInfo.SerialNumber,
        //            MatBatch = MatBatch,
        //            MatQty = MatQty,
        //            TotalPan = totalPan,
        //            CurrentMatSn = MatSNs,
        //            DeviceType = LocalFile.Config.DeviceType,
        //            UserName = LocalStatic.CurrentUser,
        //        };
        //        var Result = ApiHelp.GetDataFromHttp<ResponseBase<List<MatInfoModel>>>(LocalFile.Config.ApiIpHost + "matBaseInfo/JinChuanCommitMatInfo", body, "POST");
        //        if (Result != null && Result.Code == 200 && Result.Data != null)
        //        {
        //            MatInfos = Result.Data;
        //            MatSNs = MatSNs + " 已生成";
        //            Growl.Success("生成成功！");
        //        }
        //        else
        //        {
        //            if (Result != null && !string.IsNullOrEmpty(Result.Message))
        //            {
        //                HandyControl.Controls.MessageBox.Show(Result.Message);
        //            }
        //            else
        //                HandyControl.Controls.MessageBox.Show("操作失败，请重试！");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Growl.Warning(ex.Message);
        //    }
        //    #endregion
        //}


        public ICommand BtnGeneratePrintCommand { get => new DelegateCommand(BtnGeneratePrint); }
        public void BtnGeneratePrint()
        {
            #region 调用接口获取物料 MatBaseInfo
            try
            {
                if (MatQty == 0)
                {
                    HandyControl.Controls.MessageBox.Show("数量不能为0！");
                    return;
                }

                var body = new JinChuanCommitMatInfoRequest()
                {
                    MatId = MatBaseInfo.Id,
                    CurrentSerilNumber = MatBaseInfo.SerialNumber,
                    MatBatch = MatBatch,
                    MatQty = MatQty,
                    TotalPan = TotalPan,
                    CurrentMatSn = MatSNs,
                    DeviceType = LocalFile.Config.DeviceType,
                    UserName = LocalStatic.CurrentUser,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseBase<List<MatInfoModel>>>(LocalFile.Config.ApiIpHost + "matBaseInfo/JinChuanCommitMatInfo", body, "POST");
                if (Result != null && Result.Code == 200 && Result.Data != null && Result.Data.Count != 0)
                {
                    MatInfos = Result.Data;
                    MatSNsStr = MatSNsStr + " 已生成";
                    Task.Run(() =>
                    {
                        ProcessDialog process = null;
                        Dialog dia = null;
                        var totalCount = MatInfos.Count;
                        int currentCount = 0;

                        App.Current.Dispatcher.Invoke(() =>
                        {
                            process = new ProcessDialog();
                            dia = Dialog.Show(process);
                        });

                        foreach (var matInfo in MatInfos)
                        {
                            PrintTender.PrintTag(new PrintClass()
                            {
                                MatSn = matInfo.MatSN,
                                MatName = matInfo.MatName,
                                MatCode = matInfo.MatCode,
                                MatBatch = matInfo.MatBatch,
                                MatQty = matInfo.MatQty.ToString(),
                                MatSpec = matInfo.MatSpec,
                            });
                            currentCount++;
                            if (process != null)
                                process.viewModel.ProcessValue = Convert.ToInt32(((decimal)currentCount / totalCount) * 100);
                        }

                        App.Current.Dispatcher.Invoke(() =>
                        {
                            dia.Close();
                            dia.Collapse();
                        });

                        #region 回传后端打印成功
                        try
                        {
                            var body = new PrintedMatInfoRequest()
                            {
                                PrintedMatInfoIds = MatInfos.Select(t => t.Id).ToList(),
                                UserName = LocalStatic.CurrentUser,
                                DeviceType = LocalFile.Config.DeviceType,
                            };
                            var Result11 = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "matBaseInfo/printedMatInfo", body, "POST");
                            if (Result11 != null && Result11.Code == 200)
                            {
                                MatSNsStr = MatSNsStr + " 已打印";
                                //回传成功
                            }
                            else
                            {
                                //回传失败
                                Logs.Write("回传“打印成功”失败");
                            }
                        }
                        catch (Exception ex)
                        {
                            Logs.Write("回传“打印成功”失败：" + ex.Message);
                        }
                        #endregion
                    });
                }
                else
                {
                    if (Result != null && !string.IsNullOrEmpty(Result.Message))
                    {
                        HandyControl.Controls.MessageBox.Show(Result.Message);
                    }
                    else
                        HandyControl.Controls.MessageBox.Show("操作失败，请重试！");
                }
            }
            catch (Exception ex)
            {
                Growl.Warning(ex.Message);
            }
            #endregion
        }
        #endregion

        public void ParsingBarcode(string input)
        {
            #region 解析扫码文本
            // 提取第一个字段  CPN物料编码
            //string firstField = Regex.Match(input, @"^[0-9,a-z,A-Z, ]{9}{").Value;
            string firstField = Regex.Match(input, LocalFile.Config.RegexMatCode).Value;


            try
            {
                // 第二个字段 数量  
                //string secondField = Regex.Match(input, @"{[1-9][0]{2,5}[ ]{").Value;
                string secondField = Regex.Match(input, LocalFile.Config.RegexMatQty).Value;
                MatQty = Convert.ToInt32(secondField.Replace("{", "").Replace(" ", ""));

                input = input.Replace(secondField, string.Empty);
            }
            catch
            {
                Growl.Warning("数量解析失败！请重试或手动输入");
            }

            // 第三个字段 批次
            //string thirdField = Regex.Match(input, @"{[0-9, ]{5}{").Value;
            string thirdField = Regex.Match(input, LocalFile.Config.RegexMatBatch).Value;
            MatBatch = thirdField.Replace("{", "").Replace(" ", ""); ;
            #endregion

            MatCode = firstField.Replace("{", "").Replace(" ", "");
            //GetMatBaseInfoRequest();
        }

        public void GetMatBaseInfoRequest()
        {
            //调用接口获取物料信息
            #region 调用接口获取物料 MatBaseInfo
            try
            {
                var body = new JinChuanGenerateMatInfoRequest()
                {
                    MatCode = MatCode,
                    DeviceType = LocalFile.Config.DeviceType,
                    UserName = LocalStatic.CurrentUser,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseBase<MatBaseInfoModel>>(LocalFile.Config.ApiIpHost + "matBaseInfo/JinChuanGenerateMatInfo", body, "POST");
                if (Result != null && Result.Code == 200 && Result.Data != null)
                {
                    MatBaseInfo = Result.Data;
                    MatName = MatBaseInfo.MatName;
                    MatSpec = MatBaseInfo.MatSpec;
                    MatBaseInfo.SerialNumber++;

                    GenerateMatSN();
                }
                else
                {
                    if (Result == null && !string.IsNullOrEmpty(Result.Message))
                    {
                        HandyControl.Controls.MessageBox.Show(Result.Message);
                    }
                    else
                        HandyControl.Controls.MessageBox.Show("接口调用失败，请重试！");
                }
            }
            catch (Exception ex)
            {
                Growl.Warning(ex.Message);
            }
            #endregion
        }

        public void UpdateMatSN()
        {
            try
            {
                if (MatSNs != null && MatSNs.Count > 0 && totalPan >= 1)
                {
                    MatSNs.Clear();
                    for (int i = 0; i < TotalPan; i++)
                    {
                        var newMatSn = ChangelessCode + MatCode + ReservedCode + MatBatch + (MatBaseInfo.SerialNumber + i).ToString("000");
                        MatSNs.Add(newMatSn);
                    }

                    if (MatSNs == null || MatSNs.Count == 0)
                    {
                        MatSNsStr = string.Empty;
                    }
                    else if (MatSNs.Count == 1)
                    {
                        MatSNsStr = MatSNs[0].ToString();
                    }
                    else
                    {
                        MatSNsStr = MatSNs[0].ToString() + "~\r\n" + MatSNs[MatSNs.Count - 1].ToString();
                    }
                }
            }
            catch
            {
            }

        }

        public void GenerateMatSN()
        {
            MatSNs.Clear();
            for (int i = 0; i < TotalPan; i++)
            {
                var newMatSn = ChangelessCode + MatCode + ReservedCode + MatBatch + (MatBaseInfo.SerialNumber + i).ToString("000");
                MatSNs.Add(newMatSn);
            }

            if (MatSNs == null || MatSNs.Count == 0)
            {
                MatSNsStr = string.Empty;
            }
            else if (MatSNs.Count == 1)
            {
                MatSNsStr = MatSNs[0].ToString();
            }
            else
            {
                MatSNsStr = MatSNs[0].ToString() + "\r\n~" + MatSNs[MatSNs.Count - 1].ToString();
            }
        }
    }
}
