public bool UpdateOrder(OrderType order)
        {
            NSession.Update(order);
            NSession.Flush();
            return false;

        }
 public static void GetOrderRecord(OrderType order, string recordType, string Content, ISession NSession)
 {
     UserType CurrentUser = null;
     if (HttpContext.Current.Session["account"] != null)
     {
         CurrentUser = (UserType)HttpContext.Current.Session["account"];
     }
     GetOrderRecord(order.Id, order.OrderNo, recordType, Content, CurrentUser, NSession);
 }
        public bool CreateOrder(OrderType order)
        {
            NSession.Save(order.AddressInfo);
            NSession.Flush();
            order.Enabled = 1;
            order.AddressId = order.AddressInfo.Id;
            NSession.Save(order);
            NSession.Flush();
            foreach (var p in order.Products)
            {
                p.OId = order.Id;
                p.OrderNo = order.OrderNo;
                OrderHelper.CreateOrderPruduct(p, NSession);

            }
            return true;
        }
        public ActionResult EditOrderMerger()
        {
            IList<OrderType> orderTypes =
                NSession.CreateQuery(
                    "from OrderType where Status='待处理' and Platform='Ebay' and Enabled=1 and BuyerName in (select BuyerName from OrderType where Status='待处理'  and Platform='Ebay' and Enabled=1   group by BuyerName,Country,Account having count (BuyerName)>1)")
                    .List<OrderType>();
            string ids = "";
            foreach (OrderType order in orderTypes)
            {
                ids += order.AddressId + ",";
            }
            List<OrderAddressType> orderAddressTypes =
                NSession.CreateQuery("from OrderAddressType where Id in(" + ids.Trim(',') + ")").List<OrderAddressType>()
                    .ToList();

            foreach (OrderType o in orderTypes)
            {
                o.AddressInfo = orderAddressTypes.Find(x => x.Id == o.AddressId);
            }
            var strs = new List<int>();
            var copyOrders = new List<OrderType>(orderTypes.ToArray());
            foreach (OrderType o in orderTypes)
            {
                if (strs.Contains(o.Id))
                    continue;
                List<OrderType> orders =
                    copyOrders.Where(
                        x =>
                        x.BuyerName == o.BuyerName && x.Country == o.Country && x.Account == o.Account &&
                        x.AddressInfo.Street == o.AddressInfo.Street).ToList();
                var order = new OrderType();

                if (orders.Count > 1)
                {
                    NSession.Clear();
                    order = CloneObjectEx(o) as OrderType;
                    order.Id = 0;
                    order.OrderNo = Utilities.GetOrderNo(NSession);
                    order.Amount = 0;
                    order.IsMerger = 1;
                    order.Enabled = 1;
                    NSession.SaveOrUpdate(order);
                    NSession.Flush();
                    foreach (OrderType orderType in orders)
                    {
                        strs.Add(orderType.Id);
                        order.Amount += orderType.Amount;
                        order.OrderExNo += "|" + orderType.OrderExNo;
                        order.TId += "|" + orderType.TId;
                        orderType.MId = order.Id;
                        orderType.IsMerger = 1;
                        orderType.Enabled = 0;
                        NSession.Clear();
                        NSession.SaveOrUpdate(orderType);
                        NSession.Flush();
                        IList<OrderProductType> orderProductTypes =
                            NSession.CreateQuery(" from OrderProductType where OId=" + orderType.Id).List
                                <OrderProductType>();
                        foreach (OrderProductType orderProductType in orderProductTypes)
                        {
                            orderProductType.Id = 0;
                            orderProductType.OId = order.Id;
                            orderProductType.OrderNo = order.OrderNo;
                            NSession.Clear();
                            NSession.SaveOrUpdate(orderProductType);
                            NSession.Flush();
                        }
                    }
                    NSession.Clear();
                    NSession.SaveOrUpdate(order);
                    NSession.Flush();
                }
            }
            return Json(new { IsSuccess = true });
        }
        private void UploadTrackCode(OrderType o)
        {


            if (o.Platform == PlatformEnum.Ebay.ToString())
            {
                if (o.TrackCode != null)
                {
                    if (!o.TrackCode.StartsWith("LK"))
                        EBayUtil.EbayUploadTrackCode(o.Account, o);
                }
            }
            if (o.Platform == PlatformEnum.SMT.ToString())
            {
                string CarrierUsed = "";
                IList<logisticsSetupType> setups = NSession.CreateQuery("from  logisticsSetupType where LId in (select ParentID from LogisticsModeType where LogisticsCode='" + o.LogisticMode + "') and Platform='SMT'").List<logisticsSetupType>();
                if (setups.Count > 0)
                {
                    CarrierUsed = setups[0].SetupName;
                }
                else
                {

                }
                IList<AccountType> accounts = NSession.CreateQuery("from AccountType where AccountName='" + o.Account + "'").SetMaxResults(1).
                  List<AccountType>();
                if (accounts.Count > 0)
                {
                    AccountType accountType = accounts[0];
                    if (string.IsNullOrEmpty(accountType.ApiSecret))
                    {
                        accountType.ApiSecret = AliUtil.RefreshToken(accountType);
                        NSession.Save(accountType);
                        NSession.Flush();
                    }
                    string c = AliUtil.sellerShipment(accountType.ApiSecret, o.OrderExNo, o.TrackCode, CarrierUsed, true);
                    if (c.IndexOf("Request need user authorized") != -1)
                    {
                        accountType.ApiSecret = AliUtil.RefreshToken(accountType);
                        NSession.Save(accountType);
                        NSession.Flush();
                        AliUtil.sellerShipment(accountType.ApiSecret, o.OrderExNo, o.TrackCode, CarrierUsed, true);
                    }
                }


            }
        }
        private static void AddToOrderData(OrderType order, List<OrderData> os)
        {
            OrderData o = new OrderData();

            if (order != null)
            {
                o.OrderNo = order.OrderNo;
                o.OrderExNo = order.OrderExNo;
                o.TrackCode = order.TrackCode;
                o.Weight = order.Weight;
                o.RMB = order.RMB;
                o.Country = order.Country;
                o.CurrencyCode = order.CurrencyCode;
                o.LogisticMode = order.LogisticMode;
                o.OrderAmount = order.Amount;

                o.Status = order.Status;
                o.OrderType = "正常";
                if (order.IsRepeat == 1)
                    o.OrderType = "重发";
                if (order.IsSplit == 1)
                    o.OrderType += "拆包";
                o.Country = order.Country;
                o.SendOn = order.ScanningOn;
                o.Freight = order.Freight;
                o.Account = order.Account;
                o.Platform = order.Platform;
            }
            os.Add(o);
        }
        public static void SaveAmount(OrderType order, List<CurrencyType> currencys, ISession NSession)
        {
            NSession.Delete("from OrderAmountType where OId=" + order.Id);
            NSession.Flush();
            CurrencyType currency = currencys.Find(p => p.CurrencyCode.ToUpper() == order.CurrencyCode.ToUpper());

            if (order.Status == "待处理")
                order.Status = OrderStatusEnum.已处理.ToString();
            order.RMB = Math.Round(Convert.ToDouble(currency.CurrencyValue) * order.Amount, 4);
            OrderAmountType orderAmount = new OrderAmountType();
            orderAmount.Account = order.Account;
            orderAmount.OrderNo = order.OrderNo;
            orderAmount.OrderExNo = order.OrderExNo;
            orderAmount.OrderAmount = order.Amount;
            orderAmount.OId = order.Id;
            order.MId = order.MId;
            orderAmount.IsRepeat = order.IsRepeat;
            orderAmount.IsSplit = order.IsSplit;
            orderAmount.ExchangeRate = Convert.ToDouble(currency.CurrencyValue);
            //总成本确认
            object obj = NSession.CreateSQLQuery(
                "select SUM(OP.Qty*p.Price) from OrderProducts OP left join Products  P On OP.SKU=p.SKU where OId=" + order.Id).
                UniqueResult();
            orderAmount.TotalCosts = Convert.ToDouble(obj);

            IList<AccountFeeType> list = NSession.CreateQuery(string.Format("from AccountFeeType where AccountId in (select Id from AccountType where AccountName='{0}' ) and AmountBegin<={1} and AmountEnd>{1} ", order.Account, order.Amount)).List<AccountFeeType>();

            foreach (var feeType in list)
            {

                object d = new DataTable().Compute(feeType.FeeFormula.Replace("T", order.Amount.ToString()), "");
                if (feeType.FeeName == "交易费")
                {
                    if (order.OrderFees > 0)
                    {
                        orderAmount.TransactionFees = order.OrderFees;
                    }
                    else
                    {
                        orderAmount.TransactionFees = Convert.ToDouble(d);
                    }

                }
                if (feeType.FeeName == "手续费")
                {
                    orderAmount.Fee = Convert.ToDouble(d);
                }
                if (feeType.FeeName == "其他费")
                {
                    orderAmount.OtherFees = Convert.ToDouble(d);
                }
            }
            orderAmount.CreateOn = order.CreateOn;
            orderAmount.ScanningOn = order.ScanningOn;
            orderAmount.CurrencyCode = order.CurrencyCode;
            orderAmount.UpdateOn = DateTime.Now;

            orderAmount.Platform = order.Platform;
            orderAmount.Country = order.Country;
            orderAmount.RMB = order.RMB;
            orderAmount.Profit = Math.Round(order.RMB - orderAmount.TotalCosts - orderAmount.OtherFees * Convert.ToDouble(currency.CurrencyValue) - orderAmount.Fee * Convert.ToDouble(currency.CurrencyValue) -
                                 orderAmount.TransactionFees * Convert.ToDouble(currency.CurrencyValue), 5);
            NSession.Save(orderAmount);
            NSession.Flush();
            if (orderAmount.IsRepeat == 1 && orderAmount.MId != 0)
            {
                NSession.CreateQuery("update OrderAmountType set SplitCount=SplitCount+1 where OId=" + orderAmount.MId).ExecuteUpdate();
                NSession.Flush();
            }
            if (orderAmount.IsSplit == 1 && orderAmount.MId != 0)
            {
                NSession.CreateQuery("update OrderAmountType set AgainCount=AgainCount+1 where OId=" + orderAmount.MId).ExecuteUpdate();
                NSession.Flush();
            }
            UpdateAmount(order, NSession);
        }
 //订单日志
 public static void GetOrderRecord(OrderType order, string recordType, string Content, UserType CurrentUser, ISession NSession)
 {
     GetOrderRecord(order.Id, order.OrderNo, recordType, Content, CurrentUser, NSession);
 }
        private void SetQuestionOrder(string subject, OrderType orderType, string content = "")
        {
            var question = new QuestionOrderType();
            question.OId = orderType.Id;
            question.OrderNo = orderType.OrderNo;
            question.Status = 0;
            question.Subjest = subject;
            if (string.IsNullOrEmpty(content))
            {
                question.Content = orderType.CutOffMemo;
            }
            else
            {
                question.Content = content;
            }

            question.CreateBy = CurrentUser.Realname;
            question.CreateOn = DateTime.Now;
            question.SolveOn = DateTime.Now;
            NSession.Save(question);
            NSession.Flush();
        }
        public ActionResult Edit(OrderType obj)
        {
            try
            {
                obj.Enabled = 1;
                OrderType obj2 = GetById(obj.Id);
                NSession.Update(obj.AddressInfo);
                NSession.Flush();
                NSession.Clear();
                obj.Country = obj.AddressInfo.Country;
                string str = Utilities.GetObjEditString(obj2, obj);
                NSession.Update(obj);
                NSession.Flush();
                NSession.Clear();
                var list = JsonConvert.DeserializeObject<List<OrderProductType>>(obj.rows);
                List<OrderProductType> pis =
                    NSession.CreateQuery("from OrderProductType where OId=" + obj.Id).List<OrderProductType>().ToList
                        <OrderProductType>();
                if (list.Count != pis.Count)
                {
                    str += "组合产品由<br>";
                    foreach (OrderProductType item in pis)
                    {
                        str += Zu1(item);
                    }
                    str += "修改为<br> ";
                    foreach (OrderProductType item in list)
                    {
                        //str += " ExSKU:" + item.ExSKU + " 名称:" + item.Title + " SKU:" + item.SKU + " 数量:" + item.Qty + " 规格:" + item.Standard + " 价格:" + item.Price + " 网址:" + item.Url + " 描述:" + item.Remark + "<br>";
                        str += Zu1(item);
                    }
                    str += "<br>";
                }
                else
                {
                    foreach (OrderProductType it in pis)
                    {
                        int check = 0;
                        foreach (OrderProductType it1 in list)
                        {
                            if (it.ExSKU == it1.ExSKU && it.Title == it1.Title && it.SKU == it1.SKU && it.Qty == it1.Qty &&
                                it.Standard == it1.Standard && it.Price == it1.Price && it.Url == it1.Url &&
                                it.Remark == it1.Remark)
                            {
                                check = 1;
                            }
                        }
                        if (check != 1)
                        {
                            str += "组合产品由<br>";
                            foreach (OrderProductType item in pis)
                            {
                                str += Zu1(item);
                            }
                            str += "修改为<br> ";
                            foreach (OrderProductType item in list)
                            {
                                str += Zu1(item);
                            }
                            str += "<br>";
                        }
                    }
                }

                NSession.CreateQuery("delete from OrderProductType where OId=" + obj.Id).ExecuteUpdate();
                foreach (OrderProductType orderProductType in list)
                {
                    orderProductType.OId = obj.Id;
                    orderProductType.OrderNo = obj.OrderNo;
                    NSession.Save(orderProductType);
                    NSession.Flush();
                }
                LoggerUtil.GetOrderRecord(obj, "修改订单", str, CurrentUser, NSession);
            }
            catch (Exception ee)
            {
                return Json(new { IsSuccess = false, ErrorMsg = "出错了" });
            }
            return Json(new { IsSuccess = true });
        }
        public static List<ResultInfo> ImportBySMT(AccountType account, string fileName, ISession NSession)
        {


            List<ResultInfo> results = new List<ResultInfo>();

            foreach (DataRow dr in GetDataTable(fileName).Rows)
            {
                string OrderExNo = dr["订单号"].ToString();
                string o = dr["订单状态"].ToString();
                if (o != "等待您发货")
                {
                    results.Add(GetResult(OrderExNo, "订单已经发货", "导入失败"));
                    continue;
                }

                bool isExist = IsExist(OrderExNo, NSession);
                if (!isExist)
                {
                    OrderType order = new OrderType { IsMerger = 0, Enabled = 1, IsOutOfStock = 0, IsRepeat = 0, IsSplit = 0, Status = OrderStatusEnum.待处理.ToString(), IsPrint = 0, CreateOn = DateTime.Now, ScanningOn = DateTime.Now };
                    try
                    {
                        order.OrderNo = Utilities.GetOrderNo(NSession);
                        order.CurrencyCode = "USD";
                        order.OrderExNo = OrderExNo;
                        order.Amount = Utilities.ToDouble(dr["订单金额"].ToString());
                        order.BuyerMemo = dr["订单备注"].ToString();
                        order.Country = dr["收货国家"].ToString();
                        order.BuyerName = dr["买家名称"].ToString();
                        order.BuyerEmail = dr["买家邮箱"].ToString();
                        order.TId = "";
                        order.Account = account.AccountName;
                        order.GenerateOn = Convert.ToDateTime(dr["付款时间"]);
                        order.Platform = PlatformEnum.SMT.ToString();
                        //舍弃原来的客户表
                        //下面地址
                        order.AddressId = CreateAddress(dr["收货人名称"].ToString(), dr["地址"].ToString(), dr["城市"].ToString(), dr["州/省"].ToString(), dr["收货国家"].ToString(), dr["收货国家"].ToString(), dr["联系电话"].ToString(), dr["手机"].ToString(), dr["买家邮箱"].ToString(), dr["邮编"].ToString(), 0, NSession);


                        NSession.Save(order);
                        NSession.Flush();
                        //
                        //添加产品
                        //
                        string info = dr["产品信息_(双击单元格展开所有产品信息!)"].ToString();
                        string[] cels = info.Split(new char[] { '【' }, StringSplitOptions.RemoveEmptyEntries);
                        if (cels.Length == 0)
                        {
                            results.Add(GetResult(OrderExNo, "没有产品信息", "导入失败"));
                            continue;//物品信息出错
                        }
                        for (int i = 0; i < cels.Length; i++)
                        {
                            string Str = cels[i];
                            System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex(@"】(?<title>.*)\n", System.Text.RegularExpressions.RegexOptions.None);
                            System.Text.RegularExpressions.Regex r4 = new System.Text.RegularExpressions.Regex(@"\(产品属性:(?<ppp>.*)\n", System.Text.RegularExpressions.RegexOptions.None);
                            System.Text.RegularExpressions.Regex r5 = new System.Text.RegularExpressions.Regex(@"\(产品数量:(?<quantity>\d+)", System.Text.RegularExpressions.RegexOptions.None);
                            System.Text.RegularExpressions.Regex r3 = new System.Text.RegularExpressions.Regex(@"\(商家编码:(?<sku>.*)\)", System.Text.RegularExpressions.RegexOptions.None);
                            //System.Text.RegularExpressions.Regex r6 = new System.Text.RegularExpressions.Regex(@"\(物流等级&买家选择物流:(?<wuliu>.+)\)", System.Text.RegularExpressions.RegexOptions.None);
                            System.Text.RegularExpressions.Match mc2 = r2.Match(Str);
                            System.Text.RegularExpressions.Match mc3 = r3.Match(Str);
                            System.Text.RegularExpressions.Match mc4 = r4.Match(Str);
                            System.Text.RegularExpressions.Match mc5 = r5.Match(Str);

                            order.LogisticMode = dr["买家选择物流"].ToString();
                            if (order.LogisticMode.IndexOf("\n") != -1)
                            {
                                order.LogisticMode = order.LogisticMode.Substring(0, order.LogisticMode.IndexOf("\n"));
                            }
                            NSession.Update(order);
                            NSession.Flush();
                            CreateOrderPruduct(mc3.Groups["sku"].Value, Utilities.ToInt(mc5.Groups["quantity"].Value.Trim(')').Trim()), mc2.Groups["title"].Value, mc4.Groups["ppp"].Value.Replace("(产品属性: ", "").Replace(")", ""), 0, "", order.Id, order.OrderNo, NSession);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }


                    results.Add(GetResult(OrderExNo, "", "导入成功"));
                    LoggerUtil.GetOrderRecord(order, "订单导入", "导入成功", NSession);
                }
                else
                {
                    results.Add(GetResult(OrderExNo, "订单已存在", "导入失败"));
                }
            }
            return results;

        }
        public static List<ResultInfo> APIBySMT(AccountType account, DateTime st, DateTime et, ISession NSession)
        {

            List<ResultInfo> results = new List<ResultInfo>();
            string token = AliUtil.RefreshToken(account);
            List<CountryType> countryTypes = NSession.CreateQuery("from CountryType").List<CountryType>().ToList();
            AliOrderListType aliOrderList = null;
            int page = 1;
            do
            {
                try
                {
                    aliOrderList = AliUtil.findOrderListQuery(token, page);
                    if (aliOrderList.totalItem != 0)
                    {

                        foreach (var o in aliOrderList.orderList)
                        {

                            bool isExist = IsExist(o.orderId.ToString(), NSession);

                            if (!isExist)
                            {
                                AliOrderType ot = AliUtil.findOrderById(token, o.orderId.ToString());
                                OrderType order = new OrderType
                                                      {
                                                          IsMerger = 0,
                                                          Enabled = 1,
                                                          IsOutOfStock = 0,
                                                          IsRepeat = 0,
                                                          IsSplit = 0,
                                                          Status = OrderStatusEnum.待处理.ToString(),
                                                          IsPrint = 0,
                                                          CreateOn = DateTime.Now,
                                                          ScanningOn = DateTime.Now
                                                      };
                                order.OrderNo = Utilities.GetOrderNo(NSession);
                                order.CurrencyCode = ot.orderAmount.currencyCode;
                                order.OrderExNo = ot.id.ToString();
                                order.Amount = ot.orderAmount.amount;
                                order.LogisticMode = o.productList[0].logisticsServiceName;
                                CountryType country =
                                    countryTypes.Find(
                                        p => p.CountryCode.ToUpper() == ot.receiptAddress.country.ToUpper());
                                if (country != null)
                                {
                                    order.Country = country.ECountry;
                                }
                                else
                                {
                                    order.Country = ot.receiptAddress.country;
                                }

                                order.BuyerName = ot.buyerInfo.firstName + " " + ot.buyerInfo.lastName;
                                order.BuyerEmail = ot.buyerInfo.email;
                                foreach (ProductList p in o.productList)
                                {
                                    order.BuyerMemo += p.memo;
                                }
                                OrderMsgType[] msgTypes = AliUtil.findOrderMsgByOrderId(token, order.OrderExNo);

                                foreach (OrderMsgType orderMsgType in msgTypes)
                                {
                                    order.BuyerMemo += "<br/>" + orderMsgType.senderName + "  " +
                                                       GetAliDate(orderMsgType.gmtCreate).ToString("yyyy-MM-dd HH:mm:ss") +
                                                       ":" + orderMsgType.content + "";
                                }
                                if (!string.IsNullOrEmpty(order.BuyerMemo))
                                    order.IsLiu = 1;

                                order.TId = "";
                                order.OrderFees = 0;
                                order.OrderCurrencyCode = "";
                                order.Account = account.AccountName;
                                order.GenerateOn = GetAliDate(ot.gmtPaySuccess);
                                order.Platform = PlatformEnum.SMT.ToString();
                                order.AddressId = CreateAddress(ot.receiptAddress.contactPerson,
                                                                ot.receiptAddress.detailAddress + "  " + ot.receiptAddress.address2,
                                                                ot.receiptAddress.city, ot.receiptAddress.province,
                                                                country == null
                                                                    ? ot.receiptAddress.country
                                                                    : country.ECountry,
                                                                country == null
                                                                    ? ot.receiptAddress.country
                                                                    : country.CountryCode, ot.receiptAddress.phoneCountry + " " + ot.receiptAddress.phoneArea + " " + ot.receiptAddress.phoneNumber,
                                                                ot.receiptAddress.mobileNo, ot.buyerInfo.email,
                                                                ot.receiptAddress.zip, 0, NSession);
                                NSession.Save(order);
                                NSession.Flush();
                                foreach (ChildOrderList item in ot.childOrderList)
                                {
                                    string remark = "";
                                    if (item.productAttributes.Length > 0)
                                    {
                                        SkuListType skuList =
                                            JsonConvert.DeserializeObject<SkuListType>(
                                                item.productAttributes.Replace("\\", ""));
                                        foreach (SkuType skuType in skuList.sku)
                                        {
                                            remark += skuType.pName + ":" + skuType.pValue;
                                        }
                                    }
                                    CreateOrderPruduct(item.productId.ToString(), item.skuCode, item.productCount,
                                                       item.productName,
                                                       remark, item.initOrderAmt.amount,
                                                       "",
                                                       order.Id,
                                                       order.OrderNo, NSession);
                                }
                                NSession.Clear();
                                NSession.Update(order);
                                NSession.Flush();
                                results.Add(GetResult(order.OrderExNo, "", "导入成功"));
                            }
                            else
                            {
                                results.Add(GetResult(o.orderId.ToString(), "该订单已存在", "导入失败"));
                            }
                        }
                        page++;
                    }
                }
                catch (Exception)
                {
                    token = AliUtil.RefreshToken(account);
                    continue;
                }

            } while (aliOrderList.totalItem > (page - 1) * 50);
            return results;
        }
        public static List<ResultInfo> APIByB2C(AccountType account, DateTime st, DateTime et, ISession NSession)
        {
            List<ResultInfo> results = new List<ResultInfo>();

            string s = DownHtml("http://www.gamesalor.com/GetOrdersHandler.ashx?startTime=" + st.ToShortDateString() + "&endTime=" + et.ToShortDateString() + "", System.Text.Encoding.UTF8);
            System.Collections.Generic.List<Order> orders = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.List<Order>>(s);
            foreach (Order foo in orders)
            {
                try
                {
                    bool isExist = IsExist(foo.GoodsDataWare.ItemNumber, NSession);
                    if (!isExist)
                    {
                        OrderType order = new OrderType
                                              {
                                                  Enabled = 1,
                                                  IsMerger = 0,
                                                  IsOutOfStock = 0,
                                                  IsRepeat = 0,
                                                  IsSplit = 0,
                                                  Status = OrderStatusEnum.待处理.ToString(),
                                                  IsPrint = 0,
                                                  CreateOn = DateTime.Now,
                                                  ScanningOn = DateTime.Now
                                              };
                        order.OrderNo = Utilities.GetOrderNo(NSession);
                        order.CurrencyCode = foo.GoodsDataWare.McCurrency;
                        order.OrderExNo = foo.GoodsDataWare.ItemNumber;
                        order.Amount = Utilities.ToDouble(foo.GoodsDataWare.McGross.ToString());
                        order.BuyerMemo = "客户付款账户" + foo.GoodsDataWare.Business + "  " + foo.GoodsDataWare.Memo;
                        order.Country = foo.GoodsDataWare.AddressCountry;
                        order.BuyerName = foo.GoodsDataWare.FirstName + " " + foo.GoodsDataWare.LastName;
                        order.BuyerEmail = foo.GoodsDataWare.PayerEmail;
                        order.TId = foo.GoodsDataWare.TxnId;
                        order.Account = account.AccountName;
                        order.GenerateOn = foo.GoodsDataWare.PaymentDate;
                        order.Platform = PlatformEnum.DH.ToString();
                        order.LogisticMode = foo.GoodsDataWare.EMS;
                        order.AddressId = CreateAddress(foo.GoodsDataWare.AddressName, foo.GoodsDataWare.AddressStreet,
                                                        foo.GoodsDataWare.AddressCity, foo.GoodsDataWare.AddressState,
                                                        foo.GoodsDataWare.AddressCountry,
                                                        foo.GoodsDataWare.AddressCountryCode, foo.GoodsDataWare.ContactPhone,
                                                        foo.GoodsDataWare.ContactPhone, foo.GoodsDataWare.PayerEmail,
                                                        foo.GoodsDataWare.AddressZip, 0, NSession);
                        NSession.Save(order);
                        NSession.Flush();
                        foreach (GoodsDataOrder item in foo.GoodsDataOrderList)
                        {
                            CreateOrderPruduct(item.ItemID, item.Quantity, item.ItemID, "", 0, item.Url, order.Id,
                                               order.OrderNo, NSession);
                        }
                        results.Add(GetResult(order.OrderExNo, "", "导入成功"));
                    }
                    else
                    {

                        results.Add(GetResult(foo.GoodsDataWare.ItemNumber, "该订单已存在", "导入失败"));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw ex;
                }
            }
            return results;
        }
        public static List<ResultInfo> ImportByB2C(AccountType account, string fileName, ISession NSession)
        {

            List<ResultInfo> results = new List<ResultInfo>();
            foreach (DataRow item in OrderHelper.GetDataTable(fileName).Rows)
            {
                try
                {
                    string OrderExNo = item["订单编号"].ToString();
                    bool isExist = IsExist(OrderExNo, NSession);
                    if (!isExist)
                    {
                        OrderType order = new OrderType { IsMerger = 0, Enabled = 1, IsOutOfStock = 0, IsRepeat = 0, IsSplit = 0, Status = OrderStatusEnum.待处理.ToString(), IsPrint = 0, CreateOn = DateTime.Now, ScanningOn = DateTime.Now };
                        order.OrderNo = Utilities.GetOrderNo(NSession);
                        order.OrderExNo = OrderExNo;
                        order.Amount = Utilities.ToDouble(item["金额"].ToString());
                        order.Country = item["国家"].ToString();
                        order.BuyerName = item["用户名"].ToString();
                        order.CurrencyCode = "USD";
                        order.Account = account.AccountName;
                        order.GenerateOn = DateTime.Now;
                        order.Platform = PlatformEnum.DH.ToString();

                        order.AddressId = CreateAddress(item["收件人"].ToString(), item["街道"].ToString(), item["城市"].ToString(), item["省"].ToString(), item["国家"].ToString(), item["国家"].ToString(), item["电话"].ToString(), item["电话"].ToString(), item["邮箱"].ToString(), item["邮编"].ToString(), 0, NSession);

                        NSession.Save(order);
                        NSession.Flush();


                        CreateOrderPruduct(item["商品"].ToString(), item["商品"].ToString(), Utilities.ToInt(item["数量"].ToString()), "", "", 0, item["属性"].ToString(), order.Id, order.OrderNo, NSession);
                        results.Add(GetResult(OrderExNo, "", "导入成功"));
                        LoggerUtil.GetOrderRecord(order, "订单导入", "导入成功", NSession);

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw ex;
                }
            }
            return results;
        }
        public static List<ResultInfo> ImportByGmarket(AccountType account, string fileName, ISession NSession)
        {

            List<ResultInfo> results = new List<ResultInfo>();
            CsvReader csv = new CsvReader(fileName, Encoding.Default);

            List<Dictionary<string, string>> lsitss = csv.ReadAllData();
            Dictionary<string, int> listOrder = new Dictionary<string, int>();
            foreach (Dictionary<string, string> item in lsitss)
            {
                try
                {
                    if (item.Count < 10)//判断列数
                        continue;
                    string OrderExNo = item["Cart no."];
                    double price = Convert.ToDouble(item["Settle Price"].Replace(",", ""));
                    if (listOrder.ContainsKey(OrderExNo))
                    {
                        CreateOrderPruduct(item["Item code"], item["Option Code"], Utilities.ToInt(item["Qty."]), item["Item"], item["Options"], 0, "", listOrder[OrderExNo], OrderExNo, NSession);
                        NSession.CreateSQLQuery("update orders set Amount=Amount+" + price + " where Id=" +
                                                listOrder[OrderExNo]).UniqueResult();
                        continue;
                    }
                    bool isExist = IsExist(OrderExNo, NSession, account.AccountName);
                    if (!isExist)
                    {
                        OrderType order = new OrderType { IsMerger = 0, Enabled = 1, IsOutOfStock = 0, IsRepeat = 0, IsSplit = 0, Status = OrderStatusEnum.待处理.ToString(), IsPrint = 0, CreateOn = DateTime.Now, ScanningOn = DateTime.Now };
                        order.OrderNo = Utilities.GetOrderNo(NSession);
                        order.CurrencyCode = item["Currency"];
                        order.OrderExNo = OrderExNo;
                        order.Amount = Utilities.ToDouble(item["Settle Price"]);
                        order.BuyerMemo = item["Memo to Seller"];
                        order.Country = item["Nation"];
                        order.BuyerName = item["Customer"];
                        order.BuyerEmail = "";
                        order.TId = item["Order no."];
                        order.Account = account.AccountName;
                        order.GenerateOn = Convert.ToDateTime(item["Payment Complete"]);
                        order.Platform = PlatformEnum.Gmarket.ToString();
                        order.BuyerMemo = item["Memo to Seller"] + item["Options"];
                        order.AddressId = CreateAddress(item["Recipient"], item["Address"], "", "", item["Nation"], item["Nation"], item["Recipient Phone number"], item["Recipient mobile Phone number"], "", item["Postal code"], 0, NSession);
                        NSession.Save(order);
                        NSession.Flush();
                        CreateOrderPruduct(item["Item code"], item["Option Code"], Utilities.ToInt(item["Qty."]), item["Item"], item["Options"], 0, "", order.Id, order.OrderNo, NSession);
                        results.Add(GetResult(OrderExNo, "", "导入成功"));
                        listOrder.Add(OrderExNo, order.Id);
                        LoggerUtil.GetOrderRecord(order, "订单导入", "导入成功", NSession);
                    }
                    else
                    {
                        results.Add(GetResult(OrderExNo, "订单已存在", "导入失败"));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw ex;
                }
            }
            return results;
        }
        public static void GetOrderRecord(OrderType order, string recordType, string Content, string CreateBy, ISession NSession)
        {
            GetOrderRecord(order.Id, order.OrderNo, recordType, Content, CreateBy, NSession);

        }
        public static List<ResultInfo> ImportByAmazon(AccountType account, string fileName, ISession NSession)
        {

            List<ResultInfo> results = new List<ResultInfo>();
            CsvReader csv = new CsvReader(fileName, Encoding.Default);

            List<Dictionary<string, string>> lsitss = csv.ReadAllData();
            Dictionary<string, int> listOrder = new Dictionary<string, int>();
            foreach (Dictionary<string, string> item in lsitss)
            {
                if (item.Count < 10)//判断列数
                    continue;
                string OrderExNo = item["order-id"];

                if (listOrder.ContainsKey(OrderExNo))
                {
                    CreateOrderPruduct(item["sku"], Utilities.ToInt(item["quantity-purchased"]), item["sku"], "", 0, "", listOrder[OrderExNo], OrderExNo, NSession);
                    continue;
                }
                bool isExist = IsExist(OrderExNo, NSession);
                if (!isExist)
                {
                    OrderType order = new OrderType { IsMerger = 0, Enabled = 1, IsOutOfStock = 0, IsRepeat = 0, IsSplit = 0, Status = OrderStatusEnum.待处理.ToString(), IsPrint = 0, CreateOn = DateTime.Now, ScanningOn = DateTime.Now };
                    order.OrderNo = Utilities.GetOrderNo(NSession);
                    try
                    {
                        order.CurrencyCode = item["currency"].ToUpper().Trim();
                    }
                    catch (Exception)
                    {
                        order.CurrencyCode = "USD";
                    }
                    order.OrderExNo = item["order-id"];
                    //order.Amount =Utilities.ToDouble(dr["订单金额"]);
                    //order.BuyerMemo = dr["订单备注"].ToString();
                    order.Country = item["ship-country"];
                    order.BuyerName = item["buyer-name"];
                    order.BuyerEmail = item["buyer-email"];
                    order.TId = "";
                    order.Account = account.AccountName;
                    order.GenerateOn = Convert.ToDateTime(item["payments-date"]);
                    order.Platform = PlatformEnum.Amazon.ToString();
                    order.AddressId = CreateAddress(item["recipient-name"], item["ship-address-1"] + item["ship-address-2"] + item["ship-address-3"], item["ship-city"], item["ship-state"], item["ship-country"], item["ship-country"], item["buyer-phone-number"], item["buyer-phone-number"], item["buyer-email"], item["ship-postal-code"], 0, NSession);
                    NSession.Save(order);
                    NSession.Flush();
                    CreateOrderPruduct(item["sku"], Utilities.ToInt(item["quantity-purchased"]), item["sku"], "", 0, "", order.Id, order.OrderNo, NSession);
                    results.Add(GetResult(OrderExNo, "", "导入成功"));
                    listOrder.Add(OrderExNo, order.Id);
                    LoggerUtil.GetOrderRecord(order, "订单导入", "导入成功", NSession);
                }
                else
                {
                    results.Add(GetResult(OrderExNo, "订单已存在", "导入失败"));
                }
            }
            return results;
        }
 public void SaveRecord(OrderType order, string p)
 {
     IList<OrderProductType> orderproduct =
         NSession.CreateQuery("from OrderProductType where OId='" + order.Id + "'").List<OrderProductType>();
     double PackCoefficient = 0;
     string sku = "";
     if (orderproduct.Count == 0)
     {
         PackCoefficient = 3;
     }
     foreach (OrderProductType item in orderproduct)
     {
         IList<ProductType> product =
             NSession.CreateQuery("from ProductType where SKU='" + item.SKU + "'").List<ProductType>();
         if (product.Count != 0)
         {
             if (product[0].PackCoefficient > PackCoefficient)
             {
                 PackCoefficient = product[0].PackCoefficient;
                 sku = product[0].SKU;
             }
         }
         else
         {
             PackCoefficient = 1;
         }
     }
     var orderPackRecord = new OrderPackRecordType
                               {
                                   OId = order.Id,
                                   OrderNo = order.OrderNo,
                                   PackBy = p,
                                   PackOn = DateTime.Now,
                                   ScanBy = CurrentUser.Realname,
                                   PackCoefficient = PackCoefficient,
                                   SKU = sku
                               };
     NSession.Save(orderPackRecord);
     NSession.Flush();
 }
        public JsonResult Create(OrderType obj)
        {
            try
            {
                var acc = NSession.Get<AccountType>(Utilities.ToInt(obj.Account));
                if (acc != null)
                    obj.Account = acc.AccountName;
                if (obj.OrderExNo.Trim() == "" || OrderHelper.IsExist(obj.OrderExNo.Trim(), NSession, obj.Account))
                {
                    return Json(new { IsSuccess = false, ErrorMsg = "平台订单号为空或者重复" });
                }

                object c =
                    NSession.CreateQuery("select count(Id) from OrderType where OrderNo='" + obj.OrderNo + "'").
                        UniqueResult();
                if (Convert.ToInt32(c) > 0)
                {
                    obj.OrderNo = Utilities.GetOrderNo(NSession);
                }

                obj.AddressInfo.CountryCode = obj.AddressInfo.Country;
                obj.AddressInfo.Email = obj.BuyerEmail;
                NSession.Save(obj.AddressInfo);

                obj.AddressId = obj.AddressInfo.Id;
                obj.Country = obj.AddressInfo.Country;
                obj.Status = OrderStatusEnum.待处理.ToString();
                obj.GenerateOn = obj.ScanningOn = obj.CreateOn = DateTime.Now;
                var list = JsonConvert.DeserializeObject<List<OrderProductType>>(obj.rows);
                obj.Enabled = 1;
                NSession.Save(obj);
                foreach (OrderProductType item in list)
                {
                    item.OId = obj.Id;
                    item.OrderNo = obj.OrderNo;
                    NSession.Save(item);
                }
                NSession.Flush();
                LoggerUtil.GetOrderRecord(obj, "新建订单", "创建订单", CurrentUser, NSession);
            }
            catch (Exception ee)
            {
                return Json(new { IsSuccess = false, ErrorMsg = "出错了" });
            }
            return Json(new { IsSuccess = true });
        }
        public static List<ResultInfo> APIByEbay(AccountType account, DateTime st, DateTime et, ISession NSession)
        {

            List<ResultInfo> results = new List<ResultInfo>();
            ApiContext context = AppSettingHelper.GetGenericApiContext("US");
            context.ApiCredential.eBayToken = account.ApiToken;
            eBay.Service.Call.GetOrdersCall apicall = new eBay.Service.Call.GetOrdersCall(context);
            apicall.IncludeFinalValueFee = true;
            apicall.DetailLevelList.Add(eBay.Service.Core.Soap.DetailLevelCodeType.ReturnAll);
            eBay.Service.Core.Soap.OrderTypeCollection m = null;
            int i = 1;
            do
            {
                apicall.Pagination = new eBay.Service.Core.Soap.PaginationType();
                apicall.Pagination.PageNumber = i;
                apicall.Pagination.EntriesPerPage = 50;
                apicall.OrderRole = eBay.Service.Core.Soap.TradingRoleCodeType.Seller;
                apicall.OrderStatus = eBay.Service.Core.Soap.OrderStatusCodeType.Completed;
                apicall.ModTimeFrom = st;
                apicall.ModTimeTo = et;
                apicall.Execute();

                m = apicall.OrderList;
                for (int k = 0; k < m.Count; k++)
                {
                    eBay.Service.Core.Soap.OrderType ot = m[k];
                    if (ot.OrderStatus == eBay.Service.Core.Soap.OrderStatusCodeType.Authenticated ||
                        ot.OrderStatus == eBay.Service.Core.Soap.OrderStatusCodeType.CustomCode ||
                        ot.OrderStatus == eBay.Service.Core.Soap.OrderStatusCodeType.Default ||
                        ot.OrderStatus == eBay.Service.Core.Soap.OrderStatusCodeType.Inactive ||
                        ot.OrderStatus == eBay.Service.Core.Soap.OrderStatusCodeType.InProcess)
                    {
                        //去除别的订单状态
                        continue;
                    }
                    if (ot.PaidTime == DateTime.MinValue || ot.ShippedTime != DateTime.MinValue)
                    {
                        continue;
                    }
                    //查看是不是在订单系统里面存在
                    bool isExist = IsExist(ot.OrderID, NSession);
                    if (!isExist)
                    {
                        OrderType order = new OrderType
                                              {
                                                  IsMerger = 0,
                                                  Enabled = 1,
                                                  IsOutOfStock = 0,
                                                  IsRepeat = 0,
                                                  IsSplit = 0,
                                                  Status = OrderStatusEnum.待处理.ToString(),
                                                  IsPrint = 0,
                                                  CreateOn = DateTime.Now,
                                                  ScanningOn = DateTime.Now
                                              };
                        order.OrderNo = Utilities.GetOrderNo(NSession);
                        order.CurrencyCode = ot.AmountPaid.currencyID.ToString();
                        order.OrderExNo = ot.OrderID;
                        order.Amount = ot.AmountPaid.Value;

                        order.Country = ot.ShippingAddress.CountryName;
                        order.BuyerName = ot.BuyerUserID;
                        order.BuyerEmail = ot.TransactionArray[0].Buyer.Email;
                        order.BuyerMemo = ot.BuyerCheckoutMessage;

                        order.TId = ot.ExternalTransaction[0].ExternalTransactionID;
                        order.OrderFees = ot.ExternalTransaction[0].FeeOrCreditAmount.Value;
                        order.OrderCurrencyCode = ot.ExternalTransaction[0].FeeOrCreditAmount.currencyID.ToString();
                        order.Account = account.AccountName;
                        order.GenerateOn = ot.PaidTime;
                        order.Platform = PlatformEnum.Ebay.ToString();

                        order.AddressId = CreateAddress(ot.ShippingAddress.Name,
                                                        (string.IsNullOrEmpty(ot.ShippingAddress.Street)
                                                             ? ""
                                                             : ot.ShippingAddress.Street) +
                                                        (string.IsNullOrEmpty(ot.ShippingAddress.Street1)
                                                             ? ""
                                                             : ot.ShippingAddress.Street1) +
                                                        (string.IsNullOrEmpty(ot.ShippingAddress.Street2)
                                                             ? ""
                                                             : ot.ShippingAddress.Street2),
                                                        ot.ShippingAddress.CityName, ot.ShippingAddress.StateOrProvince,
                                                        ot.ShippingAddress.CountryName,
                                                        ot.ShippingAddress.Country.ToString(), ot.ShippingAddress.Phone,
                                                        ot.ShippingAddress.Phone, ot.TransactionArray[0].Buyer.Email,
                                                        ot.ShippingAddress.PostalCode, 0, NSession);
                        NSession.Save(order);
                        NSession.Flush();
                        foreach (TransactionType item in ot.TransactionArray)
                        {
                            string sku = "";
                            if (item.Variation != null)
                            {
                                sku = item.Variation.SKU;
                            }
                            else
                            {
                                sku = item.Item.SKU;
                            }
                            order.OrderCurrencyCode2 = item.FinalValueFee.currencyID.ToString();
                            order.OrderFees2 += item.FinalValueFee.Value;

                            CreateOrderPruduct(item.Item.ItemID, sku, item.QuantityPurchased, item.Item.Title,
                                               "", 0,
                                               "http://thumbs.ebaystatic.com/pict/" + item.Item.ItemID + "6464_1.jpg",
                                               order.Id,
                                               order.OrderNo, NSession);
                        }
                        NSession.Clear();
                        NSession.Update(order);
                        NSession.Flush();
                        results.Add(GetResult(order.OrderExNo, "", "导入成功"));
                    }
                    else
                    {
                        results.Add(GetResult(ot.OrderID, "该订单已存在", "导入失败"));
                    }
                }
                i++;
            } while (apicall.HasMoreOrders);

            return results;
        }
        /// <summary>
        /// 重发或者拆分 生成的新订单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="t">0:拆分 1:重发</param>
        /// <returns></returns>
        public OrderType CreateNewOrder(OrderType order, int t)
        {

            order.Amount = 0;
            order.IsPrint = 0;
            order.RMB = 0;
            order.TrackCode = "";
            order.Freight = 0;
            order.Weight = 0;
            order.OrderNo = Utilities.GetOrderNo(NSession);
            order.CreateOn = DateTime.Now;
            order.IsCanSplit = 0;
            if (order.MId == 0)
                order.MId = order.Id;
            order.Id = 0;
            order.IsAudit = 1;
            order.IsOutOfStock = 0;
            switch (t)
            {
                case 0:
                    order.IsSplit = 1;
                    break;
                case 1:
                    order.IsRepeat = 1;
                    order.IsAudit = 0;
                    order.Status = OrderStatusEnum.已处理.ToString();
                    break;
                default:
                    break;
            }
            NSession.Clear();
            NSession.Save(order);
            NSession.Flush();
            return order;
        }
        public static bool ValiOrder(OrderType order, List<CountryType> countrys, List<ProductType> products, List<CurrencyType> currencys, List<LogisticsModeType> logistics, ISession NSession)
        {


            bool resultValue = true;
            order.Products = NSession.CreateQuery("from OrderProductType where OId='" + order.Id + "'").List<OrderProductType>().ToList();
            order.ErrorInfo = "";
            if (order.Country != null)
            {
                if (
                    countrys.FindIndex(
                        p => p.ECountry == order.Country || p.CountryCode.ToUpper() == order.Country.ToUpper()) == -1)
                {
                    resultValue = false;
                    order.ErrorInfo += "国家不符 ";
                }
            }
            else
            {
                resultValue = false;
                order.ErrorInfo += "国家不符 ";
            }
            if (order.CurrencyCode != null)
            {
                CurrencyType currency = currencys.Find(p => p.CurrencyCode.ToUpper() == order.CurrencyCode.ToUpper());
                if (currency == null)
                {
                    resultValue = false;
                    order.ErrorInfo += "货币不符 ";
                }
            }
            else
            {
                resultValue = false;
                order.ErrorInfo += "货币不符 ";
            }
            if (logistics.FindIndex(p => p.LogisticsCode == order.LogisticMode) == -1)
            {
                resultValue = false;
                order.ErrorInfo += "货运不符 ";
            }
            if (order.Amount == 0 && order.Platform != PlatformEnum.Amazon.ToString())
            {
                resultValue = false;
                order.ErrorInfo += "金额不能为0 ";
            }
            foreach (var item in order.Products)
            {
                if (item.SKU == null)
                {
                    resultValue = false;
                    order.ErrorInfo += "SKU不符";
                    break;
                }
                ProductType product = products.Find(p => p.SKU.Trim().ToUpper() == item.SKU.Trim().ToUpper());
                if (product == null)
                {
                    resultValue = false;
                    order.ErrorInfo += "SKU不符";
                    break;
                }
                else
                {
                    if (product.Status == "停产")
                    {
                        order.IsStop = 1;
                        item.IsQue = 2;
                        NSession.SaveOrUpdate(item);
                        NSession.Flush();
                    }
                }
            }
            object obj = NSession.CreateQuery("select count(Id) from OrderType where Status<>'待处理' and OrderExNo=:p and Account=:p2 and IsSplit =0 and IsRepeat=0").SetString("p", order.OrderExNo).SetString("p2", order.Account).UniqueResult();
            if (Convert.ToInt32(obj) > 0)
            {
                resultValue = false;
                order.ErrorInfo += " 订单重复";
            }

            if (resultValue)
            {
                order.IsAudit = 1;
                SaveAmount(order, currencys, NSession);
                if (order.IsStop == 0)
                {
                    SetQueOrder(order, NSession);
                }
            }

            if (order.ErrorInfo == "")
            {
                order.ErrorInfo = "验证成功!";
                if (order.IsStop == 1)
                {
                    LoggerUtil.GetOrderRecord(order, "验证订单", "订单中有停产产品,自动设为停产订单。", NSession);
                }

                IList<EmailMessageType> messageTypes = NSession.CreateQuery("from EmailMessageType where OrderExNo='" + order.OrderExNo + "'").List<EmailMessageType>();
                foreach (EmailMessageType emailMessageType in messageTypes)
                {
                    order.BuyerMemo = emailMessageType.RserverDate + " 有买家留言<br>" + order.BuyerMemo;
                }
            }
            NSession.Clear();
            NSession.SaveOrUpdate(order);
            NSession.Flush();
            LoggerUtil.GetOrderRecord(order, "验证订单", order.ErrorInfo, NSession);
            return resultValue;
        }
        public static void EbayUploadTrackCode(string account, KeWeiOMS.Domain.OrderType orderType)
        {
            ISession NSession = NhbHelper.OpenSession();
            Dictionary <string, int> sendNum  = new Dictionary <string, int>();
            IList <AccountType>      accounts = NSession.CreateQuery("from AccountType where AccountName='" + account + "'").SetMaxResults(1).
                                                List <AccountType>();

            if (accounts.Count > 0)
            {
                IList <KeWeiOMS.Domain.OrderType> orderList = new List <KeWeiOMS.Domain.OrderType>();
                if (orderType.IsMerger == 1 || orderType.OrderExNo.IndexOf("|") != -1)
                {
                    orderList = NSession.CreateQuery("from OrderType where MId='" + orderType.Id + "' Or Id ='" + orderType.Id + "'").List <KeWeiOMS.Domain.OrderType>();
                }
                else
                {
                    orderList.Add(orderType);
                }
                ApiContext context = GetGenericApiContext("US");

                context.ApiCredential.eBayToken = accounts[0].ApiToken;
                eBay.Service.Call.CompleteSaleCall call = null;
                string CarrierUsed = "";
                // IList<logisticsSetupType> setups = NSession.CreateQuery("from  logisticsSetupType where LId in (select ParentID from LogisticsModeType where LogisticsCode='" + orderType.LogisticMode + "')").List<logisticsSetupType>();
                //if (setups != null)
                //{
                //    CarrierUsed = setups[0].SetupName;
                //}
                CarrierUsed = "China Post";
                call        = new eBay.Service.Call.CompleteSaleCall(context);
                foreach (KeWeiOMS.Domain.OrderType order in orderList)
                {
                    string orderid = "";
                    string itemid  = "";

                    if (order.OrderExNo.IndexOf("-") == -1)
                    {
                        orderid = order.OrderExNo;

                        GetOrdersCall       apicall = new GetOrdersCall(context);
                        OrderTypeCollection orders  = null;
                        try
                        {
                            orders = apicall.GetOrders(new StringCollection {
                                order.OrderExNo
                            });
                        }
                        catch (Exception)
                        {
                            orders = new OrderTypeCollection();
                        }

                        if (orders.Count > 0)
                        {
                            foreach (TransactionType trans in orders[0].TransactionArray)
                            {
                                itemid        = trans.Item.ItemID;
                                orderid       = trans.TransactionID;
                                call.Shipment = new ShipmentType();
                                call.Shipment.DeliveryStatus          = eBay.Service.Core.Soap.ShipmentDeliveryStatusCodeType.Delivered;
                                call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();

                                if (orderType.OrderNo == order.TrackCode || order.TrackCode == "" || order.TrackCode == null)
                                {
                                    //call.Shipment.ShipmentTrackingNumber = "";
                                }
                                else
                                {
                                    call.Shipment.ShippingCarrierUsed    = CarrierUsed;
                                    call.Shipment.ShipmentTrackingNumber = orderType.TrackCode.ToString();
                                }
                                call.Shipment.DeliveryDate          = DateTime.Now;
                                call.Shipment.DeliveryDateSpecified = true;
                                call.Shipment.DeliveryStatus        = ShipmentDeliveryStatusCodeType.Delivered;
                                try
                                {
                                    call.CompleteSale(itemid, orderid, true, true);
                                }
                                catch (Exception ex)
                                {
                                    break;
                                }
                                break;
                            }
                        }
                    }
                    else
                    {
                        itemid        = order.OrderExNo.Substring(0, order.OrderExNo.IndexOf("-"));
                        orderid       = order.OrderExNo.Substring(order.OrderExNo.IndexOf("-") + 1);
                        call.Shipment = new ShipmentType();
                        call.Shipment.DeliveryStatus          = eBay.Service.Core.Soap.ShipmentDeliveryStatusCodeType.Delivered;
                        call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();
                        if (orderType.OrderNo == order.TrackCode || order.TrackCode == "" || order.TrackCode == null)
                        {
                            //call.Shipment.ShipmentTrackingNumber = "";
                        }
                        else
                        {
                            call.Shipment.ShippingCarrierUsed    = CarrierUsed;
                            call.Shipment.ShipmentTrackingNumber = orderType.TrackCode.ToString();
                        }

                        call.Shipment.DeliveryDate          = DateTime.Now;
                        call.Shipment.DeliveryDateSpecified = true;
                        call.Shipment.DeliveryStatus        = ShipmentDeliveryStatusCodeType.Delivered;
                        try
                        {
                            call.CompleteSale(itemid, orderid, true, true);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        finally
                        {
                        }
                    }
                }
            }
        }
        public static void UpdateAmount(OrderType order, ISession NSession)
        {
            OrderAmountType orderAmount = null;
            if (order.MId > 0)
            {
                IList<OrderAmountType> l =
                    NSession.CreateQuery("from OrderAmountType where OId=" + order.MId).SetMaxResults(1).List
                        <OrderAmountType>();
                if (l.Count > 0)
                    orderAmount = l[0];
            }
            else
            {
                IList<OrderAmountType> l = NSession.CreateQuery("from OrderAmountType where OId=" + order.Id).SetMaxResults(1).List<OrderAmountType>();
                if (l.Count > 0)
                    orderAmount = l[0];
            }
            if (orderAmount != null)
            {
                orderAmount.TotalFreight += order.Freight;
                object obj =
                       NSession.CreateQuery("select count(Id) from OrderType where Status <> '已发货' and (MId=" + order.Id + " or Id=" + order.Id + ")").UniqueResult();

                if (Convert.ToInt32(obj) > 0)
                {
                    orderAmount.Status = "未发货";
                }
                else
                {
                    orderAmount.Status = "已发货";
                }
                orderAmount.ScanningOn = order.ScanningOn;
                orderAmount.Profit = Math.Round(orderAmount.Profit - order.Freight, 5);
                orderAmount.CreateOn = order.CreateOn;
                orderAmount.UpdateOn = DateTime.Now;
                NSession.Update(orderAmount);
                NSession.Flush();
            }


        }
        public static void SetQueOrder(OrderType order, ISession NSession)
        {
            ///计算产品是否是缺货订单--确定定位:设置缺货标记,设置产品占位标记,根据订单审核时间设置。订单统一设置。
            if (order.Enabled == 0) return;
            bool isUse = true;
            bool isold = false;
            if (order.IsOutOfStock == 1)
                isold = true;
            if (order.Products == null)
            {
                order.Products = NSession.CreateQuery("from OrderProductType where OId='" + order.Id + "'").List<OrderProductType>().ToList();
            }
            if (order.Products.Count > 1)
            {
                order.IsCanSplit = 1;
            }
            foreach (var item in order.Products)
            {
                item.IsQue = 0;
                int unPeiCount = Convert.ToInt32(NSession.CreateSQLQuery("select isnull(count(Id),0) from SKUCode where SKU='" + item.SKU + "' and IsOut=0 ").UniqueResult());
                int useCount = Convert.ToInt32(NSession.CreateSQLQuery("select isnull(sum(OP.Qty),0) from OrderProducts OP where OP.SKU='" + item.SKU + "' and OP.IsQue=3").UniqueResult());
                if (item.Qty > 1)
                    order.IsCanSplit = 1;
                if ((unPeiCount - useCount) < item.Qty) //剩余的数量不足于订单的的SKU数量
                {
                    isUse = false;
                    item.IsQue = 1;//标记缺货
                    order.IsOutOfStock = 1;//只要有一个产品是缺货的,那么整个订单都是缺货的。
                }
                NSession.SaveOrUpdate(item);
                NSession.Flush();
            }
            if (isUse) //订单都是不缺货的的。
            {

                order.IsOutOfStock = 0;
                foreach (var item in order.Products)
                {
                    item.IsQue = 3;//标记这个产品排入库存的序列
                    NSession.SaveOrUpdate(item);
                    NSession.Flush();
                }
            }
            NSession.SaveOrUpdate(order);
            NSession.Flush();
            if (!isold && order.IsOutOfStock == 1)
            {
                LoggerUtil.GetOrderRecord(order, "验证订单", "订单中有产品缺货,自动设置为缺货订单。", NSession);
            }
            else if (isold && order.IsOutOfStock == 0)
            {
                LoggerUtil.GetOrderRecord(order, "系统自动检验订单", "检验到产品有库存,缺货自动状态删除。", NSession);
            }

        }
 public static void SaveAmount(OrderType order, ISession NSession)
 {
     List<CurrencyType> currencys = NSession.CreateQuery("from CurrencyType").List<CurrencyType>().ToList();
     SaveAmount(order, currencys, NSession);
 }