using CK.SCP.Controller;
using CK.SCP.Models;
using CK.SCP.Models.Enums;
using CK.SCP.Models.ScpEntity;
using CK.SCP.Utils;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CK.SCP.Controller
{
    public class SCP_PALLET_CONTROLLER
    {
        public static void Get_V_TB_PALLET_List(V_TB_PALLET p_entity, Action<ResultObject<IQueryable<V_TB_PALLET>>> p_action)
        {
            ResultObject<IQueryable<V_TB_PALLET>> _ret = new ResultObject<IQueryable<V_TB_PALLET>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_PALLET> q = db.V_TB_PALLET;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.AskBillNum))
                    {
                        q = q.Where(p => p.AskBillNum.Contains(p_entity.AskBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                   
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ShipUser))
                    {
                        q = q.Where(p => p.ShipUser.Contains(p_entity.ShipUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ReceiveUser))
                    {
                        q = q.Where(p => p.ReceiveUser.Contains(p_entity.ReceiveUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ErpBillNum))
                    {
                        q = q.Where(p => p.ErpBillNum.Contains(p_entity.ErpBillNum));
                    }
                    if (p_entity.ModType != null)
                    {
                        q = q.Where(p => p.ModType == p_entity.ModType);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Buyer))
                    {
                        q = q.Where(p => p.Buyer.Contains(p_entity.Buyer));
                    }
                    if (!string.IsNullOrEmpty(p_entity.BuyerPhone))
                    {
                        q = q.Where(p => p.BuyerPhone.Contains(p_entity.BuyerPhone));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ModType_DESC))
                    {
                        q = q.Where(p => p.ModType_DESC.Contains(p_entity.ModType_DESC));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.State_DESC))
                    {
                        q = q.Where(p => p.State_DESC.Contains(p_entity.State_DESC));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PlateNumber))
                    {
                        q = q.Where(p => p.PlateNumber.Contains(p_entity.PlateNumber));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site_Desc))
                    {
                        q = q.Where(p => p.Site_Desc.Contains(p_entity.Site_Desc));
                    }
                    q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    //if (!string.IsNullOrEmpty(p_entity.ReceivedPort))
                    //{
                    //    q = q.Where(p => p.ReceivedPort.Contains(p_entity.ReceivedPort));
                    //}
                    //if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    //{
                    //    q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    //}
                    //if (!string.IsNullOrEmpty(p_entity.UpdateUser))
                    //{
                    //    q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    //}
                    //if (!string.IsNullOrEmpty(p_entity.UpdateInfo))
                    //{
                    //    q = q.Where(p => p.UpdateInfo.Contains(p_entity.UpdateInfo));
                    //}
                    //if (p_entity.IsDeleted != false)
                    //{
                    //    q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    //}
                    //if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    //{
                    //    q = q.Where(p => p_entity.UserInAddress.Contains(p.));
                    //}
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                    p_action(_ret);
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//捕获实体验证异常
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("表:{0},字段:{1},信息:{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_V_TB_PALLET_List", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "字段验证失败" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//并发冲突异常
            {

                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_V_TB_PALLET_List", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_V_TB_PALLET_List", ex.ToString());
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_V_TB_PALLET_List", e.Message);
                throw e;
            }

        }
        public static void Get_TB_PALLETS_List(TB_PALLETS p_entity, Action<ResultObject<IQueryable<TB_PALLETS>>> p_action)
        {
            ResultObject<IQueryable<TB_PALLETS>> _ret = new ResultObject<IQueryable<TB_PALLETS>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<TB_PALLETS> q = db.TB_PALLETS;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                    p_action(_ret);
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//捕获实体验证异常
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("表:{0},字段:{1},信息:{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_TB_PALLETS_List", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "字段验证失败" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//并发冲突异常
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_TB_PALLETS_List", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_TB_PALLETS_List", ex.ToString());
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;
                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Get_TB_PALLETS_List", e.Message);
                throw e;
            }
        }
        public ResultObject<bool> Save_V_TB_PALLET(List<TB_PALLET> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TB_PALLET.AddOrUpdate(itm);
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(V_TB_PALLET), "Save_V_TB_PALLET", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }



        public ResultObject<bool> Del_V_TB_PALLET(List<TB_PALLET> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TB_PALLET.Remove(itm);
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(V_TB_PALLET), "Del_V_TB_PALLET", e.Message); throw e;
            }
            return _ret;
        }






        public static void Get_V_TB_PALLET_DETAIL_List(V_TB_PALLET_DETAIL p_entity, Action<ResultObject<IQueryable<V_TB_PALLET_DETAIL>>> p_action)
        {
            ResultObject<IQueryable<V_TB_PALLET_DETAIL>> _ret = new ResultObject<IQueryable<V_TB_PALLET_DETAIL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_PALLET_DETAIL> q = db.V_TB_PALLET_DETAIL;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (p_entity.PoLine != 0)
                    {
                        q = q.Where(p => p.PoLine == p_entity.PoLine);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoUnit))
                    {
                        q = q.Where(p => p.PoUnit.Contains(p_entity.PoUnit));
                    }
                    if (!string.IsNullOrEmpty(p_entity.LocUnit))
                    {
                        q = q.Where(p => p.LocUnit.Contains(p_entity.LocUnit));
                    }
                    if (p_entity.Price != 0)
                    {
                        q = q.Where(p => p.Price == p_entity.Price);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Currency))
                    {
                        q = q.Where(p => p.Currency.Contains(p_entity.Currency));
                    }
                    if (p_entity.PackQty != 0)
                    {
                        q = q.Where(p => p.PackQty == p_entity.PackQty);
                    }
                    if (p_entity.UnConv != 0)
                    {
                        q = q.Where(p => p.UnConv == p_entity.UnConv);
                    }
                    if (!string.IsNullOrEmpty(p_entity.DockCode))
                    {
                        q = q.Where(p => p.DockCode.Contains(p_entity.DockCode));
                    }
                    if (p_entity.State != null)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateUser))
                    {
                        q = q.Where(p => p.UpdateUser.Contains(p_entity.UpdateUser));
                    }
                    if (!string.IsNullOrEmpty(p_entity.UpdateInfo))
                    {
                        q = q.Where(p => p.UpdateInfo.Contains(p_entity.UpdateInfo));
                    }
                    if (p_entity.IsDeleted != false)
                    {
                        q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartDesc1))
                    {
                        q = q.Where(p => p.PartDesc1.Contains(p_entity.PartDesc1));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CurrencyDesc))
                    {
                        q = q.Where(p => p.CurrencyDesc.Contains(p_entity.CurrencyDesc));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartDesc2))
                    {
                        q = q.Where(p => p.PartDesc2.Contains(p_entity.PartDesc2));
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch.Contains(p_entity.VendBatch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch.Contains(p_entity.Batch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.AskBillNum))
                    {
                        q = q.Where(p => p.AskBillNum.Contains(p_entity.AskBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PalletNum))
                    {
                        q = q.Where(p => p.PalletNum.Contains(p_entity.PalletNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ReceivedPort))
                    {
                        q = q.Where(p => p.ReceivedPort.Contains(p_entity.ReceivedPort));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ReceivedPort_Desc))
                    {
                        q = q.Where(p => p.ReceivedPort_Desc.Contains(p_entity.ReceivedPort_Desc));
                    }
                    //if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    //{
                    //    q = q.Where(p => p_entity.UserInAddress.Contains(p.Address));
                    //}
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                    p_action(_ret);
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(V_TB_PALLET_DETAIL), "Get_V_TB_PALLET_DETAIL_List", e.Message);
                throw e;
            }
        }


        public static ResultObject<bool> Save_TB_PALLET_STATE(List<string> p_list, PalletState p_state)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                   
                    if (p_state == PalletState.Reject)
                    {
                        var _ls = db.TB_PALLET.Where(p => p_list.Contains(p.PalletNum)).ToList();
                       
                            _ls.ForEach(p =>
                            {
                                p.State = (int)AskState.Reject;
                                p.IsDeleted = true;
                                var _list = db.TB_PALLET_DETAIL.Where(itm => itm.PalletNum == p.PalletNum).ToList();
                                _list.ForEach(itm =>
                                {
                                    itm.State = (int)PalletState.Reject;
                                    itm.IsDeleted = true;
                                }
                                );
                                db.TB_PALLET_DETAIL.AddOrUpdate(itm => itm.UID, _list.ToArray());
                            }
                            );
                            db.TB_PALLET.AddOrUpdate(p => p.PalletNum, _ls.ToArray());
                    }
                
                  
                 
                    if (string.IsNullOrEmpty(_ret.Message))
                    {
                        if (db.SaveChanges() != -1)
                        {
                            _ret.State = ReturnStatus.Succeed;
                            _ret.Result = true;
                        }
                        else
                        {
                            _ret.State = ReturnStatus.Failed;
                            _ret.Result = false;
                            _ret.Message = "数据更新失败!";
                        }
                    }

                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)//捕获实体验证异常
            {
                var sb = new StringBuilder();

                foreach (var error in dbEx.EntityValidationErrors.ToList())
                {

                    error.ValidationErrors.ToList().ForEach(i =>
                    {
                        sb.AppendFormat("表:{0},字段:{1},信息:{2}\r\n", error.Entry.Entity.GetType().Name, i.PropertyName, i.ErrorMessage);
                    });
                }
                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(dbEx);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_PALLET_CONTROLLER), "Save_TB_PALLET_STATE", sb.ToString());
                throw new ScpException(ResultCode.DbEntityValidationException, sb.ToString(), "字段验证失败" + sb.ToString());
            }
            catch (OptimisticConcurrencyException ex)//并发冲突异常
            {

                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_PALLET_CONTROLLER), "Save_TB_PALLET_STATE", ex.ToString());
                throw new ScpException(ResultCode.Exception, "9999", ex.ToString());
            }
            catch (ScpException ex)
            {


                _ret.State = ReturnStatus.Failed;
                _ret.Result = false;
                _ret.ErrorList.Add(ex);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_PALLET_CONTROLLER), "Save_TB_PALLET_STATE", ex.ToString());

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UpdateException))
                {
                    var inner = (UpdateException)ex.InnerException;


                    throw new ScpException(ResultCode.Exception, "0000", ex.ToString());
                }
                else
                {
                    if (ex.InnerException != null) throw ex.InnerException;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_PALLET_CONTROLLER), "Save_TB_PALLET_STATE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }



    }


}