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.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CK.SCP.Controller
{
    public class SCP_ASK_CONTROLLER_PACKAGE
    {
        public static void Get_V_TB_ASK_DETAIL_PACKAGE_List(V_TB_ASK_DETAIL_PACKAGE p_entity, Action<ResultObject<IQueryable<V_TB_ASK_DETAIL_PACKAGE>>> p_action)
        {
            ResultObject<IQueryable<V_TB_ASK_DETAIL_PACKAGE>> _ret = new ResultObject<IQueryable<V_TB_ASK_DETAIL_PACKAGE>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_ASK_DETAIL_PACKAGE> q = db.V_TB_ASK_DETAIL_PACKAGE;
                    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));
                    }                
                    q = q.Where(p => p.MinPackQty!=null);              
                    if (!string.IsNullOrEmpty(p_entity.DockCode))
                    {
                        q = q.Where(p => p.DockCode.Contains(p_entity.DockCode));
                    }
                    if (p_entity.State == 3 || p_entity.State == 4 || p_entity.State == 2)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }

                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }

                    q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);


                    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.AskBillNum))
                    {
                        q = q.Where(p => p.AskBillNum.Contains(p_entity.AskBillNum));
                    }
                    _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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_List", e.Message);
                throw e;
            }
        }
        #region 青岛项目
        public static void IS_CHECK_PACKAGE(List<V_TB_ASK_DETAIL> p_list, Action<ResultObject<bool>> p_action)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _entity = p_list.FirstOrDefault();
                    var _ask = db.V_TB_ASK_DETAIL_PACKAGE.Where
                         (p => p.AskBillNum == _entity.AskBillNum
                          && p.PoLine == _entity.PoLine
                          && p.PartCode == _entity.PartCode
                         ).FirstOrDefault();
                   // var _palletPack = _ask.PalletPackQty;
                    if (_ask != null)
                    {
                        decimal _percent = 0;
                        decimal _number = 0;
                        List<string> _list = new List<string>();
                        p_list.ForEach(p =>
                        {
                            var _askDetail = db.V_TB_ASK_DETAIL_PACKAGE.Where
                           (itm => itm.AskBillNum == p.AskBillNum
                            && itm.PoLine == p.PoLine
                            && itm.PartCode == p.PartCode
                           ).FirstOrDefault();
                            var _palletPack = _askDetail.PalletPackQty;
                            if (_askDetail != null)
                            {
                                _number = 0;
                                int _TempQty = Convert.ToInt32( p.TempQty);
                                int _PackQty = Convert.ToInt32(p.PackQty);
                                if (_TempQty / _PackQty > 0)
                                {
                                    int _count = _TempQty / _PackQty;
                                    _number += _count;
                                    if (p.TempQty % p.PackQty > 0)
                                    {
                                        _number++;
                                    }
                                }
                                else
                                {
                                    if (_TempQty > 0)
                                    {
                                        _number++;
                                    }
                                }
                                _percent += _number / (decimal)_palletPack;//托盘标包半分比
                               // if (!string.IsNullOrEmpty(p.VendBatch)&& _number > (decimal)_palletPack)
                                //{
                                    string _str = string.Format("零件号:{0},供应商批次:{1},要货箱数:{2}箱,托盘标包数:{3}箱/托盘,占总托盘百数为:{4}", p.PartCode, p.VendBatch, _number.ToString(),_palletPack, _number / (decimal)_palletPack);
                                    _list.Add(_str);
                               // }
                            }
                        });
                        _ret.State = ReturnStatus.Succeed;
                        if (_percent <= 1)
                        {
                            _ret.Result = true;
                        }
                        else
                        {
                            _ret.Result = false;
                            _ret.MessageList = _list;
                        }
                        //if (_list.Count==0)
                        //{
                        //    _ret.Result = true;
                        //}
                        //else
                        //{
                        //    _ret.Result = false;
                        //    _ret.MessageList = _list;
                        //}
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        
                    }
                    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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_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_ASK_CONTROLLER), "Get_V_TB_ASK_DETAIL_List", e.Message);
                throw e;
            }
        }

        #endregion


    }
}