using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Khd.Core.Library.Mapper;
using Khd.Core.Plc;
using Khd.Core.Plc.S7;
using Khd.Core.Wpf.Form;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Khd.Core.Wpf.TaskForm
{
    /// <summary>
    /// AddTask.xaml 的交互逻辑
    /// </summary>
    public partial class AddNewStockForm : Window
    {

        public delegate void RefreshDelegate(string containerCode);
        public static event RefreshDelegate? RefreshDelegateEvent;
 
        private readonly IHost _host;
        public AddNewStockForm(IHost host,string containerCode)
        {
            InitializeComponent();
            _host = host;
            txtInBox.Text = containerCode;
            txtInBarCode.Focus();

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           

        }

        private void UpdateBtn_Click(object sender, RoutedEventArgs e)
        {
           

        }

      

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


        //入库
        private void InRawBaseLocaltion_Click(object sender, RoutedEventArgs e)
        {
            ScanInBox();
        }


        private void ScanInBox()
        {
            try
            {

                if (!string.IsNullOrEmpty(txtInBox.Text) && !string.IsNullOrEmpty(txtInBarCode.Text))
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    if (txtInScan.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Error("请先输入数量"); return;
                    }
                    decimal amount = decimal.Parse(txtInScan.Text);
                    // 计算入库后当前总数量，仅用来提示使用
                    decimal? totalMessage = 0;
                    if (amount <= 0)
                    {
                        HandyControl.Controls.MessageBox.Error("入库数量需大于0");
                        return;
                    }
                    var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);

                    var container = dbContext.WmsBaseLocation.FirstOrDefault(t => t.containerCode == txtInBox.Text && t.warehouseId == 512);
                    List<WmsRawStock> wmsRawStocks = dbContext.WmsRawStock
                        .Where(t => txtInBarCode.Text == t.instockBatch && t.palletInfoCode== txtInBox.Text)
                        .Where(t => t.warehouseFloor == 5 && t.warehouseId == 512).ToList();
                    if (container == null)
                    {
                        txtInBox.Focus();
                        txtInBox.Text = string.Empty;
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        HandyControl.Controls.MessageBox.Error("未查询到该容器"); return;
                    }
                    if (material == null)
                    {
                        HandyControl.Controls.MessageBox.Error("未查询到该条码内容");
                        txtInBox.Text = string.Empty;
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        txtInBox.Focus();
                        return;
                    }

                    if (wmsRawStocks.Count > 0)
                    {
                        if (material.batchFlag != "1")
                        {
                            HandyControl.Controls.MessageBox.Error($"该条码已入库!料箱号为{wmsRawStocks.First().palletInfoCode},库位号为{wmsRawStocks.First().locationCode}");
                            txtInBox.Text = string.Empty;
                            txtInBarCode.Text = string.Empty;
                            txtInScan.Text = string.Empty;
                            txtInBox.Focus();
                            return;
                        }
                        else
                        {
                            WmsRawStock wmsRawStock = wmsRawStocks.First();
                            wmsRawStock.totalAmount += amount;
                            dbContext.WmsRawStock.Update(wmsRawStock);

                            var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);
                            WmsRawInstock wmsRawInstock = new WmsRawInstock()
                            {
                                taskCode = Global.SnowId.NextId().ToString(),
                                materialBarCode = mesBaseBarcodeInfo.barcodeInfo,
                                materialBatchCode = mesBaseBarcodeInfo.batchCode,
                                applyBy = "WPF",
                                applyDate = System.DateTime.Now,
                                purchaseOrderId = mesBaseBarcodeInfo.PurchaseOrderId,

                                beginTime = System.DateTime.Now,
                                endTime = DateTime.Now,
                                locationCode = container.locationCode,
                                executeStatus = "1",
                                instockAmount = amount,
                                instockType = "1",
                                materialId = material.materialId,
                                operationType = "1",
                                palletInfoCode = container.containerCode,
                                poNo = mesBaseBarcodeInfo.poNo,
                                warehouseId = 512
                            };

                            dbContext.WmsRawInstock.Add(wmsRawInstock);
                            dbContext.SaveChanges();
                            totalMessage = wmsRawStock.totalAmount;
                        }
                    }
                    else
                    {
                        var newRawStock = new WmsRawStock()
                        {
                            materialId = material.materialId,
                            supplierId = material.manufacturerId,
                            instockBatch = txtInBarCode.Text,
                            locationCode = container.locationCode,
                            stockType = "1",
                            palletInfoCode = container.containerCode,
                            totalAmount = material.batchFlag == "1" ? amount : 1,
                            activeFlag = "1",
                            occupyAmount = 0,
                            completeFlag = "1",
                            frozenAmount = 0,
                            instockDate = System.DateTime.Now,
                            rawStockId = Global.SnowId.NextId(),
                            saleOrderId = material.saleOrderId == null ? 0 : material.saleOrderId,
                            warehouseFloor = 5,
                            warehouseId = 512,
                            createBy = "扫描入库",
                            createDate = System.DateTime.Now,
                            safeFlag = material.safeFlag
                        };
                        dbContext.WmsRawStock.Add(newRawStock);

                        var mesBaseBarcodeInfo = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == txtInBarCode.Text);
                        WmsRawInstock wmsRawInstock = new WmsRawInstock()
                        {
                            taskCode = Global.SnowId.NextId().ToString(),
                            materialBarCode = mesBaseBarcodeInfo.barcodeInfo,
                            materialBatchCode = mesBaseBarcodeInfo.batchCode,
                            applyBy = "WPF",
                            applyDate = System.DateTime.Now,
                            purchaseOrderId = mesBaseBarcodeInfo.PurchaseOrderId,

                            beginTime = System.DateTime.Now,
                            endTime = DateTime.Now,
                            locationCode = container.locationCode,
                            executeStatus = "2",
                            instockAmount = amount,
                            instockType = "1",
                            materialId = material.materialId,
                            operationType = "1",
                            palletInfoCode = container.containerCode,
                            poNo = mesBaseBarcodeInfo.poNo,
                            warehouseId = 512
                        };
                        dbContext.WmsRawInstock.Add(wmsRawInstock);

                        #region 添加盘点明细
                        WmsInventoryCheck wmsInventoryCheck =  dbContext.WmsInventoryCheck.Where(x => x.CheckStatus == "1").FirstOrDefault();
                        if(wmsInventoryCheck != null)
                        {
                            WmsInventoryCheckDetail wmsInventoryCheckDetail= new WmsInventoryCheckDetail
                            {
                                InventoryCheckDetailId = Global.SnowId.NextId(),
                                InventoryCheckId = wmsInventoryCheck.InventoryCheckId,
                                CheckStatus = "2",
                                CreateBy = "WPF",
                                CreateTime = DateTime.Now,
                                StockAmount = newRawStock.totalAmount,
                                RealAmount = newRawStock.totalAmount,
                                InventoryCount = 0,
                                LocationCode = newRawStock.locationCode,
                                MaterialBatch = newRawStock.instockBatch,
                                StockId = 1,
                                StockType = "1",
                                MaterialId = newRawStock.materialId,
                                ErpStatus = "0",
                                ErpAmount = 0,
                                CheckType = "2"
                            };
                            dbContext.WmsInventoryCheckDetail.Add(wmsInventoryCheckDetail);

                        }
                        #endregion


                        dbContext.SaveChanges();
                        totalMessage = newRawStock.totalAmount;
                    }
                    txtInBox.Focus();
                    HandyControl.Controls.MessageBox.Info($"入库成功!当前库存:{totalMessage}");
                    txtInBox.Text = string.Empty;
                    txtInBarCode.Text = string.Empty;
                    txtInScan.Text = string.Empty;

                }
                else
                {
                    HandyControl.Controls.MessageBox.Error("请先扫描容器号和条码");
                   
                }
            }
            catch (Exception ex)
            {
                
                txtInBox.Text = string.Empty;
                txtInBarCode.Text = string.Empty;
                txtInScan.Text = string.Empty;
                HandyControl.Controls.MessageBox.Error("入库失败");
                txtInBarCode.Focus();
            }
        }





        /// <summary>
        /// 入库条码改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInBarCode_TextChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                materialName.Text = string.Empty;
                materialSpec.Text = string.Empty;
                string barCode = txtInBarCode.Text;
                if (barCode.Length < 19) return;


                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();

                if (!string.IsNullOrEmpty(barCode))
                {


                    var material = dbContext.MesBaseBarcodeInfo.FirstOrDefault(t => t.barcodeInfo == barCode);
                    if (material == null)
                    {
                        HandyControl.Controls.MessageBox.Error("未查询到该条码内容!");
                       
                        txtInBarCode.Text = string.Empty;
                        txtInScan.Text = string.Empty;
                        txtInBarCode.Focus();
                    }
                    else
                    {
                        var mesBaseMaterialInfo = dbContext.MesBaseMaterialInfo.FirstOrDefault(t => t.MaterialId == material.materialId);
                        if (mesBaseMaterialInfo == null)
                        {
                            HandyControl.Controls.MessageBox.Error("未查询到该条码绑定的物料信息!");
                       
                          
                            txtInBarCode.Text = string.Empty;
                            txtInScan.Text = string.Empty;
                            txtInBarCode.Focus();
                        }
                        else
                        {

                            txtInScan.Text = (material.batchFlag == "1") ? "" : "1.00";
                            materialName.Text = mesBaseMaterialInfo.MaterialName;
                            materialSpec.Text = mesBaseMaterialInfo.MaterialSpec;
                            if (mesBaseMaterialInfo.BatchFlag == "0")
                            {
                                txtInScan.IsReadOnly = true;
                            }
                            else
                            {
                                txtInScan.IsReadOnly = false;
                            }
                            txtInScan.Focus();
                        }
                    }
                }
            }
            catch
            {

            }
        }



    }
}
