using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Business;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.Model.enums;
using SlnMesnac.Plc;
using SlnMesnac.Repository.service;
using SlnMesnac.WPF.MessageTips;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.WPF.ViewModel
* 唯一标识：7b8b1dd3-c235-4b39-9df0-2c086246b206
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-04-10 10:31:47
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.WPF.ViewModel
{
    public class ManualDeliveryViewModel : ViewModelBase
    {

        private readonly IWmsRawPreferredOutService? wmsRawPreferredOutService;
        private readonly ISqlSugarClient? sqlSugarClient;
        private readonly DebugConfig debugConfig = DebugConfig.Instance;
        public ManualDeliveryViewModel()
        {
            wmsRawPreferredOutService = App.ServiceProvider.GetService<IWmsRawPreferredOutService>();
            sqlSugarClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            QueryStringCommand = new RelayCommand<string>(Query);

            Init();

            //  ConfirmCommand = new RelayCommand<object>(Confirm);
            DeleteCommand = new RelayCommand<object>(Delete);
            ChangeModeCommand = new RelayCommand<object>(ChangeMode);
        }

        private void Init()
        {
            WmsRawPreferredOutDataGrid.Clear();
            List<WmsRawPreferredOut> list = wmsRawPreferredOutService.Query();
            if (list != null && list.Count > 0)
            {

                foreach (var item in list)
                {
                    WmsRawPreferredOutDataGrid.Add(item);
                }
            }
        }

        #region 参数定义
        /// <summary>
        /// 计划列表DataGrid
        /// </summary>
        private ObservableCollection<WmsRawPreferredOut> wmsRawPreferredOutDataGrid = new ObservableCollection<WmsRawPreferredOut>();

        public ObservableCollection<WmsRawPreferredOut> WmsRawPreferredOutDataGrid
        {
            get { return wmsRawPreferredOutDataGrid; }
            set { wmsRawPreferredOutDataGrid = value; RaisePropertyChanged(() => WmsRawPreferredOutDataGrid); }

        }

        /// <summary>
        /// 选中计划列表信息
        /// </summary>
        private MesProductPlanDto selectedCells;
        public MesProductPlanDto SelectedCells
        {
            get { return selectedCells; }
            set
            {
                selectedCells = value;
                RaisePropertyChanged(() => SelectedCells);
            }
        }
        #endregion

        #region 事件定义
        public RelayCommand<string> QueryStringCommand { get; set; }

        

        /// <summary>
        /// 投料模式切换
        /// </summary>
        public RelayCommand<object> ChangeModeCommand { get; set; }

        /// <summary>
        /// 关闭事件
        /// </summary>
        public RelayCommand<object> DeleteCommand { get; set; }

        #endregion

        /// <summary>
        /// 查询库位能否投料，可以的话添加到投料队列
        /// </summary>
        /// <param name="queryStr"></param>
        private void Query(string queryStr)
        {
            try
            {
                WmsBaseLocation? targetLocation = sqlSugarClient.AsTenant().GetConnection("mes").Queryable<WmsBaseLocation>().Where(it => it.LocationCode == queryStr && it.WarehouseId == 311).First();
                WmsRawStock? wmsRawStock = sqlSugarClient.AsTenant().GetConnection("mes").Queryable<WmsRawStock>().Where(it => it.LocationCode == queryStr).First();
                if (targetLocation != null)
                {
                    if (string.IsNullOrEmpty(targetLocation.ContainerCode) || wmsRawStock == null)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Msg.MsgShow("该库位没有库存，请重新输入", 2, 3);

                        });

                        return;
                    }
                    if (targetLocation.LocationStatus != "1")
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Msg.MsgShow("该库位状态异常，禁止出", 2, 3);
                        });

                        return;
                    }
                    if (targetLocation.LocDeep == 1)
                    {
                        int? row = targetLocation.LocRow % 2 == 0 ? targetLocation.LocRow - 1 : targetLocation.LocRow + 1;
                        WmsBaseLocation? shallowLocation = sqlSugarClient.AsTenant().GetConnection("mes").Queryable<WmsBaseLocation>().Where(it => it.WarehouseId == 311 && it.LocRow == row && it.LocColumn == targetLocation.LocColumn).First();
                        if (shallowLocation == null)
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Msg.MsgShow($"未找到当前深库位对应的浅库位，请重新选择", 2, 3);

                            });
                           
                            return;
                        }
                        if(shallowLocation.LocationStatus != "1")
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Msg.MsgShow($"当前库位对应的浅库位{shallowLocation.LocationCode}状态异常，禁止出库", 2, 3);

                            });
                          
                            return;
                        }
                        //if (!string.IsNullOrEmpty(shallowLocation.ContainerCode))
                        //{
                        //    // 判断浅库位是否已经加到出库队列
                        //    WmsRawPreferredOut? shallowPreferredOut =  wmsRawPreferredOutService.Query(x => x.LocationCode == shallowLocation.LocationCode).FirstOrDefault();
                        //    if(shallowPreferredOut == null)
                        //    {
                        //        Msg.MsgShow($"当前库位对应的浅库位{shallowLocation.LocationCode}有库存,请优先出对应的浅库位", 2, 3);
                        //        return;
                        //    }        
                        //}

                    }
                    else
                    {  // 浅库位，需要判断深库位是否已经加到出库队列
                        int? row = targetLocation.LocRow % 2 == 0 ? targetLocation.LocRow - 1 : targetLocation.LocRow + 1;
                        WmsBaseLocation? deepLocation = sqlSugarClient.AsTenant().GetConnection("mes").Queryable<WmsBaseLocation>().Where(it => it.WarehouseId==311 &&  it.LocRow==row && it.LocColumn==targetLocation.LocColumn).First();
                     
                        if (deepLocation != null)
                        {
                            WmsRawPreferredOut? isDeepHas = wmsRawPreferredOutService.Query(x => x.WarehouseId==311 && x.LocationCode == deepLocation.LocationCode).FirstOrDefault();
                            if (isDeepHas != null)
                            {
                                Msg.MsgShow($"当前库位{targetLocation.LocationCode}对应的深库位{deepLocation.LocationCode}已经存在出库队列，禁止出浅库位,请等待出完或手动删除", 2, 3);
                                return;
                            }

                        }
                    }
                    WmsRawPreferredOut? isHas = wmsRawPreferredOutService.Query(x => x.LocationCode == targetLocation.LocationCode).FirstOrDefault();
                    if (isHas != null)
                    {
                        Msg.MsgShow($"当前库位{targetLocation.LocationCode}已经存在出库队列，无需重复出", 2, 3);
                        return;
                    }
                    WmsRawPreferredOut wmsRawPreferredOut = new WmsRawPreferredOut();
                    wmsRawPreferredOut.WarehouseId = wmsRawStock.WarehouseId;
                    wmsRawPreferredOut.WarehouseFloor = targetLocation.WarehouseFloor;
                    wmsRawPreferredOut.LocationCode = targetLocation.LocationCode;
                    wmsRawPreferredOut.StockType = "1";
                    wmsRawPreferredOut.MaterialId = wmsRawStock.MaterialId;
                    wmsRawPreferredOut.CreateBy = "PRD";
                    wmsRawPreferredOut.CreateDate = DateTime.Now;
                    wmsRawPreferredOut.UpdateBy = "PRD";
                    wmsRawPreferredOut.UpdateDate = DateTime.Now;
                    wmsRawPreferredOut.UseFlag = "1";
                    wmsRawPreferredOutService.Insert(wmsRawPreferredOut);
                    Init();

                    Msg.MsgShow("保存成功", 0, 5);
                }
                else
                {

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("输入的库位有误，请重新输入", 2, 5);

                    });
                    

                    return;
                }
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"保存异常:{ex.Message}", 2, 5);

                });
               

            }
        }

        ///// <summary>
        ///// 确认
        ///// </summary>
        ///// <param name="parameter"></param>
        //private void Confirm(object parameter)
        //{

        //    try
        //    {
        //        if (selectedCells != null)
        //        {
        //            if (_prodMgmtBusiness.ApplyDeliveryHandle(selectedCells.MaterialId.ToString()))
        //            {
        //                _prodMgmtBusiness.RefreshMessage("手动叫料成功");
        //            }
        //            else
        //            {
        //                _prodMgmtBusiness.RefreshMessage("手动叫料失败");
        //            }
        //        }
        //    }catch (Exception ex)
        //    {
        //        _prodMgmtBusiness.RefreshMessage($"手动叫料处理异常:{ex.Message}");
        //    }

        //    var window = parameter as Window;
        //    if (window != null)
        //    {
        //        window.Close();
        //    }
        //}

        /// <summary>
        /// 取消
        /// </summary>
        private void Delete(object parameter)
        {
            string locationCode = parameter as string;
            if (!string.IsNullOrEmpty(locationCode))
            {
                WmsBaseLocation? targetLocation = sqlSugarClient.AsTenant().GetConnection("mes").Queryable<WmsBaseLocation>().Where(it => it.LocationCode == locationCode && it.WarehouseId == 311).First();
                // 删除浅库位，需要保证也同步删除队列里的深库位
                if (targetLocation != null && targetLocation.LocDeep==2)
                {
                    // 判断深库位是否在出库队列，如果在删除
                    int? row = targetLocation.LocRow % 2 == 0 ? targetLocation.LocRow - 1 : targetLocation.LocRow + 1;
                    WmsBaseLocation? deepLocation = sqlSugarClient.AsTenant().GetConnection("mes").Queryable<WmsBaseLocation>().Where(it => it.WarehouseId == 311 && it.LocRow == row && it.LocColumn == targetLocation.LocColumn).First();
                    if (deepLocation != null)
                    {
                        var deepHas = wmsRawPreferredOutService.Query(x => x.LocationCode == deepLocation.LocationCode).FirstOrDefault();
                        if(deepHas != null)
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Msg.MsgShow($"当前库位对应的深库位{deepLocation.LocationCode}在出库队列,请先删除", 2, 3);

                            });
                            
                            return;
                        }
                    }
                
                }
                var item = wmsRawPreferredOutService.Query(x => x.LocationCode == locationCode).FirstOrDefault();


                bool isSuccess = wmsRawPreferredOutService.DeleteById(item.RawPreferredOutId);
                Init();
            }
        }
   
    
        private void ChangeMode(object parameter)
        {
            debugConfig.ProductMode = debugConfig.ProductMode=="1"?"2":"1";
        }


    }
}
