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

namespace CK.SCP.Controller
{
    public class SCP_REJECT_CONTROLLER
    {
        public static void Get_V_TB_REJECT_List(V_TB_REJECT p_entity, Action<ResultObject<IQueryable<V_TB_REJECT>>> p_action)
        {
            ResultObject<IQueryable<V_TB_REJECT>> _ret = new ResultObject<IQueryable<V_TB_REJECT>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_REJECT> q = db.V_TB_REJECT;

                    if (!string.IsNullOrEmpty(p_entity.RjctBillNum))
                    {
                        q = q.Where(p => p.RjctBillNum == p_entity.RjctBillNum);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    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 (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (p_entity.IsDeleted != false)
                    {
                        q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendName))
                    {
                        q = q.Where(p => p.VendName.Contains(p_entity.VendName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.OperName))
                    {
                        q = q.Where(p => p.OperName.Contains(p_entity.OperName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site_Desc))
                    {
                        q = q.Where(p => p.Site_Desc.Contains(p_entity.Site_Desc));
                    }
                    //if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    //{
                    //    q = q.Where(p => p_entity.UserInAddress.Contains(p.Address));
                    //}
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;

                    p_action(_ret);
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(V_TB_REJECT), "Get_V_TB_REJECT_List", e.Message);
                throw e;
            }

        }



        public static void Get_V_TB_REJECT_DETAIL_List(V_TB_REJECT_DETAIL p_entity, Action<ResultObject<IQueryable<V_TB_REJECT_DETAIL>>> p_action)
        {
            ResultObject<IQueryable<V_TB_REJECT_DETAIL>> _ret = new ResultObject<IQueryable<V_TB_REJECT_DETAIL>>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    IQueryable<V_TB_REJECT_DETAIL> q = db.V_TB_REJECT_DETAIL;

                    if (!string.IsNullOrEmpty(p_entity.RjctBillNum))
                    {
                        q = q.Where(p => p.RjctBillNum == p_entity.RjctBillNum);
                    }
                    if (p_entity.PoLine != 0)
                    {
                        q = q.Where(p => p.PoLine == p_entity.PoLine);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartCode))
                    {
                        q = q.Where(p => p.PartCode.Contains(p_entity.PartCode));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Batch))
                    {
                        q = q.Where(p => p.Batch.Contains(p_entity.Batch));
                    }
                    if (p_entity.Qty != 0)
                    {
                        q = q.Where(p => p.Qty == p_entity.Qty);
                    }
                  
                    if (!string.IsNullOrEmpty(p_entity.Remark))
                    {
                        q = q.Where(p => p.Remark.Contains(p_entity.Remark));
                    }
                    if (!string.IsNullOrEmpty(p_entity.CreateUser))
                    {
                        q = q.Where(p => p.CreateUser.Contains(p_entity.CreateUser));
                    }
                    if (p_entity.IsDeleted != false)
                    {
                        q = q.Where(p => p.IsDeleted == p_entity.IsDeleted);
                    }
                    if (!string.IsNullOrEmpty(p_entity.AsnBillNum))
                    {
                        q = q.Where(p => p.AsnBillNum.Contains(p_entity.AsnBillNum));
                    }
                    if (!string.IsNullOrEmpty(p_entity.Site))
                    {
                        q = q.Where(p => p.Site.Contains(p_entity.Site));
                    }
                    if (!string.IsNullOrEmpty(p_entity.VendId))
                    {
                        q = q.Where(p => p.VendId.Contains(p_entity.VendId));
                    }
                    if (!string.IsNullOrEmpty(p_entity.OperName))
                    {
                        q = q.Where(p => p.OperName.Contains(p_entity.OperName));
                    }
                    if (!string.IsNullOrEmpty(p_entity.PartDesc1))
                    {
                        q = q.Where(p => p.PartDesc1.Contains(p_entity.PartDesc1));
                    }
                    if (p_entity.State != 0)
                    {
                        q = q.Where(p => p.State == p_entity.State);
                    }
                    if (!string.IsNullOrEmpty(p_entity.PoBillNum))
                    {
                        q = q.Where(p => p.PoBillNum.Contains(p_entity.PoBillNum));
                    }
                    //if (p_entity.UserInAddress != null && p_entity.UserInAddress.Count > 0)
                    //{
                    //    q = q.Where(p => p_entity.UserInAddress.Contains(p.Address));
                    //}
                    _ret.State = ReturnStatus.Succeed;
                    _ret.Result = q;
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                _ret.ErrorList.Add(e);
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(V_TB_REJECT_DETAIL), "Get_V_TB_REJECT_DETAIL_List", e.Message);
                throw e;
            }

        }
        public static ResultObject<bool> Save_TB_REJECT_STATE(List<string> p_list, RejectState p_state)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {
                    var _ls = db.V_TB_REJECT.Where(p => p_list.Contains(p.RjctBillNum)).ToList();
                    int count = _ls.Count(p => p.State == (int)RejectState.NoReceive);
                    if (count == _ls.Count && _ls.Count > 0)
                    {
                        _ls.ForEach(p =>
                        {
                            p.State = (int)RejectState.Check;
                            var _list = db.TB_REJECT_DETAIL.Where(itm => itm.RjctBillNum == p.RjctBillNum).ToList();
                            _list.ForEach(itm => itm.State = (int)RejectState.Check);
                            db.TB_REJECT_DETAIL.AddOrUpdate(itm => itm.UID, _list.ToArray());
                            #region 退货审核提醒供应商提起发票申请
                            TB_PENING_ITEMS _item = new TB_PENING_ITEMS();
                            _item.ROLE_NAME = "供应商";
                            _item.ITEM_NO = p.RjctBillNum;
                            _item.ITEM_CONTENT = string.Format("退货单号{0}发货单号{1},已拒绝收货!", p.RjctBillNum, _ls[0].AsnBillNum);
                            _item.ITEM_TYPE = (int)PENDING_MESSAGE_TYPE.FC_AUDIT_BACK;
                            _item.ITEM_STATE = (int)PENDING_STATE.WAITING;
                            _item.SENDER = p.CreateUser;
                            _item.VEND_ID = p.VendId;
                            _item.SENDING_TIME = DateTime.Now;
                            _item.ITEM_ADDRESS = p.Site_Desc;
                            _item.GUID = Guid.NewGuid();
                            db.TB_PENING_ITEMS.Add(_item);
                            #endregion
                        }
                       );
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                        _ret.Message = "选择的记录,有不是拒收状态记录!";
                    }
                    if (db.SaveChanges() != -1)
                    {
                        _ret.State = ReturnStatus.Succeed;
                        _ret.Result = true;
                    }
                    else
                    {
                        _ret.State = ReturnStatus.Failed;
                        _ret.Result = false;
                        _ret.Message = "数据更新失败!";
                    }
                }
            }
            catch (Exception e)
            {
                _ret.State = ReturnStatus.Failed;
                LogHelper.Writlog(LogHelper.LogType.Error, typeof(V_TB_REJECT_DETAIL), "Save_TB_REJECT_STATE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
        /// <summary>
        /// 保存退货
        /// </summary>
        /// <param name="p_entity"></param>
        /// <param name="p_list"></param>
        /// <param name="currentuser"></param>
        /// <returns></returns>
        public static ResultObject<bool> Save_TB_REJECT(V_TB_ASN_DETAIL p_entity, List<V_TB_ASN_DETAIL> p_list, string currentuser)
        {
            ResultObject<bool> _ret = new ResultObject<bool>();
            var scpRcvList = new List<TB_RECEIVE>();
            var scpRcveDetailList = new List<TB_RECEIVE_DETAIL>();
            try
            {
                using (ScpEntities db = EntitiesFactory.CreateScpInstance())
                {                                 
                        TB_RECEIVE scpRcv = new TB_RECEIVE();
                        scpRcv.RecvBillNum = SCP_BILLCODE_CONTROLLER.MakeReviceCode();//退货单号                                                
                        scpRcv.State = (int)FormState.开放;
                        scpRcv.Remark = "";
                        scpRcv.CreateTime = DateTime.Now;//创建日期
                        scpRcv.CreateUser = currentuser;//创建用户
                        scpRcv.IsDeleted = false;
                        scpRcv.GUID = System.Guid.NewGuid();
                        scpRcv.BillType = 1;
                        scpRcv.PoBillNum = p_entity.PoBillNum;//采购单
                        scpRcv.AsnBillNum = p_entity.AsnBillNum;//发货单号
                        scpRcv.Site = p_entity.Site;//地点
                        scpRcv.VendId = p_entity.VendId;//供货商名称
                        scpRcv.ShipTime = DateTime.Now;//收货日期
                        scpRcvList.Add(scpRcv);
                        db.TB_RECEIVE.AddOrUpdate(p => p.UID, scpRcvList.ToArray());
                        p_list.ForEach(item =>
                        {
                            TB_RECEIVE_DETAIL scpRcvDetail = new TB_RECEIVE_DETAIL();
                            scpRcvDetail.RecvBillNum = SCP_BILLCODE_CONTROLLER.MakeReviceCode();//退货单号
                            scpRcvDetail.PoBillNum = item.PoBillNum;//采购单
                            scpRcvDetail.PoLine = item.PoLine;//订单行
                            scpRcvDetail.PartCode = item.PartCode;//零件号
                            scpRcvDetail.Batch = item.Batch;//批次
                            scpRcvDetail.VendBatch = item.VendBatch;//供应商批号
                            scpRcvDetail.PoUnit = item.PoUnit;//采购单位
                            scpRcvDetail.LocUnit = item.LocUnit;//基本单位
                            scpRcvDetail.Qty = item.RejectQty;//退货数量
                            scpRcvDetail.State = (int)FormState.开放;// (int)FormState.关闭,
                            scpRcvDetail.Remark = item.Remark;
                            scpRcvDetail.CreateTime = DateTime.Now;//创建日期
                            scpRcvDetail.CreateUser = currentuser;//创建用户
                            scpRcvDetail.IsDeleted = false;
                            scpRcvDetail.GUID = System.Guid.NewGuid();
                            scpRcvDetail.BillType = 1;
                            scpRcveDetailList.Add(scpRcvDetail);
                        });
                        db.TB_RECEIVE_DETAIL.AddOrUpdate(p => p.UID, scpRcveDetailList.ToArray());
                    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_RECIVECE_CONTROLLER), "Save_TB_RECEIVE", 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_RECIVECE_CONTROLLER), "Save_TB_RECEIVE", 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_RECIVECE_CONTROLLER), "Save_TB_RECEIVE", 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_RECIVECE_CONTROLLER), "Save_TB_RECEIVE", e.Message);
                _ret.Result = false;
                _ret.ErrorList.Add(e);
                throw e;
            }
            return _ret;
        }
    }
}