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

namespace CK.SCP.Controller
{




    public class SCP_INVOICE_CONTROLLER
    {

        public static void Get_V_TB_INVOICE_BY_CG_List(V_TB_INVOICE p_entity, Action<ResultObject<IQueryable<V_TB_INVOICE>>> p_action)
        {
            ResultObject<IQueryable<V_TB_INVOICE>> _ret = new ResultObject<IQueryable<V_TB_INVOICE>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_INVOICE> q = db.V_TB_INVOICE;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvcBillNum))
                    {
                        q = q.Where(p => p.InvcBillNum.Contains(p_entity.InvcBillNum));
                    }
                  
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }

                    //if (p_entity.BeginTime != null && !p_entity.BeginTime.ToString().Contains("0001/1/1"))
                    //{
                    //    q = q.Where(p => p.CreateTime >= p_entity.BeginTime);
                    //}
                    //if (p_entity.EndTime != null && !p_entity.EndTime.ToString().Contains("0001/1/1"))
                    //{
                    //    q = q.Where(p => p.CreateTime <= p_entity.EndTime);
                    //}
                    if (!string.IsNullOrEmpty(p_entity.InvoiceNum))
                    {
                        q = q.Where(p => p.InvoiceNum.Contains(p_entity.InvoiceNum));
                    }
                    if (p_entity.BillStateList != null && p_entity.BillStateList.Count > 0)
                    {
                        q = q.Where(p => p_entity.BillStateList.Contains(p.State));
                    }
                    else if (p_entity.State != 0)
                    {
                        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 (p_entity.Tax != null)
                    {
                        q = q.Where(p => p.Tax == p_entity.Tax);
                    }
                    if (p_entity.TaxAmount != null)
                    {
                        q = q.Where(p => p.TaxAmount == p_entity.TaxAmount);
                    }
                    if (p_entity.Amount != null)
                    {
                        q = q.Where(p => p.Amount == p_entity.Amount);
                    }
                    if (p_entity.Total != null)
                    {
                        q = q.Where(p => p.Total == p_entity.Total);
                    }
                    if (!string.IsNullOrEmpty(p_entity.ExpressNum))
                    {
                        q = q.Where(p => p.ExpressNum.Contains(p_entity.ExpressNum));
                    }
                    if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInAddress.Contains(p.Site));
                    }

                    if (p_entity.UserInVendIds != null && p_entity.UserInVendIds.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInVendIds.Contains(p.VendId));
                    }
                    if (p_entity.InvoiceList != null && p_entity.InvoiceList.Count > 0)
                    {
                        q = q.Where(p => p_entity.InvoiceList.Contains(p.InvcBillNum));
                    }

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

                    _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_INVOICE_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_INVOICE_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_INVOICE_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_INVOICE_List", e.Message);
                throw e;
            }

        }




        public static List<string> Get_V_TB_INVOICE_BY_TIME(string p_begin,string p_end,string p_po,string p_asn)
        {
            List<string> _list = new List<string>();
            using (ScpEntities db = EntitiesFactory.CreateScpInstance())
            {

                StringBuilder _builder = new StringBuilder();
                _builder.Append( "SELECT DISTINCT InvcBillNum  FROM TB_INVOICE_DETAIL a Inner join TB_RECEIVE B on A.RecvBillNum = B.RecvBillNum\r\n");
                _builder.AppendFormat(" WHERE 1=1 \r\n");
                if (!string.IsNullOrEmpty(p_begin))
                {
                    _builder.AppendFormat(" and B.CreateTime >= cast('{0}' as datetime) \r\n", p_begin);
                }
                if (!string.IsNullOrEmpty(p_end))
                {
                    _builder.AppendFormat(" and B.CreateTime <= cast('{0}' as datetime) \r\n", p_end);
                }
                if (!string.IsNullOrEmpty(p_po))
                {
                    _builder.AppendFormat(" AND  A.PoBillNum='{0}' \r\n", p_po);
                }
                if (!string.IsNullOrEmpty(p_asn))
                {
                    _builder.AppendFormat(" and A.AsnBillNum='{0}' \r\n",p_asn);
                }
                _list =db.Database.SqlQuery<string>(_builder.ToString()).ToList();

            }
            return _list;
        }


        public static void Get_V_TB_INVOICE_List(V_TB_INVOICE p_entity, Action<ResultObject<IQueryable<V_TB_INVOICE>>> p_action)
        {
            ResultObject<IQueryable<V_TB_INVOICE>> _ret = new ResultObject<IQueryable<V_TB_INVOICE>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_INVOICE> q = db.V_TB_INVOICE;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvcBillNum))
                    {
                        q = q.Where(p => p.InvcBillNum.Contains(p_entity.InvcBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId==p_entity.VendId);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                  
                    if (!string.IsNullOrEmpty(p_entity.InvoiceNum))
                    {
                        q = q.Where(p => p.InvoiceNum.Contains(p_entity.InvoiceNum));
                    }
                    if (p_entity.BillStateList != null && p_entity.BillStateList.Count > 0)
                    {
                        q = q.Where(p => p_entity.BillStateList.Contains(p.State));
                    }
                    else if (p_entity.State != 0)
                    {
                        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 (p_entity.Tax != null)
                    {
                        q = q.Where(p => p.Tax == p_entity.Tax);
                    }
                    if (p_entity.TaxAmount != null)
                    {
                        q = q.Where(p => p.TaxAmount == p_entity.TaxAmount);
                    }
                    if (p_entity.Amount != null)
                    {
                        q = q.Where(p => p.Amount == p_entity.Amount);
                    }
                    if (p_entity.Total != null)
                    {
                        q = q.Where(p => p.Total == p_entity.Total);
                    }
                    if (!string.IsNullOrEmpty(p_entity.ExpressNum))
                    {
                        q = q.Where(p => p.ExpressNum.Contains(p_entity.ExpressNum));
                    }
                    if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInAddress.Contains(p.Site));
                    }

                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (p_entity.InvoiceList!=null && p_entity.InvoiceList.Count>0)
                    {
                        q = q.Where(p => p_entity.InvoiceList.Contains(p.InvcBillNum));
                    }
                    // q = q.Where(p => p_entity.IsRed == p.IsRed);

                    _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_INVOICE_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_INVOICE_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_INVOICE_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_INVOICE_List", e.Message);
                throw e;
            }

        }



        public static void Get_V_TB_INVOICE_ERP_List(V_TB_INVOICE p_entity, Action<ResultObject<IQueryable<V_TB_INVOICE>>> p_action)
        {
            ResultObject<IQueryable<V_TB_INVOICE>> _ret = new ResultObject<IQueryable<V_TB_INVOICE>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_INVOICE> q = db.V_TB_INVOICE;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvcBillNum))
                    {
                        q = q.Where(p => p.InvcBillNum.Contains(p_entity.InvcBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }

                    if (!string.IsNullOrEmpty(p_entity.InvoiceNum))
                    {
                        q = q.Where(p => p.InvoiceNum.Contains(p_entity.InvoiceNum));
                    }
                    if (p_entity.BillStateList != null && p_entity.BillStateList.Count > 0)
                    {
                        q = q.Where(p => p_entity.BillStateList.Contains(p.State));
                    }
                    else if (p_entity.State != 0)
                    {
                        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 (p_entity.Tax != null)
                    {
                        q = q.Where(p => p.Tax == p_entity.Tax);
                    }
                    if (p_entity.TaxAmount != null)
                    {
                        q = q.Where(p => p.TaxAmount == p_entity.TaxAmount);
                    }
                    if (p_entity.Amount != null)
                    {
                        q = q.Where(p => p.Amount == p_entity.Amount);
                    }
                    if (p_entity.Total != null)
                    {
                        q = q.Where(p => p.Total == p_entity.Total);
                    }
                    if (!string.IsNullOrEmpty(p_entity.ExpressNum))
                    {
                        q = q.Where(p => p.ExpressNum.Contains(p_entity.ExpressNum));
                    }
                    if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInAddress.Contains(p.Site));
                    }

                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (p_entity.InvoiceList != null && p_entity.InvoiceList.Count > 0)
                    {
                        q = q.Where(p => p_entity.InvoiceList.Contains(p.InvcBillNum));
                    }
                    // q = q.Where(p => p_entity.IsRed == p.IsRed);

                    _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_INVOICE_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_INVOICE_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_INVOICE_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_INVOICE_List", e.Message);
                throw e;
            }

        }

        public static void Get_V_TB_INVOICE_List2(V_TB_INVOICE p_entity, Action<ResultObject<IQueryable<V_TB_INVOICE_RED>>> p_action)
        {
            ResultObject<IQueryable<V_TB_INVOICE_RED>> _ret = new ResultObject<IQueryable<V_TB_INVOICE_RED>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_INVOICE_RED> q = db.V_TB_INVOICE_RED;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvcBillNum))
                    {
                        q = q.Where(p => p.InvcBillNum.Contains(p_entity.InvcBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (p_entity.BeginTime != null && !p_entity.BeginTime.ToString().Contains("0001/1/1"))
                    {
                        q = q.Where(p => p.CreateTime >= p_entity.BeginTime);
                    }
                    if (p_entity.EndTime != null && !p_entity.EndTime.ToString().Contains("0001/1/1"))
                    {
                        q = q.Where(p => p.CreateTime <= p_entity.EndTime);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvoiceNum))
                    {
                        q = q.Where(p => p.InvoiceNum.Contains(p_entity.InvoiceNum));
                    }
                    if (p_entity.BillStateList != null && p_entity.BillStateList.Count > 0)
                    {
                        q = q.Where(p => p_entity.BillStateList.Contains(p.State));
                    }
                    else if (p_entity.State != 0)
                    {
                        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 (p_entity.Tax != null)
                    {
                        q = q.Where(p => p.Tax == p_entity.Tax);
                    }
                    if (p_entity.TaxAmount != null)
                    {
                        q = q.Where(p => p.TaxAmount == p_entity.TaxAmount);
                    }
                    if (p_entity.Amount != null)
                    {
                        q = q.Where(p => p.Amount == p_entity.Amount);
                    }
                    if (p_entity.Total != null)
                    {
                        q = q.Where(p => p.Total == p_entity.Total);
                    }
                    if (!string.IsNullOrEmpty(p_entity.ExpressNum))
                    {
                        q = q.Where(p => p.ExpressNum.Contains(p_entity.ExpressNum));
                    }
                    if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    {
                        q = q.Where(p => p_entity.UserInAddress.Contains(p.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    q = q.Where(p => p_entity.IsRed == p.IsRed);

                    _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_INVOICE_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_INVOICE_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_INVOICE_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_INVOICE_List", e.Message);
                throw e;
            }

        }
        public static void Get_V_TB_INVOICE_DETAIL_List(V_TB_INVOICE_DETAIL p_entity, Action<ResultObject<IQueryable<V_TB_INVOICE_DETAIL>>> p_action)
        {
            ResultObject<IQueryable<V_TB_INVOICE_DETAIL>> _ret = new ResultObject<IQueryable<V_TB_INVOICE_DETAIL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_INVOICE_DETAIL> q = db.V_TB_INVOICE_DETAIL;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvcBillNum))
                    {
                        q = q.Where(p => p.InvcBillNum.Contains(p_entity.InvcBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (p_entity.PoLineNum != 0)
                    {
                        q = q.Where(p => p.PoLineNum == p_entity.PoLineNum);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch.Contains(p_entity.Batch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch.Contains(p_entity.VendBatch));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoUnit))
                    {
                        q = q.Where(p => p.PoUnit.Contains(p_entity.PoUnit));
                    }
                    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 != null)
                    {
                        q = q.Where(p => p.PackQty == p_entity.PackQty);
                    }
                    if (p_entity.State != null)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvoiceNum))
                    {
                        q = q.Where(p => p.InvoiceNum.Contains(p_entity.InvoiceNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ExpressNum))
                    {
                        q = q.Where(p => p.ExpressNum.Contains(p_entity.ExpressNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    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 (p_entity.Tax != null)
                    {
                        q = q.Where(p => p.Tax == p_entity.Tax);
                    }
                    if (!string.IsNullOrEmpty(p_entity.RecvBillNum))
                    {
                        q = q.Where(p => p.RecvBillNum.Contains(p_entity.RecvBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartDesc1))
                    {
                        q = q.Where(p => p.PartDesc1.Contains(p_entity.PartDesc1));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    q = q.Where(p => p.IsRed == p_entity.IsRed);

                    _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_INVOICE_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_INVOICE_CONTROLLER), "Get_V_TB_INVOICE_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_INVOICE_CONTROLLER), "Get_V_TB_INVOICE_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_INVOICE_CONTROLLER), "Get_V_TB_INVOICE_DETAIL_List", e.Message);
                throw e;
            }

        }
        public static void Get_V_TB_INVOICE_DETAIL_List2(V_TB_INVOICE_DETAIL p_entity, Action<ResultObject<IQueryable<V_TB_INVOICE_DETAIL_RED>>> p_action)
        {
            ResultObject<IQueryable<V_TB_INVOICE_DETAIL_RED>> _ret = new ResultObject<IQueryable<V_TB_INVOICE_DETAIL_RED>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_INVOICE_DETAIL_RED> q = db.V_TB_INVOICE_DETAIL_RED;
                    if (p_entity.UID != 0)
                    {
                        q = q.Where(p => p.UID == p_entity.UID);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvcBillNum))
                    {
                        q = q.Where(p => p.InvcBillNum.Contains(p_entity.InvcBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (p_entity.PoLineNum != 0)
                    {
                        q = q.Where(p => p.PoLineNum == p_entity.PoLineNum);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch.Contains(p_entity.Batch));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendBatch))
                    {
                        q = q.Where(p => p.VendBatch.Contains(p_entity.VendBatch));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoUnit))
                    {
                        q = q.Where(p => p.PoUnit.Contains(p_entity.PoUnit));
                    }
                    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 != null)
                    {
                        q = q.Where(p => p.PackQty == p_entity.PackQty);
                    }
                    if (p_entity.State != null)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.InvoiceNum))
                    {
                        q = q.Where(p => p.InvoiceNum.Contains(p_entity.InvoiceNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.ExpressNum))
                    {
                        q = q.Where(p => p.ExpressNum.Contains(p_entity.ExpressNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    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 (p_entity.Tax != null)
                    {
                        q = q.Where(p => p.Tax == p_entity.Tax);
                    }
                    if (!string.IsNullOrEmpty(p_entity.RecvBillNum))
                    {
                        q = q.Where(p => p.RecvBillNum.Contains(p_entity.RecvBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartDesc1))
                    {
                        q = q.Where(p => p.PartDesc1.Contains(p_entity.PartDesc1));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    q = q.Where(p => p.IsRed == p_entity.IsRed);

                    _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_INVOICE_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_INVOICE_CONTROLLER), "Get_V_TB_INVOICE_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_INVOICE_CONTROLLER), "Get_V_TB_INVOICE_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_INVOICE_CONTROLLER), "Get_V_TB_INVOICE_DETAIL_List", e.Message);
                throw e;
            }

        }


        public static ResultObject<bool> CREATE_TB_INVOICE(V_TB_INVOICE p_entity,List<V_TB_RECEIVE_LIST> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _tax=db.TA_VENDER.Where(p => p.VendId == p_entity.VendId).Select(p => p.Tax).FirstOrDefault();
                    var _ls=p_list.Where(p => p.BillType_DESC == "索赔单").ToList();
                    TB_INVOICE invoice = new TB_INVOICE();
                    invoice.InvcBillNum = SCP_BILLCODE_CONTROLLER.MakeInvoiceCode();
                    invoice.VendId = p_entity.VendId;
                    invoice.CreateTime = DateTime.Now;
                    invoice.InvoiceNum = "";
                    invoice.ExpressNum = "";
                    invoice.Remark = p_entity.Remark;
                    invoice.CreateUser = p_entity.CreateUser;
                    invoice.CreateTime = DateTime.Now;
                    invoice.Site = p_entity.Site;
                    invoice.State = (int)InvoiceState.New;
                    invoice.IsDeleted = false;
                    invoice.GUID = Guid.NewGuid();
                    invoice.Tax = p_entity.Tax;
                    invoice.IsRed = false;

                    if (_ls.Count > 0)
                    {
                        invoice.ContractPrice =0- _ls.Sum(p=>p.Price);
                    }
                    else
                    {
                        invoice.ContractPrice = 0;
                    }
                    invoice.BlancePrice = p_entity.BlancePrice;
                    db.TB_INVOICE.AddOrUpdate(invoice);
                    
                    p_list.ForEach(p => {

                        TB_INVOICE_DETAIL invocieDetail = new TB_INVOICE_DETAIL();
                        invocieDetail.InvcBillNum= invoice.InvcBillNum;
                        invocieDetail.AsnBillNum = p.AsnBillNum;
                        invocieDetail.PoBillNum = p.PoBillNum;
                        invocieDetail.PoLineNum = p.PoLine;
                        invocieDetail.RecvBillNum = p.RecvBillNum;
                        invocieDetail.ErpRecvBillNum = p.ErpRecvBillNum;
                        invocieDetail.CreateUser = invoice.CreateUser;
                        invocieDetail.CreateTime = invoice.CreateTime;
                        invocieDetail.PoUnit = p.PoUnit; //自己改数据库
                        //invocieDetail.LocUnit = p.LocUnit;//自己改数据库
                        invocieDetail.PartCode = p.PartCode;
                        invocieDetail.Price = p.Price;//自己改数据库
                        invocieDetail.Batch = p.Batch;
                        invocieDetail.VendBatch = p.VendBatch;
                        invocieDetail.Qty = p.Qty;
                        invocieDetail.Currency = p.Currency;//自己改数据库
                        invocieDetail.IsDeleted = false;
                        invocieDetail.State = (int)InvoiceState.New;
                        invocieDetail.GUID = Guid.NewGuid();
                        invocieDetail.Remark = p.Remark;
                        invocieDetail.IsRed = false;
                        db.TB_INVOICE_DETAIL.AddOrUpdate(invocieDetail);

                    });

                    #region 采购员代办任务新
                    //TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                    //_item.ROLE_NAME = "采购人员";
                    //_item.ITEM_ADDRESS = invoice.Site;
                    //_item.ITEM_NO = invoice.InvcBillNum;
                    //_item.ITEM_CONTENT = "新的采购发票申请!";
                    //_item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.APPLY_INVOICE;
                    //_item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                    //_item.SENDER = invoice.CreateUser;
                    //_item.VEND_ID = invoice.VendId;
                    //_item.SENDING_TIME = DateTime.Now;
                    ////_item.ITEM_ADDRESS = _entity.Site;
                    //_item.GUID = Guid.NewGuid();
                    //db.TB_PENING_ITEMS.Add(_item);
                    #endregion

                    if (db.SaveChanges() != -1)
                    {                        
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", 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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", 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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", 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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> SAVE_TB_INVOICE_STATE(string p_billno, InvoiceState p_state)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _entity = db.TB_INVOICE.Where(p => p.InvcBillNum == p_billno).FirstOrDefault();
                    if (p_state == InvoiceState.Apply)
                    {
                       
                        #region 采购员代办任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "采购人员";
                        _item.ITEM_ADDRESS = _entity.Site;
                        _item.ITEM_NO = p_billno;
                        _item.ITEM_CONTENT = "新的采购发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.APPLY_INVOICE;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                    }
                    if (p_state == InvoiceState.CheckFail)
                    {
                        #region 供应商代办采购退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = p_billno;
                        _item.ITEM_CONTENT = "采购审核退回发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.PO_AUDIT_BACK;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                    }
                    if (p_state == InvoiceState.CheckSuccess)
                    {
                        #region 供应商代办采购退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = p_billno;
                        _item.ITEM_CONTENT = "采购审核通过发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.PO_AUDIT_PASS;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                        List<TB_ASN> _lists = db.TB_ASN.Where(p => p.AsnBillNum == "" && p.IsDeleted == false).ToList();//p_asnBillNum
                        if (_lists.Count > 0)
                        {
                            _lists.ForEach(itm => itm.State = (int)AsnState.Receive);
                            db.TB_ASN.AddOrUpdate(p => p.UID, _lists.ToArray());
                            var _entitys = _lists.FirstOrDefault();
                            var _asnList = db.TB_ASN.Where(p => p.AskBillNum == _entitys.AskBillNum && p.IsDeleted == false);
                            var _count = _asnList.Count(p => p.State == (int)AsnState.Receive);
                            if (_asnList.Count() == _count)
                            {
                                var _askList = db.TB_ASK.Where(p => p.AskBillNum == _entitys.AskBillNum && p.IsDeleted == false).ToList();
                                _askList.ForEach(itm => itm.State = (int)AskState.Receive);
                                db.TB_ASK.AddOrUpdate(p => p.UID, _askList.ToArray());
                            }
                        }
                    }
                    if (p_state == InvoiceState.FinanceFail)
                    {
                        #region 财务审核退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = p_billno;
                        _item.ITEM_CONTENT = "财务审核退回发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.FC_AUDIT_BACK;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion


                    }
                    if (p_state == InvoiceState.FinanceReceive)
                    {

                        var _ary=db.TB_PENING_ITEMS.Where(itm => itm.INVOICE_NO == _entity.InvcBillNum).ToArray();
                        db.TB_PENING_ITEMS.RemoveRange(_ary);

                        #region 财务审核通过任务新

                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = p_billno;
                        _item.ITEM_CONTENT = "财务审核接收发票!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.FC_AUDIT_PASS;
                        _item.ITEM_STATE = (int)PENDING_STATE.COMPLETED;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion


                    }
                    if (p_state == InvoiceState.Mail)
                    {
                        #region 财务审核通过任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "财务人员";
                        _item.ITEM_NO = p_billno;
                        _item.ITEM_CONTENT = "财务审核接收发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.NEW_ASK;
                        _item.ITEM_STATE = (int)PENDING_STATE.COMPLETED;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                         #endregion

                    }

                    var _list = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == p_billno).ToList();
                    _list.ForEach(p => {
                        p.State = (int)p_state;

                    });

                    _entity.State = (int)p_state;

                    if (p_state == InvoiceState.Reject)
                    {
                        _entity.State = (int)p_state;
                        _entity.IsDeleted = true;

                        _list = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == p_billno).ToList();
                        _list.ForEach(p => {
                            p.State = (int)p_state;
                            p.IsDeleted = true;
                        });
                    }

                    db.TB_INVOICE_DETAIL.AddOrUpdate(p => p.UID, _list.ToArray());
                    db.TB_INVOICE.AddOrUpdate(p => p.UID,_entity);

                    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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_STATE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }




        public static ResultObject<bool> SAVE_TB_INVOICE_STATE(V_TB_INVOICE invoice, InvoiceState p_state,string p_username="")
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _entity = db.TB_INVOICE.Where(p => p.InvcBillNum == invoice.InvcBillNum).FirstOrDefault();
                    if (p_state == InvoiceState.Apply)
                    {

                        #region 采购员代办任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "采购负责人";
                        _item.ITEM_ADDRESS = _entity.Site;
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "新的采购发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.APPLY_INVOICE;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = _entity.CreateUser;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                        _entity.InvoiceNum = invoice.InvoiceNum;
                        _entity.ExpressNum = invoice.ExpressNum;
                      
                        _entity.ContractPrice = invoice.ContractPrice;
                        _entity.BlancePrice = invoice.BlancePrice;
                        _entity.DiscountPrice = invoice.DiscountPrice;
                    }
                    if (p_state == InvoiceState.CheckFail)
                    {
                        #region 供应商代办采购退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "采购审核退回发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.PO_AUDIT_BACK;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = p_username;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                    }
                    if (p_state == InvoiceState.CheckSuccess)
                    {
                        #region 供应商代办采购退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "采购审核通过发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.PO_AUDIT_PASS;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = p_username;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                        TB_INVOICE_DETAIL detail = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == invoice.InvcBillNum).FirstOrDefault();
                        if (detail != null)
                        {
                            List<TB_ASN> _lists = db.TB_ASN.Where(p => p.AsnBillNum == detail.AsnBillNum && p.IsDeleted == false).ToList();//p_asnBillNum
                            if (_lists.Count > 0)
                            {
                                _lists.ForEach(itm => itm.State = (int)AsnState.Receive);
                                db.TB_ASN.AddOrUpdate(p => p.UID, _lists.ToArray());
                                var _entitys = _lists.FirstOrDefault();
                                var _asnList = db.TB_ASN.Where(p => p.AskBillNum == _entitys.AskBillNum && p.IsDeleted == false);
                                var _count = _asnList.Count(p => p.State == (int)AsnState.Receive);
                                if (_asnList.Count() == _count)
                                {
                                    var _askList = db.TB_ASK.Where(p => p.AskBillNum == _entitys.AskBillNum && p.IsDeleted == false).ToList();
                                    _askList.ForEach(itm => itm.State = (int)AskState.Receive);
                                    db.TB_ASK.AddOrUpdate(p => p.UID, _askList.ToArray());
                                }
                            }
                        }
                    }
                    if (p_state == InvoiceState.FinanceFail)
                    {
                        #region 财务审核退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "财务审核退回发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.FC_AUDIT_BACK;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = p_username;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion


                    }
                    if (p_state == InvoiceState.FinanceReceive)
                    {

                        var _ary = db.TB_PENING_ITEMS.Where(itm => itm.INVOICE_NO == _entity.InvcBillNum).ToArray();
                        db.TB_PENING_ITEMS.RemoveRange(_ary);

                        #region 财务审核通过任务新

                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "财务审核接收发票!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.FC_AUDIT_PASS;
                        _item.ITEM_STATE = (int)PENDING_STATE.COMPLETED;
                        _item.SENDER = p_username;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion


                    }
                    if (p_state == InvoiceState.Mail)
                    {
                        #region 财务审核通过任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "财务人员";
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "财务审核接收发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.NEW_ASK;
                        _item.ITEM_STATE = (int)PENDING_STATE.COMPLETED;
                        _item.SENDER = p_username;
                        _item.VEND_ID = _entity.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        //_item.ITEM_ADDRESS = _entity.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                        _entity.InvoiceNum = invoice.InvoiceNum;
                        _entity.ExpressNum = invoice.ExpressNum;
                        if (invoice.UpdateTime != null)
                        {
                            _entity.UpdateTime = invoice.UpdateTime.Value;
                        }
                        _entity.ContractPrice = invoice.ContractPrice;
                        _entity.BlancePrice = invoice.BlancePrice;
                        _entity.DiscountPrice = invoice.DiscountPrice;
                    }

                    var _list = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == invoice.InvcBillNum).ToList();
                    _list.ForEach(p => {
                        p.State = (int)p_state;

                    });

                    _entity.State = (int)p_state;

                    if (p_state == InvoiceState.Reject)
                    {
                        _entity.State = (int)p_state;
                        _entity.IsDeleted = true;

                        _list = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == invoice.InvcBillNum).ToList();
                        _list.ForEach(p => {
                            p.State = (int)p_state;
                            p.IsDeleted = true;
                        });
                    }

                    db.TB_INVOICE_DETAIL.AddOrUpdate(p => p.UID, _list.ToArray());
                    db.TB_INVOICE.AddOrUpdate(p => p.UID, _entity);

                    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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_STATE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public ResultObject<bool> Del_TB_INVOICE(List<TB_INVOICE> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TB_INVOICE.Remove(itm);
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "Del_TB_INVOICE", 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_INVOICE_CONTROLLER), "Del_TB_INVOICE", 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_INVOICE_CONTROLLER), "Del_TB_INVOICE", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Del_TB_INVOICE", e.Message); throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> SAVE_TB_INVOICE_APPLY(V_TB_INVOICE p_invoice, List<V_TB_INVOICE_DETAIL> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _bill=db.TB_INVOICE.Where(itm => itm.InvcBillNum == p_invoice.InvcBillNum).FirstOrDefault();
                    _bill.InvoiceNum = p_invoice.InvoiceNum;
                    _bill.ExpressNum = p_invoice.ExpressNum;
                    _bill.ContractPrice = p_invoice.ContractPrice;
                    _bill.BlancePrice = p_invoice.BlancePrice;
                    _bill.DiscountPrice = p_invoice.DiscountPrice;
                    _bill.DiscountRemark = p_invoice.DiscountRemark;
                    _bill.Tax = p_invoice.Tax;
                    _bill.Remark = p_invoice.Remark;
                    _bill.State = (int)p_invoice.State;
                    if (p_invoice.UpdateTime != null)
                    {
                        _bill.UpdateTime = p_invoice.UpdateTime;
                    }
                    db.TB_INVOICE.AddOrUpdate(p => p.InvcBillNum, _bill);
                    p_list.ForEach(p => {
                        var _detail=db.TB_INVOICE_DETAIL.Where(itm => itm.UID == p.UID).FirstOrDefault();
                        _detail.State =(int)p.State;
                        _detail.Qty = p.Qty;
                        _detail.Price = p.Price;
                        _detail.ContractPrice = p.ContractPrice;
                        _detail.BlancePrice = p.BlancePrice;
                        _detail.DiscountPrice = p.DiscountPrice;
                        _detail.DiscountRemark = p.DiscountRemark;
                        if (_detail.Qty == 0)
                        {
                            _detail.State = (int)InvoiceState.Reject;
                            _detail.IsDeleted = true; 
                        }
                        _detail.Remark = p.Remark;
                        db.TB_INVOICE_DETAIL.AddOrUpdate(itm=>itm.UID,_detail);
                    });

                    #region 供应商代办采购退回任务新
                    TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                    _item.ROLE_NAME = "供应商";
                    _item.ITEM_NO = _bill.InvcBillNum;
                    _item.ITEM_CONTENT = "采购审核退回发票申请!";
                    _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.PO_AUDIT_BACK;
                    _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                    _item.SENDER = _bill.CreateUser;
                    _item.VEND_ID = _bill.VendId;
                    _item.SENDING_TIME = DateTime.Now;
                    _item.ITEM_ADDRESS = _bill.Site;
                    _item.GUID = Guid.NewGuid();
                    db.TB_PENING_ITEMS.Add(_item);
                    #endregion

                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        public static ResultObject<bool> SAVE_TB_INVOICE_APPLY2(V_TB_INVOICE_RED p_invoice, List<V_TB_INVOICE_DETAIL_RED> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _bill = db.TB_INVOICE.Where(itm => itm.InvcBillNum == p_invoice.InvcBillNum && itm.IsRed==true).FirstOrDefault();
                    _bill.InvoiceNum = p_invoice.InvoiceNum;
                    _bill.ExpressNum = p_invoice.ExpressNum;
                    _bill.ContractPrice = p_invoice.ContractPrice;
                    _bill.BlancePrice = p_invoice.BlancePrice;
                    _bill.DiscountPrice = p_invoice.DiscountPrice;
                    _bill.DiscountRemark = p_invoice.DiscountRemark;
                    _bill.Remark = p_invoice.Remark;
                    _bill.State = (int)p_invoice.State;
                    db.TB_INVOICE.AddOrUpdate(p => p.UID, _bill);
                    p_list.ForEach(p => {
                        var _detail = db.TB_INVOICE_DETAIL.Where(itm => itm.UID == p.UID).FirstOrDefault();
                        _detail.State = (int)p.State;
                        _detail.Qty = p.Qty;
                        _detail.Price = p.Price;
                        _detail.ContractPrice = p.ContractPrice;
                        _detail.BlancePrice = p.BlancePrice;
                        _detail.DiscountPrice = p.DiscountPrice;
                        _detail.DiscountRemark = p.DiscountRemark;
                        //if (_detail.Qty == 0)
                        //{
                        //    _detail.State = (int)InvoiceState.Reject;
                        //    _detail.IsDeleted = true;
                        //}
                        _detail.Remark = p.Remark;
                        db.TB_INVOICE_DETAIL.AddOrUpdate(itm => itm.UID, _detail);
                    });

                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> SAVE_TB_INVOICE_RED(V_TB_INVOICE p_invoice, List<V_TB_INVOICE_DETAIL> p_list)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
             
                    TB_INVOICE _bill = db.TB_INVOICE.Where(itm => itm.InvcBillNum == p_invoice.InvcBillNum && itm.IsDeleted==false).FirstOrDefault();


                    if (_bill != null)
                    {

                        _bill.InvcBillNum = p_invoice.InvcBillNum;
                        _bill.Site = p_invoice.Site;
                        _bill.InvoiceNum = p_invoice.InvoiceNum;
                        _bill.ExpressNum = p_invoice.ExpressNum;
                        _bill.VendId = p_invoice.VendId;
                        _bill.Tax = p_invoice.Tax;
                        _bill.State = (int)p_invoice.State;
                        _bill.Remark = p_invoice.Remark;
                        if (p_invoice.CreateTime != null)
                        {
                            _bill.CreateTime = DateTime.Parse(p_invoice.CreateTime.ToString());
                        }
                        _bill.CreateUser = p_invoice.CreateUser;
                        if (p_invoice.UpdateTime != null)
                        {
                            _bill.UpdateTime = DateTime.Parse(p_invoice.UpdateTime.ToString());
                        }
                        _bill.UpdateUser = p_invoice.UpdateUser;
                        _bill.UpdateInfo = p_invoice.UpdateInfo;
                        _bill.IsDeleted = p_invoice.IsDeleted;
                        _bill.GUID = p_invoice.GUID;
                        _bill.ContractPrice = p_invoice.ContractPrice;
                        _bill.BlancePrice = p_invoice.BlancePrice;
                        _bill.DiscountPrice = p_invoice.DiscountPrice;
                        _bill.DiscountRemark = p_invoice.DiscountRemark;
                        _bill.IsRed = true;

                        db.TB_INVOICE.AddOrUpdate(itm => itm.UID, _bill);

                        p_list.ForEach(p =>
                        {
                            TB_INVOICE_DETAIL _detail = new TB_INVOICE_DETAIL();
                            _detail.InvcBillNum = p.InvcBillNum;
                            _detail.RecvBillNum = p.RecvBillNum;
                            _detail.AsnBillNum = p.AsnBillNum;
                            _detail.PoBillNum = p.PoBillNum;
                            _detail.PoLineNum = p.PoLineNum;
                            _detail.PartCode = p.PartCode;
                            _detail.Batch = p.Batch;
                            if (p.ProduceDate != null)
                            {
                                _detail.ProduceDate = DateTime.Parse(p.ProduceDate.ToString());
                            }
                            _detail.VendBatch = p.VendBatch;
                            _detail.Qty = p.Qty;
                            _detail.PoUnit = p.PoUnit;
                            _detail.Price = p.Price;
                            _detail.Currency = p.Currency;
                            if (p.PackQty != null)
                            {
                                _detail.PackQty = decimal.Parse(p.PackQty.ToString());
                            }
                            if (p.State != null)
                            {
                                _detail.State = int.Parse(p.State.ToString());
                            }
                            _detail.Remark = p.Remark;
                            if (p.CreateTime != null)
                            {
                                _detail.CreateTime = DateTime.Parse(p.CreateTime.ToString());
                            }
                            _detail.CreateUser = p.CreateUser;
                            if (p.UpdateTime != null)
                            {
                                _detail.UpdateTime = DateTime.Parse(p.UpdateTime.ToString());
                            }
                            _detail.UpdateUser = p.UpdateUser;
                            _detail.UpdateInfo = p.UpdateInfo;
                            _detail.IsDeleted = p.IsDeleted;
                            _detail.GUID = p.GUID;
                            if (p.BeginTime != null)
                            {
                                _detail.BeginTime = DateTime.Parse(p.BeginTime.ToString());
                            }
                            _detail.ContractPrice = p.ContractPrice;
                            _detail.BlancePrice = p.BlancePrice;
                            _detail.DiscountPrice = p.DiscountPrice;
                            _detail.DiscountRemark = p.DiscountRemark;
                            _detail.IsRed =true;

                            db.TB_INVOICE_DETAIL.Add(_detail);
                        });

                        if (db.SaveChanges() != -1)
                        {
                            _ret.State = ReturnStatus.Succeed;
                            _ret.Result = true;
                        }
                        else
                        {
                            _ret.State = ReturnStatus.Failed;
                            _ret.Result = false;
                        }
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "SAVE_TB_INVOICE", "发票记录未查询到");
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", 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_INVOICE_CONTROLLER), "SAVE_TB_INVOICE_APPLY", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }


        public ResultObject<bool> Del_TB_INVOICE_DETAIL(List<TB_INVOICE_DETAIL> p_entitys)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    foreach (var itm in p_entitys)
                    {
                        db.TB_INVOICE_DETAIL.Remove(itm);
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "Del_TB_INVOICE_DETAIL", 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_INVOICE_CONTROLLER), "Del_TB_INVOICE_DETAIL", 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_INVOICE_CONTROLLER), "Del_TB_INVOICE_DETAIL", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "Del_TB_INVOICE_DETAIL", e.Message); throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> CaiWu_Return_Reason(string p_InvcBillNum,string p_Memo)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    TB_INVOICE invoice = db.TB_INVOICE.Where(p => p.InvcBillNum == p_InvcBillNum).FirstOrDefault();

                    if (invoice != null)
                    {
                        invoice.State = (int)InvoiceState.FinanceFail;
                        invoice.Remark = p_Memo;
                        invoice.InvoiceNum = "";
                        invoice.ExpressNum = "";

                        db.TB_INVOICE.AddOrUpdate(invoice);

                        List<TB_INVOICE_DETAIL> invoicedetail = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == p_InvcBillNum).ToList();

                        foreach (TB_INVOICE_DETAIL det in invoicedetail)
                        {
                            det.State = (int)InvoiceState.FinanceFail;
                        }

                        #region 财务审核退回任务新
                        TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                        _item.ROLE_NAME = "供应商";
                        _item.ITEM_NO = invoice.InvcBillNum;
                        _item.ITEM_CONTENT = "财务审核退回发票申请!";
                        _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.FC_AUDIT_BACK;
                        _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        _item.SENDER = invoice.CreateUser;
                        _item.VEND_ID = invoice.VendId;
                        _item.SENDING_TIME = DateTime.Now;
                        _item.ITEM_ADDRESS = invoice.Site;
                        _item.GUID = Guid.NewGuid();
                        db.TB_PENING_ITEMS.Add(_item);
                        #endregion

                        if (db.SaveChanges() != -1)
                        {
                            _ret.State = ReturnStatus.Succeed;
                            _ret.Result = true;
                            _ret.Message = invoice.VendId;
                        }
                        else
                        {
                            _ret.State = ReturnStatus.Failed;
                            _ret.Result = false;
                            _ret.Message = invoice.VendId;
                        }
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                        _ret.Message = invoice.VendId;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "CaiWu_Return_Reason", 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_INVOICE_CONTROLLER), "CaiWu_Return_Reason", 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_INVOICE_CONTROLLER), "CaiWu_Return_Reason", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "CaiWu_Return_Reason", e.Message); throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> UpdateMemoByInvcBillNum(string p_InvcBillNum, string p_Memo)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    TB_INVOICE invoice = db.TB_INVOICE.Where(p => p.InvcBillNum == p_InvcBillNum).FirstOrDefault();

                    invoice.Remark = p_Memo;
                   

                    db.TB_INVOICE.AddOrUpdate(invoice);

                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", 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_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", 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_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", e.Message); throw e;
            }
            return _ret;
        }


        public static ResultObject<bool> UpdateMemoByInvcBillNum(string p_InvcBillNum, string p_Memo, decimal p_blan, string p_inv,DateTime p_time)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    TB_INVOICE invoice = db.TB_INVOICE.Where(p => p.InvcBillNum == p_InvcBillNum).FirstOrDefault();

                    invoice.Remark = p_Memo;
                    invoice.BlancePrice = p_blan;
                    invoice.InvoiceNum = p_inv;
                    invoice.UpdateTime = p_time;

                    db.TB_INVOICE.AddOrUpdate(invoice);

                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", 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_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", 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_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", 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.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "UpdateMemoByInvcBillNum", e.Message); throw e;
            }
            return _ret;
        }




        public static ResultObject<bool> SET_INVOICE_STATE(string p_InvcBillNum, InvoiceState p_state)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    TB_INVOICE invoice = db.TB_INVOICE.Where(p => p.InvcBillNum == p_InvcBillNum).FirstOrDefault();

                    if (invoice != null)
                    {
                        invoice.State = (int)p_state;

                        db.TB_INVOICE.AddOrUpdate(invoice);

                        List<TB_INVOICE_DETAIL> invoicedetail = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == p_InvcBillNum).ToList();

                        foreach (TB_INVOICE_DETAIL det in invoicedetail)
                        {
                            det.State = (int)p_state;
                        }

                        if (p_state == InvoiceState.Mail)
                        {
                            db.Database.ExecuteSqlCommand(string.Format("delete   FROM  TS_UNI_API where InterfaceType = 'invoice' and billnum = '{0}'", p_InvcBillNum));
                        }
                            //财务审核通过,把所有代办信息设为已办状态
                         if (p_state == InvoiceState.FinanceReceive)
                        {
                            List<TB_PENING_ITEMS> items = db.TB_PENING_ITEMS.Where(p => p.ITEM_NO == p_InvcBillNum).ToList();

                            foreach (TB_PENING_ITEMS item in items)
                            {
                                item.ITEM_STATE = (int)PENDING_STATE.COMPLETED;
                            }


                            List<V_TB_INVOICE_DETAIL> _ls = db.V_TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == p_InvcBillNum).ToList();
                            V_TB_INVOICE _bill= db.V_TB_INVOICE.Where(p => p.InvcBillNum == p_InvcBillNum).FirstOrDefault();
                            foreach (V_TB_INVOICE_DETAIL itm in _ls)
                            {
                                
                                TS_UNI_API _api = UniApiController.CreateBy(_bill,itm ,UniApiType.Invoice);
                                _api.State = 1;
                                db.TS_UNI_API.AddOrUpdate(_api);
                                itm.State = (int)p_state;
                            }

                        }
                     
                        //财务取消收票,把所有代办信息设为等待状态
                        //if (p_state == InvoiceState.Mail)
                        //{
                        //    List<TB_PENING_ITEMS> items = db.TB_PENING_ITEMS.Where(p => p.ITEM_NO == p_InvcBillNum).ToList();

                        //    foreach (TB_PENING_ITEMS item in items)
                        //    {
                        //        item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                        //    }
                        //}

                        if (db.SaveChanges() != -1)
                        {
                            _ret.State = ReturnStatus.Succeed;
                            _ret.Result = true;
                            _ret.Message = invoice.VendId;
                        }
                        else
                        {
                            _ret.State = ReturnStatus.Failed;
                            _ret.Result = false;
                            _ret.Message = invoice.VendId;
                        }
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                        _ret.Message = invoice.VendId;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "SET_INVOICE_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_INVOICE_CONTROLLER), "SET_INVOICE_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_INVOICE_CONTROLLER), "SET_INVOICE_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;
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(SCP_INVOICE_CONTROLLER), "SET_INVOICE_STATE", e.Message); throw e;
            }
            return _ret;
        }

        public static ResultObject<bool> Add_New_Red_Invoice(V_TB_INVOICE p_entity)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _invoice = db.TB_INVOICE.Where(p => p.InvcBillNum == p_entity.InvcBillNum).FirstOrDefault();
                    var _invoicedetail = db.TB_INVOICE_DETAIL.Where(p => p.InvcBillNum == p_entity.InvcBillNum).FirstOrDefault();

                    if(_invoice !=null)
                    {
                        if (_invoicedetail != null)
                        {
                            TB_INVOICE_DETAIL invocieDetail = new TB_INVOICE_DETAIL();
                            invocieDetail.InvcBillNum = _invoicedetail.InvcBillNum;
                            //invocieDetail.RecvBillNum = _invoicedetail.RecvBillNum;
                            //invocieDetail.AsnBillNum = _invoicedetail.AsnBillNum;
                            invocieDetail.PoBillNum = _invoicedetail.PoBillNum;
                            invocieDetail.PoLineNum = 0;// _invoicedetail.PoLineNum;
                            invocieDetail.PartCode = ""; // _invoicedetail.PartCode;
                            invocieDetail.Batch = "";// _invoicedetail.Batch;

                            //invocieDetail.VendBatch = _invoicedetail.VendBatch;
                            invocieDetail.Qty = 0;
                            //invocieDetail.PoUnit = _invoicedetail.PoUnit; //自己改数据库
                            invocieDetail.Price = 0;//自己改数据库
                            invocieDetail.Currency = _invoicedetail.Currency;//自己改数据库
                            invocieDetail.State = _invoicedetail.State;
                            invocieDetail.Remark = "";//_invoicedetail.Remark;
                            invocieDetail.CreateUser = _invoicedetail.CreateUser;
                            invocieDetail.CreateTime = _invoicedetail.CreateTime;
                            //invocieDetail.LocUnit = p.LocUnit;//自己改数据库
                            invocieDetail.IsDeleted = false;
                            invocieDetail.GUID = Guid.NewGuid();
                            invocieDetail.IsRed = false;

                            db.TB_INVOICE_DETAIL.Add(invocieDetail);
                        }
                        else
                        {
                            TB_INVOICE_DETAIL invocieDetail = new TB_INVOICE_DETAIL();
                            invocieDetail.InvcBillNum = _invoice.InvcBillNum;
                            //invocieDetail.RecvBillNum = _invoicedetail.RecvBillNum;
                            //invocieDetail.AsnBillNum = _invoicedetail.AsnBillNum;
                            invocieDetail.PoBillNum = "";// _invoice.PoBillNum;
                            invocieDetail.PoLineNum = 0;// _invoicedetail.PoLineNum;
                            invocieDetail.PartCode = ""; // _invoicedetail.PartCode;
                            invocieDetail.Batch = "";// _invoicedetail.Batch;

                            //invocieDetail.VendBatch = _invoicedetail.VendBatch;
                            invocieDetail.Qty = 0;
                            //invocieDetail.PoUnit = _invoicedetail.PoUnit; //自己改数据库
                            invocieDetail.Price = 0;//自己改数据库
                            invocieDetail.Currency = "CNY";// _invoice.Currency;//自己改数据库
                            invocieDetail.State = _invoice.State;
                            invocieDetail.Remark = "";//_invoicedetail.Remark;
                            invocieDetail.CreateUser = _invoice.CreateUser;
                            invocieDetail.CreateTime = _invoice.CreateTime;
                            //invocieDetail.LocUnit = p.LocUnit;//自己改数据库
                            invocieDetail.IsDeleted = false;
                            invocieDetail.GUID = Guid.NewGuid();
                            invocieDetail.IsRed = false;

                            db.TB_INVOICE_DETAIL.Add(invocieDetail);
                        }
                    }

                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                    }
                }
            }
            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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", 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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", 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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", 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_INVOICE_CONTROLLER), "CREATE_TB_INVOICE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
    }
}