using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Masuit.Tools;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Khd.Core.Wpf.TaskForm.Inventory
{
    /// <summary>
    /// InventoryTaskEditForm.xaml 的交互逻辑
    /// </summary>
    public partial class InventoryTaskEditForm : Window
    {
        private readonly Microsoft.Extensions.Hosting.IHost _host;
        private readonly long _materialId;
        private readonly string _containerNo;
        private readonly string _materialName;
        private readonly InventoryTaskForm _inventoryTaskForm;
        private readonly string _locationCode;
        private Dictionary<string, string> _barCodeList;
        public InventoryTaskEditForm(Microsoft.Extensions.Hosting.IHost _host, long materialId, string containerNo, string materialName, string locationCode, InventoryTaskForm inventoryTaskForm)
        {
            InitializeComponent();
            this._host = _host;
            this._materialId = materialId;
            this._containerNo = containerNo;
            this._materialName = materialName;
            this._inventoryTaskForm = inventoryTaskForm;
            this._locationCode = locationCode;
            _barCodeList = new Dictionary<string, string>();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.ContainerNo.Text = _containerNo;
                this.MaterialSpec.Text = _materialName;
                using var scope = this._host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var wmsRawStocks = dbContext.WmsRawStock.Where(t => t.palletInfoCode == _containerNo)
                    .WhereIf(_materialId != 0, t => t.materialId == _materialId)
                    .ToList();
                if (wmsRawStocks.Count == 0)
                {
                    this.BarCode.Text = "空";
                }
                else
                {
                    //这里把条码号用换行符分开
                    this.BarCode.Text = string.Join("\n", wmsRawStocks.Select(t => t.instockBatch));
                    this.Count.Text = string.Join("\n", wmsRawStocks.Select(t => t.totalAmount.ToString()));
                }
            }
            catch
            {
                HandyControl.Controls.MessageBox.Error("加载数据失败，请重试");
                this.Close();
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            _inventoryTaskForm.ShowDialog();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void ScanButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using var scope = this._host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == this.NewBarCode.Text);
                if (mesBaseBarcodeInfo != null)
                {
                    try
                    {
                        _barCodeList.Add(mesBaseBarcodeInfo.barcodeInfo, this.NewCount.Text);
                        this.BarCodeList.Text += mesBaseBarcodeInfo.barcodeInfo + "\n";
                        this.CountList.Text += this.NewCount.Text + "\n";
                        this.NewBarCode.Text = "";
                    }
                    catch
                    {
                        MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show("该条码已经添加过，是否更新该条码？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                        if (messageBoxResult == MessageBoxResult.OK)
                        {
                            string[] barCodes = this.BarCodeList.Text.Split('\n');
                            string[] counts = this.CountList.Text.Split('\n');
                            for (int i = 0; i < barCodes.Length; i++)
                            {
                                if (this.BarCodeList.Text == barCodes[i])
                                {
                                    counts[i] = this.NewCount.Text;
                                    this.CountList.Text = string.Join("\n", counts);
                                    this.BarCodeList.Text = string.Join("\n", barCodes);
                                    this._barCodeList[mesBaseBarcodeInfo.barcodeInfo] = this.NewCount.Text;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    HandyControl.Controls.MessageBox.Show("条码不存在，请重新扫码");
                    this.NewBarCode.Text = "";
                }
            }
            catch
            {

            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            List<string> newList = this.BarCodeList.Text.Split('\n').ToList();
            newList.RemoveAll(t => string.IsNullOrEmpty(t));
            List<string> list = this.BarCode.Text.Split('\n').ToList();
            list.RemoveAll(t => string.IsNullOrEmpty(t));
            List<string> countList = CountList.Text.Split("\n").ToList();
            StringBuilder addStr = new();
            List<string> addList = newList.Where(t => !list.Contains(t)).ToList();
            if (addList.Count > 0)
            {
                addStr.AppendLine("新增条码：");
                addStr.AppendLine(string.Join(",", addList));
            }
            StringBuilder removeStr = new();
            List<string> removeList = list.Where(t => !newList.Contains(t)).ToList();
            if (removeList.Count > 0)
            {
                removeStr.AppendLine("删除条码：");
                removeStr.AppendLine(string.Join(",", removeList));
            }
            if (addStr.Length > 0 || removeStr.Length > 0)
            {
                MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Show(addStr.ToString() + "\n" + removeStr.ToString(), "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                if (messageBoxResult == MessageBoxResult.OK)
                {
                    using var scope = this._host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    if (addList.Count > 0)
                    {
                        var wmsRawStocks = dbContext.WmsRawStock.Where(t => addList.Contains(t.instockBatch)).ToList();
                        List<string> rawList = wmsRawStocks.Select(t => t.instockBatch).ToList();
                        addList.RemoveAll(t => rawList.Contains(t));
                        if (wmsRawStocks.Count > 0)
                        {
                            string waring = string.Join(",\n", wmsRawStocks.Select(t => new
                            {
                                message = t.locationCode + ":" + t.instockBatch
                            }));
                            MessageBoxResult result = HandyControl.Controls.MessageBox.Show("条码已经在其他料箱中" + waring + "确认移动到当前料箱吗？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                            if (result == MessageBoxResult.OK)
                            {
                                foreach (var wmsRawStock in wmsRawStocks)
                                {
                                    wmsRawStock.palletInfoCode = _containerNo;
                                    wmsRawStock.locationCode = _locationCode;
                                    wmsRawStock.updateBy = "WCS";
                                    wmsRawStock.updateDate = DateTime.Now;
                                }
                                dbContext.UpdateRange(wmsRawStocks);
                            }
                            else
                            {
                                return;
                            }
                        }
                        if (addList.Count > 0)
                        {
                            List<WmsRawStock> newWmsRawStocks = dbContext.WmsRawStock
                                .WhereIf(_materialId != 0, t => t.materialId == _materialId)
                                .Where(t => t.palletInfoCode == _containerNo).ToList();
                            var mesBaseBarcodeInfos = dbContext.MesBaseBarcodeInfo.Where(t => addList.Contains(t.barcodeInfo)).ToList();
                            for (int i = 0; i < addList.Count; i++)
                            {
                                var barcode = addList[i];
                                var count = countList[i];
                                var mesBaseBarcodeInfo = mesBaseBarcodeInfos.FirstOrDefault(t => t.barcodeInfo == barcode);
                                if (mesBaseBarcodeInfo != null)
                                {
                                    if (wmsRawStocks.Where(t => t.materialId == mesBaseBarcodeInfo.materialId).Any())
                                    {
                                        WmsRawStock wmsRawStock = wmsRawStocks.First(t => t.materialId == mesBaseBarcodeInfo.materialId);
                                        wmsRawStock.totalAmount = decimal.Parse(count);
                                    }
                                    else
                                    {
                                        newWmsRawStocks.Add(new WmsRawStock
                                        {
                                            palletInfoCode = _containerNo,
                                            materialId = mesBaseBarcodeInfo.materialId,
                                            instockBatch = mesBaseBarcodeInfo.barcodeInfo,
                                            safeFlag = mesBaseBarcodeInfo.safeFlag,
                                            stockType = "1",
                                            activeFlag = "1",
                                            supplierId = mesBaseBarcodeInfo.manufacturerId,
                                            completeFlag = "1",
                                            frozenAmount = 0,
                                            instockDate = DateTime.Now,
                                            qualityStatus = "0",
                                            rawStockId = Global.SnowId.NextId(),
                                            occupyAmount = 0,
                                            totalAmount = mesBaseBarcodeInfo.batchFlag == "1" ? decimal.Parse(count) : 1,
                                            warehouseFloor = 5,
                                            warehouseId = 512,
                                            saleOrderId = mesBaseBarcodeInfo.saleOrderId == null ? 0 : mesBaseBarcodeInfo.saleOrderId,
                                            locationCode = _locationCode,
                                            createBy = "WCS",
                                            createDate = DateTime.Now,
                                            updateBy = "WCS",
                                            updateDate = DateTime.Now,
                                        });
                                    }
                                }
                                else
                                {
                                    HandyControl.Controls.MessageBox.Show($"{barcode}条码信息不存在，无法入库");
                                    return;
                                }
                            }
                            if (newWmsRawStocks.Count > 0)
                            {
                                WcsTask? wcsTask = dbContext.WcsTask.Where(t => t.containerNo == _containerNo).FirstOrDefault();
                                if (wcsTask != null)
                                {
                                    var wmsInventoryCheckDetails = dbContext.WmsInventoryCheckDetail
                                        .Where(t => t.InventoryCheckId == wcsTask.orderId && t.LocationCode == wcsTask.currPointNo).ToList();
                                    List<long?> hasMaterialId = newWmsRawStocks.Select(t => t.materialId).ToList();
                                    var hasDetails = wmsInventoryCheckDetails
                                        .Where(t => hasMaterialId.Contains(t.MaterialId) && t.LocationCode == wcsTask.currPointNo)
                                        .ToList();
                                    foreach (var item in hasDetails)
                                    {
                                        var wmsRawStock = newWmsRawStocks.Where(t => t.materialId == item.ErpAmount).First();
                                        item.RealAmount = wmsRawStock.totalAmount;
                                        item.InventoryCount++;
                                        item.UpdateBy = "WCS";
                                        item.UpdateTime = DateTime.Now;
                                    }
                                    newWmsRawStocks.Where(t => !wmsInventoryCheckDetails.Select(y => y.MaterialId).Contains(t.materialId)).ToList();
                                    List<WmsInventoryCheckDetail> addDetailList = new List<WmsInventoryCheckDetail>();
                                    foreach (var item in newWmsRawStocks)
                                    {
                                        addDetailList.Add(new WmsInventoryCheckDetail
                                        {
                                            InventoryCheckDetailId = Global.SnowId.NextId(),
                                            InventoryCheckId = wcsTask.orderId,
                                            CheckStatus = "1",
                                            CreateBy = "WCS",
                                            CreateTime = DateTime.Now,
                                            StockAmount = 0,
                                            RealAmount = item.totalAmount,
                                            InventoryCount = 1,
                                            LocationCode = item.locationCode,
                                            StockId = 1,
                                            StockType = "1",
                                            MaterialId = item.materialId,
                                            ErpStatus = "0",
                                            ErpAmount = 0,
                                        });
                                    }
                                    if (addDetailList.Count > 0)
                                        dbContext.AddRange(addDetailList);
                                    if (hasDetails.Count > 0)
                                        dbContext.UpdateRange(hasDetails);
                                    dbContext.AddRange(newWmsRawStocks);
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                    if (removeList.Count > 0)
                    {

                    }
                    HandyControl.Controls.MessageBox.Show("保存成功");
                }
                else
                {
                    return;
                }
            }
            else
            {
                HandyControl.Controls.MessageBox.Show("条码未变动");
            }
            this.Close();
        }

        private void NewBarCode_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(this.NewBarCode.Text))
                {
                    using var scope = this._host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == this.NewBarCode.Text);
                    if (mesBaseBarcodeInfo != null)
                    {
                        this.NewCount.Text = mesBaseBarcodeInfo.batchFlag == "1" ? mesBaseBarcodeInfo.amount.ToString() : "1";
                        this.NewCount.IsReadOnly = mesBaseBarcodeInfo.batchFlag != "1";
                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Show("条码不存在，请重新扫码");
                        this.NewBarCode.Text = "";
                        this.NewCount.Text = string.Empty;
                    }
                }
            }
            catch
            {

            }
        }
    }
}
