AdSchedule

Namespace: Google.AdWords
We found 10 examples in language CSharp for this search. You will see 51 fragments of code.

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public FeedItemTarget Clone() {
      return new FeedItemTarget(this);
    }
    /// <summary>Clears the value of the "feed_item" field</summary>
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearFeedItem() {
      feedItem_ = null;
    }
    /// <summary>Clears the value of the "feed_item_target_id" field</summary>
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearFeedItemTargetId() {
      _hasBits0 &= ~1;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearTarget() {
      targetCase_ = TargetOneofCase.None;
      target_ = null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as FeedItemTarget);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(FeedItemTarget other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (ResourceName != other.ResourceName) return false;
      if (FeedItem != other.FeedItem) return false;
      if (FeedItemTargetType != other.FeedItemTargetType) return false;
      if (FeedItemTargetId != other.FeedItemTargetId) return false;
      if (Status != other.Status) return false;
      if (Campaign != other.Campaign) return false;
      if (AdGroup != other.AdGroup) return false;
      if (!object.Equals(Keyword, other.Keyword)) return false;
      if (GeoTargetConstant != other.GeoTargetConstant) return false;
      if (Device != other.Device) return false;
      if (!object.Equals(AdSchedule, other.AdSchedule)) return false;
      if (TargetCase != other.TargetCase) return false;
      return Equals(_unknownFields, other._unknownFields);
    }


    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public FeedItemTarget Clone() {
      return new FeedItemTarget(this);
    }
    /// <summary>Clears the value of the "feed_item" field</summary>
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearFeedItem() {
      feedItem_ = null;
    }
    /// <summary>Clears the value of the "feed_item_target_id" field</summary>
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearFeedItemTargetId() {
      _hasBits0 &= ~1;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearTarget() {
      targetCase_ = TargetOneofCase.None;
      target_ = null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as FeedItemTarget);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(FeedItemTarget other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (ResourceName != other.ResourceName) return false;
      if (FeedItem != other.FeedItem) return false;
      if (FeedItemTargetType != other.FeedItemTargetType) return false;
      if (FeedItemTargetId != other.FeedItemTargetId) return false;
      if (Status != other.Status) return false;
      if (Campaign != other.Campaign) return false;
      if (AdGroup != other.AdGroup) return false;
      if (!object.Equals(Keyword, other.Keyword)) return false;
      if (GeoTargetConstant != other.GeoTargetConstant) return false;
      if (Device != other.Device) return false;
      if (!object.Equals(AdSchedule, other.AdSchedule)) return false;
      if (TargetCase != other.TargetCase) return false;
      return Equals(_unknownFields, other._unknownFields);
    }

		public override void ReadFrom(XElement xE)
		{
			base.ReadFrom(xE);
			DayOfWeek = null;
			StartHour = null;
			StartMinute = null;
			EndHour = null;
			EndMinute = null;
			foreach (var xItem in xE.Elements())
			{
				var localName = xItem.Name.LocalName;
				if (localName == "dayOfWeek")
				{
					DayOfWeek = DayOfWeekExtensions.Parse(xItem.Value);
				}
				else if (localName == "startHour")
				{
					StartHour = int.Parse(xItem.Value);
				}
				else if (localName == "startMinute")
				{
					StartMinute = MinuteOfHourExtensions.Parse(xItem.Value);
				}
				else if (localName == "endHour")
				{
					EndHour = int.Parse(xItem.Value);
				}
				else if (localName == "endMinute")
				{
					EndMinute = MinuteOfHourExtensions.Parse(xItem.Value);
				}
			}
		}
		public override void WriteTo(XElement xE)
		{
			base.WriteTo(xE);
			XmlUtility.SetXsiType(xE, "https://adwords.google.com/api/adwords/cm/v201609", "AdSchedule");
			XElement xItem = null;
			if (DayOfWeek != null)
			{
				xItem = new XElement(XName.Get("dayOfWeek", "https://adwords.google.com/api/adwords/cm/v201609"));
				xItem.Add(DayOfWeek.Value.ToXmlValue());
				xE.Add(xItem);
			}
			if (StartHour != null)
			{
				xItem = new XElement(XName.Get("startHour", "https://adwords.google.com/api/adwords/cm/v201609"));
				xItem.Add(StartHour.Value.ToString());
				xE.Add(xItem);
			}
			if (StartMinute != null)
			{
				xItem = new XElement(XName.Get("startMinute", "https://adwords.google.com/api/adwords/cm/v201609"));
				xItem.Add(StartMinute.Value.ToXmlValue());
				xE.Add(xItem);
			}
			if (EndHour != null)
			{
				xItem = new XElement(XName.Get("endHour", "https://adwords.google.com/api/adwords/cm/v201609"));
				xItem.Add(EndHour.Value.ToString());
				xE.Add(xItem);
			}
			if (EndMinute != null)
			{
				xItem = new XElement(XName.Get("endMinute", "https://adwords.google.com/api/adwords/cm/v201609"));
				xItem.Add(EndMinute.Value.ToXmlValue());
				xE.Add(xItem);
			}
		}


        #region 添加购物车
        /// <summary>
        /// 添加购物车
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public Common.JsonResult AddShoppingCart([FromBody]JSONAddCart jsoncart)
        {
            /**
             * 1购物车中最多3个广告位
             * 2每个广告位最多3个排期
             * 3广告位排期 天不能重复
             * **/
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart begin******");
            try
            {
                string listd = Newtonsoft.Json.JsonConvert.SerializeObject(jsoncart);
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]*****AddShoppingCart->" + listd + "******");
            }
            catch (Exception ex)
            { }
            #region 参数校验
            string vmsg = string.Empty;
            if (!jsoncart.CheckSelfModel(out vmsg))
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart 验证出错:" + vmsg);
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion

            try
            {

                foreach (JSONAPP app in jsoncart.IDs)
                {
                    Entities.CartInfo cartmodel = new Entities.CartInfo();
                    cartmodel.MediaType = jsoncart.MediaType;
                    cartmodel.MediaID = app.MediaID;
                    cartmodel.PubDetailID = app.PublishDetailID;
                    cartmodel.IsSelected = 1;
                    cartmodel.CreateUserID = currentUserID;
                    cartmodel.ADSchedule = app.ADSchedule;
                    int cartid;
                    vmsg = BLL.CartInfo.Instance.InsertV1_1(cartmodel,out cartid);
                    if (!string.IsNullOrEmpty(vmsg))
                    {
                        BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart 验证出错:" + vmsg);
                        return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
                    }                    
                }
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart 出错:" + ex.Message);
                vmsg = "出错:" + ex.Message;
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart end******");
            return WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功");
        }                
        #endregion
        #region 删除购物车
        [HttpGet]
        public Common.JsonResult DeleteShoppingCart(int mediatype,string cartids)
        {
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******DeleteShoppingCart begin******");
            #region 参数校验
            if (mediatype!=14001)
            {
                return WebAPI.Common.Util.GetJsonDataByResult(null, "媒体类型不正确", -1);
            }
            if (string.IsNullOrEmpty(cartids))
            {
                return WebAPI.Common.Util.GetJsonDataByResult(null, "购物车ID串不能为空", -1);
            }
            #endregion

            try
            {
                //根据购物车Cartid删除广告位记录、删除排期信息
                string vmsg = string.Empty;                
                //vmsg = BLL.CartInfo.Instance.DeleteV1_1(mediatype, currentUserID, cartids);
                if (!string.IsNullOrEmpty(vmsg))
                {
                    return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
                }
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******DeleteShoppingCart 出错:" + ex.Message);
                return WebAPI.Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******DeleteShoppingCart end******");
            return WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功");
        }
        #endregion
        #region 点击投放时,把当前购物车里面的内容添加到后台缓存
        [HttpPost]
        public Common.JsonResult Delivery_ShoppingCart([FromBody]JSONoptdelivery josnde)
        {
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******Delivery_ShoppingCart begin******");
            #region 参数校验
            string vmsg = string.Empty;
            if (!josnde.CheckSelfModel(out vmsg))
            {
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion
            try
            {
                #region 修改购物车投放信息
                foreach (JSONID id in josnde.IDs)
                {
                    Entities.CartInfo cartmodel = new Entities.CartInfo();
                    cartmodel.CartID = id.CartID;
                    cartmodel.MediaType = josnde.MediaType;
                    cartmodel.MediaID = id.MediaID;
                    cartmodel.PubDetailID = id.PublishDetailID;
                    cartmodel.IsSelected = id.IsSelected;

                    BLL.CartInfo.Instance.Update(cartmodel);
                }
                #endregion
                if (!string.IsNullOrEmpty(josnde.OrderID))
                {                    
                    #region 添加到待审项目
                    Entities.ADOrderInfo order = new Entities.ADOrderInfo();
                    order = BLL.ADOrderInfo.Instance.GetADOrderInfo(josnde.OrderID);
                    if (order == null)
                    {
                        return WebAPI.Common.Util.GetJsonDataByResult(null, "更新项目失败,项目号:" + josnde.OrderID + "不存在!", -1);
                    }
                    //更新项目逻辑
                    //1拿到项目
                    ADOrderInfoV1_1BAKController.JSONADOrderInfo orderInfo = new ADOrderInfoV1_1BAKController.JSONADOrderInfo() {
                        OrderID = order.OrderID,
                        MediaType = order.MediaType,
                        OrderName = order.OrderName,
                        Status = order.Status,
                        BeginTime = order.BeginTime,
                        EndTime = order.EndTime,
                        Note = order.Note,
                        UploadFileURL = order.UploadFileURL,
                        //CustomerID = ADOrderInfoV1_1BAKController.EncryptAndUrlEncode2CustomerID(order.CustomerID)
                    };
                    
                    //2拿到广告位
                    Entities.QueryADDetailInfo queryADDetailInfo = new Entities.QueryADDetailInfo() {
                        OrderID=order.OrderID
                    };
                    int icount = 0;
                    DataTable dtADDetailInfo = BLL.ADDetailInfo.Instance.GetADDetailInfo(queryADDetailInfo, " a.CreateTime DESC ", 1, 99999, out icount);
                    List<ADOrderInfoV1_1BAKController.JSONADDetailInfo> listDetail = new List<ADOrderInfoV1_1BAKController.JSONADDetailInfo>();

                    foreach (DataRow rowADDetailInfo in dtADDetailInfo.Rows)
                    {
                        Entities.ADDetailInfo entityADDetailInfo = BLL.ADDetailInfo.Instance.DataRowToModel(rowADDetailInfo);
                        //广告位排期
                        List<ADOrderInfoV1_1BAKController.JSONADScheduleInfo2> listADSchedule = new List<ADOrderInfoV1_1BAKController.JSONADScheduleInfo2>();
                        Entities.QueryADScheduleInfo query_ADScheduleInfo = new Entities.QueryADScheduleInfo() {
                            ADDetailID=entityADDetailInfo.RecID
                        };
                        DataTable dtADSchedule = BLL.ADScheduleInfo.Instance.GetADScheduleInfo(query_ADScheduleInfo, "a.BeginData asc", 1, 9999, out icount);
                        foreach (DataRow rowADSchedule in dtADSchedule.Rows)
                        {
                            Entities.ADScheduleInfo entityADSchedule = BLL.ADScheduleInfo.Instance.DataRowToModel(rowADSchedule);
                            listADSchedule.Add(new ADOrderInfoV1_1BAKController.JSONADScheduleInfo2() {
                                BeginData=entityADSchedule.BeginData,
                                EndData=entityADSchedule.EndData
                            });
                        }

                        listDetail.Add(new ADOrderInfoV1_1BAKController.JSONADDetailInfo() {
                            MediaID=entityADDetailInfo.MediaID,
                            PubDetailID=entityADDetailInfo.PubDetailID,
                            AdjustPrice=entityADDetailInfo.AdjustPrice,
                            AdjustDiscount=entityADDetailInfo.AdjustDiscount,
                            ADLaunchDays=entityADDetailInfo.ADLaunchDays,
                            ADScheduleInfos=listADSchedule
                        });
                    }

                    //3拿购物车中广告位
                    foreach (JSONID entityID in josnde.IDs)
                    {
                        if(entityID.IsSelected==1)
                        {
                            //排期查询
                            Entities.QueryCartScheduleInfo query_CartScheduleInfo = new Entities.QueryCartScheduleInfo()
                            {
                                CartID = entityID.CartID
                            };

                            List<ADOrderInfoV1_1BAKController.JSONADScheduleInfo2> listADSchedule = new List<ADOrderInfoV1_1BAKController.JSONADScheduleInfo2>();
                            DataTable dt_CartScheduleInfo = BLL.CartScheduleInfo.Instance.GetCartScheduleInfo(query_CartScheduleInfo, " a.BeginTime ASC ", 1, 9999, out icount);
                            foreach (DataRow row_CartScheduleInfo in dt_CartScheduleInfo.Rows)
                            {
                                Entities.CartScheduleInfo entityCartScheduleInfo = BLL.CartScheduleInfo.Instance.DataRowToModel(row_CartScheduleInfo);
                                listADSchedule.Add(new ADOrderInfoV1_1BAKController.JSONADScheduleInfo2()
                                {
                                    BeginData = entityCartScheduleInfo.BeginTime,
                                    EndData = Entities.Constants.Constant.DATE_INVALID_VALUE
                                });
                            }

                            listDetail.Add(new ADOrderInfoV1_1BAKController.JSONADDetailInfo()
                            {
                                MediaID = entityID.MediaID,
                                PubDetailID = entityID.PublishDetailID,                                
                                ADScheduleInfos = listADSchedule
                            });
                        }
                    }

                    //合成后总的广告位不能重复
                    if (listDetail.GroupBy(l => new { l.MediaID, l.PubDetailID }).Where(g => g.Count() > 1).Count() > 0)
                    {
                        IEnumerable<IGrouping<int, ADOrderInfoV1_1BAKController.JSONADDetailInfo>> query = listDetail.GroupBy(x => x.PubDetailID).Where(g => g.Count() > 1);
                        foreach (IGrouping<int, ADOrderInfoV1_1BAKController.JSONADDetailInfo> info in query)
                        {
                            vmsg += info.Key + ",";
                        }                       
                        if (vmsg.Contains(","))
                            vmsg = vmsg.Substring(0, vmsg.Length - 1);

                        BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]*****Delivery_ShoppingCart广告位重复vmsg->" + vmsg + "******");
                        return WebAPI.Common.Util.GetJsonDataByResult(null, "广告位ID重复:" + vmsg + "!\n", -1);
                    }
                    //4项目中的广告位和购物车选中广告位合成
                    //ADOrderInfoV1_1BAKController.ModifyOrderInfo(orderInfo, listDetail,out vmsg);
                    if (!string.IsNullOrEmpty(vmsg))
                    {
                        return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
                    }
                    #endregion
                }                
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******Delivery_ShoppingCart 出错errormsg:" + ex.Message);
                return WebAPI.Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******Delivery_ShoppingCart end******");
            return WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功", 0);
        }
        
        #endregion
        #region 获取当前购物车里面的内容
        [HttpGet]
        public Common.JsonResult GetInfo_ShoppingCart(int MediaType)
        {
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******GetInfo_ShoppingCart begin******");
            Common.JsonResult jr = new Common.JsonResult();
            jr.Message = "操作成功";

            //获取购物车信息
            System.Data.DataTable dt = BLL.CartInfo.Instance.ADCartInfoDetail_SelectV1_1(MediaType, currentUserID);
            if (dt == null || dt.Rows.Count == 0)
            {
                return WebAPI.Common.Util.GetJsonDataByResult(null, "购物车时没有任何信息", -1);
            }

            JSONcartinfo cart = new JSONcartinfo();
            cart.MediaType = MediaType;
            List<JSONAPPMedia> appList = new List<JSONAPPMedia>();
            List<JSONMediaOwner> selfList = new List<JSONMediaOwner>();


            try
            {
                if (MediaType == (int)Entities.EnumMediaType.APP)
                {
                    #region APP
                    cart.SelfMedia = null;
                    decimal totalamount = 0;
                    foreach (System.Data.DataRow row in dt.Rows)
                    {
                        JSONAPPMedia app = new JSONAPPMedia();
                        if (row["MediaID"] != null && row["MediaID"].ToString() != "")
                        {
                            app.MediaID = int.Parse(row["MediaID"].ToString());
                        }
                        if (row["PubDetailID"] != null && row["PubDetailID"].ToString() != "")
                        {
                            app.PublishDetailID = int.Parse(row["PubDetailID"].ToString());
                        }
                        if (row["Name"] != null && row["Name"].ToString() != "")
                        {
                            app.Name = row["Name"].ToString();
                        }
                        if (row["AdPosition"] != null && row["AdPosition"].ToString() != "")
                        {
                            app.AdPosition = row["AdPosition"].ToString();
                        }
                        if (row["AdForm"] != null && row["AdForm"].ToString() != "")
                        {
                            app.AdForm = row["AdForm"].ToString();
                        }
                        if (row["Style"] != null && row["Style"].ToString() != "")
                        {
                            app.Style = row["Style"].ToString();
                        }
                        if (row["CarouselCount"] != null && row["CarouselCount"].ToString() != "")
                        {
                            app.CarouselCount = int.Parse(row["CarouselCount"].ToString());
                        }
                        if (row["PlayPosition"] != null && row["PlayPosition"].ToString() != "")
                        {
                            app.PlayPosition = row["PlayPosition"].ToString();
                        }

                        if (row["SysPlatform"] != null && row["SysPlatform"].ToString() != "")
                        {
                            string[] s = row["SysPlatform"].ToString().Split(',');
                            string sys = "";
                            foreach (string item in s)
                            {
                                if (item == "12001")
                                {
                                    sys += "Android,";
                                }
                                else
                                {
                                    sys += "IOS,";
                                }
                            }
                            sys = sys.Substring(0, sys.Length - 1);
                            app.SysPlatform = sys;
                        }
                        if (row["Price"] != null && row["Price"].ToString() != "")
                        {
                            app.Price = Convert.ToDecimal(row["Price"].ToString());
                        }
                        if (row["BeginPlayDays"] != null && row["BeginPlayDays"].ToString() != "")
                        {
                            app.BeginPlayDays = Convert.ToInt32(row["BeginPlayDays"].ToString());
                        }
                        if (row["CPDCPM"] != null && row["CPDCPM"].ToString() != "")
                        {
                            app.CPDCPM = Convert.ToInt32(row["CPDCPM"].ToString());
                        }

                        if (row["IsSelected"] != null && row["IsSelected"].ToString() != "")
                        {
                            app.IsSelected = Convert.ToByte(row["IsSelected"]);
                        }

                        if (row["PublishStatus"] != null && row["PublishStatus"].ToString() != "")
                        {
                            app.PublishStatus = Convert.ToInt32(row["PublishStatus"].ToString());
                        }
                        if (row["expired"] != null && row["expired"].ToString() != "")
                        {
                            app.expired = Convert.ToInt32(row["expired"].ToString());
                        }

                        app.Amount = app.Price * app.BeginPlayDays;
                        appList.Add(app);
                        totalamount += app.Amount;
                    }

                    cart.TotalAmount = totalamount;
                    #endregion
                }
                else
                {
                    cart.APP = null;
                    decimal totalamount = 0;                    
                    var query = from t in dt.AsEnumerable()
                                group t by new { t1 = t.Field<string>("Source") } into CartInfo
                                select new
                                {
                                    Source=CartInfo.Key.t1,
                                    Details=CartInfo
                                };

                    foreach (var detail in query)
                    {
                        //按媒体主维度分组
                        JSONMediaOwner self = new JSONMediaOwner();
                        self.Medias = new List<JSONSelfMedia2>();
                        self.MediaOwner = detail.Source;
                        List<DataRow> dataRows = detail.Details.ToList();
                        foreach (DataRow row in dataRows)
                        {
                            JSONSelfMedia2 s = new JSONSelfMedia2();
                            #region 赋值
                            if (row["CartID"] != null && row["CartID"].ToString() != "")
                            {
                                s.CartID = Convert.ToInt32(row["CartID"]);
                            }
                            if (row["MediaID"] != null && row["MediaID"].ToString() != "")
                            {
                                s.MediaID = Convert.ToInt32(row["MediaID"]);
                            }
                            if (row["PubDetailID"] != null && row["PubDetailID"].ToString() != "")
                            {
                                s.PublishDetailID = Convert.ToInt32(row["PubDetailID"]);
                            }
                            if (row["IsSelected"] != null && row["IsSelected"].ToString() != "")
                            {
                                s.IsSelected = Convert.ToByte(row["IsSelected"]);
                            }
                            if (row["IsAuth"] != null && row["IsAuth"].ToString() != "")
                            {
                                s.IsAuth = row["IsAuth"].ToString();
                            }
                            if (row["ADMasterImage"] != null && row["ADMasterImage"].ToString() != "")
                            {
                                s.ADMasterImage = row["ADMasterImage"].ToString();
                            }
                            if (row["MediaStatus"] != null && row["MediaStatus"].ToString() != "")
                            {
                                s.MediaStatus = Convert.ToInt32(row["MediaStatus"]);
                            }
                            if (row["PublishStatus"] != null && row["PublishStatus"].ToString() != "")
                            {
                                s.PublishStatus = Convert.ToInt32(row["PublishStatus"]);
                            }
                            if (row["ADMasterTitle"] != null && row["ADMasterTitle"].ToString() != "")
                            {
                                s.ADMasterTitle = row["ADMasterTitle"].ToString();
                            }
                            if (row["PubBeginTime"] != null && row["PubBeginTime"].ToString() != "")
                            {
                                s.PubBeginTime = Convert.ToDateTime(row["PubBeginTime"]);
                            }
                            if (row["PubEndTime"] != null && row["PubEndTime"].ToString() != "")
                            {
                                s.PubEndTime = Convert.ToDateTime(row["PubEndTime"]);
                            }
                            if (row["expired"] != null && row["expired"].ToString() != "")
                            {
                                s.expired = Convert.ToInt32(row["expired"].ToString());
                            }
                            if (row["ADPosition"] != null && row["ADPosition"].ToString() != "")
                            {
                                s.ADPosition = row["ADPosition"].ToString();
                            }
                            if (row["CreateType"] != null && row["CreateType"].ToString() != "")
                            {
                                s.CreateType = row["CreateType"].ToString();
                            }
                            if (row["Price"] != null && row["Price"].ToString() != "")
                            {
                                s.Price = Convert.ToDecimal(row["Price"].ToString());
                            }
                            if (row["TotalAmmount"] != null && row["TotalAmmount"].ToString() != "")
                            {
                                s.TotalAmmount = Convert.ToDecimal(row["TotalAmmount"].ToString());
                            }
                            #endregion
                            #region 查询排期
                            DataTable dtt = BLL.CartInfo.Instance.ADCartScheduleInfo_Select(s.CartID);
                            List<JSONCartADSchedule> cartScheduleList = new List<JSONCartADSchedule>();
                            if (dtt != null && dtt.Rows.Count > 0)
                            {
                                foreach (DataRow cartRow in dtt.Rows)
                                {
                                    cartScheduleList.Add(
                                        new JSONCartADSchedule() {
                                            RecID = Convert.ToInt32(cartRow["RecID"]),
                                            BeginTime = Convert.ToDateTime(cartRow["BeginTime"])
                                        }
                                        );
                                }
                            }                            
                            s.ADSchedule = cartScheduleList;
                            #endregion
                            self.Medias.Add(s);
                            totalamount += s.Price;
                        }
                        selfList.Add(self);
                    }
                                                                              
                    cart.TotalAmount = totalamount;
                }
                cart.APP = appList;
                cart.SelfMedia = selfList;

                return WebAPI.Common.Util.GetJsonDataByResult(cart, "操作成功");
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******GetInfo_ShoppingCart,errormsg:" + ex.Message);
                return WebAPI.Common.Util.GetJsonDataByResult(null, "出错:"+ ex.Message,-1);
            }
            
        }
        #endregion
        #region 添加修改删除排期
        [HttpPost]
        public Common.JsonResult ADScheduleOpt_ShoppingCart([FromBody]JSONADScheduleOpt jsoncart)
        {
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******ADScheduleOpt_ShoppingCart begin******");
            try
            {
                string listd = Newtonsoft.Json.JsonConvert.SerializeObject(jsoncart);
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]*****ADScheduleOpt_ShoppingCart->" + listd + "******");
            }
            catch (Exception ex)
            { }
            #region 参数校验
            string vmsg = string.Empty;
            if (!jsoncart.CheckSelfModel(out vmsg))
            {
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion

            try
            {
                int RecIDNew = 0;
                vmsg = BLL.CartInfo.Instance.CartScheduleInfo_Oper(jsoncart.OptType, jsoncart.CartID,jsoncart.RecID, jsoncart.BeginTime, currentUserID,out RecIDNew);
                if (!string.IsNullOrEmpty(vmsg))
                {                    
                    return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
                }

                if (jsoncart.OptType == 1)
                { return WebAPI.Common.Util.GetJsonDataByResult(null, RecIDNew.ToString()); }
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******ADScheduleOpt_ShoppingCart 出错:" + ex.Message);
                vmsg = "出错:" + ex.Message;
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******ADScheduleOpt_ShoppingCart end******");
            return WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功");
        }
        #endregion
        #region 根据媒体类型查询AE待审项目列表
        [HttpGet]
        public Common.JsonResult OrderIDName_FuzzyQuery(int MediaType)
        {
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******OrderIDName_FuzzyQuery begin******>" + MediaType);
            
            #region 参数校验
            string vmsg = string.Empty;
            //if (!jsoncart.CheckSelfModel(out vmsg))
            //{
            //    return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            //}
            #endregion

            try
            {
                //业务逻辑
                DataTable dt = BLL.CartInfo.Instance.OrderIDName_Select(MediaType, currentUserID, out vmsg);
                if (!string.IsNullOrEmpty(vmsg))
                {
                    return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
                }

                if (dt != null && dt.Rows.Count > 0)
                { }
                else
                {
                    return WebAPI.Common.Util.GetJsonDataByResult(null, "没有数据", 0);
                }

                List<JSONOrderIDName> list_idname = new List<JSONOrderIDName>();
                foreach (DataRow row in dt.Rows)
                {
                    list_idname.Add(new JSONOrderIDName()
                    {
                        OrderID = Convert.ToString(row["OrderID"]),
                        OrderName = Convert.ToString(row["OrderName"]),
                    });
                }                                             
                return WebAPI.Common.Util.GetJsonDataByResult(list_idname, "操作成功");
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******OrderIDName_FuzzyQuery 出错:" + ex.Message);
                vmsg = "出错:" + ex.Message;
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******OrderIDName_FuzzyQuery end******");            
        }

        #region 添加购物车
        /// <summary>
        /// 添加购物车
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddShoppingCart([FromBody]JSONAddCart jsoncart)
        {
            /**
             * 1购物车中最多3个广告位
             * 2每个广告位最多3个排期
             * 3广告位排期 天不能重复
             * **/
            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart begin******");
            try
            {
                string listd = Newtonsoft.Json.JsonConvert.SerializeObject(jsoncart);
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]*****AddShoppingCart->" + listd + "******");
            }
            catch (Exception ex)
            { }
            #region 参数校验
            string vmsg = string.Empty;
            if (!jsoncart.CheckSelfModel(out vmsg))
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart 验证出错:" + vmsg);
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion

            try
            {

                foreach (JSONAPP app in jsoncart.IDs)
                {
                    Entities.CartInfo cartmodel = new Entities.CartInfo();
                    cartmodel.MediaType = jsoncart.MediaType;
                    cartmodel.MediaID = app.MediaID;
                    cartmodel.PubDetailID = app.PublishDetailID;
                    cartmodel.IsSelected = 1;
                    cartmodel.CreateUserID = currentUserID;
                    cartmodel.ADSchedule = app.ADSchedule;
                    int cartid;
                    vmsg = BLL.CartInfo.Instance.InsertV1_1_8(cartmodel,out cartid);
                    if (!string.IsNullOrEmpty(vmsg))
                    {
                        BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart 验证出错:" + vmsg);
                        return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
                    }                    
                }
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart 出错:" + ex.Message);
                vmsg = "出错:" + ex.Message;
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCart end******");
            return WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功");
        }
        #endregion
        #region APP添加购物车
        /// <summary>
        /// 添加购物车
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        [ApiLog]
        public JsonResult AddShoppingCartAPP([FromBody]RequestAPPAddShoppingDto reqDto)
        {
            /**
             * 广告位定义:广告位ID+售卖区域ID
             * 1排期时间跨度要在所属刊例执行周期内
             * 2排期时间跨度不能超过6个月
             * 3相同广告位排期时间不能有交差            
             * **/
            #region 参数校验
            string vmsg = string.Empty;
            if (!reqDto.CheckSelfModel(out vmsg))
            {
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCartAPP 验证出错:" + vmsg);
                return Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion

            try
            {                                
                foreach (RequestAPPAddShppingIDDto reqID in reqDto.IDs)
                {
                    foreach (RequestAPPAddShppingADScheduleDto reqSchedule in reqID.ADSchedule)
                    {
                        Entities.CartInfo cartEntity = new Entities.CartInfo() {
                            MediaType=reqDto.MediaType,
                            MediaID=reqID.MediaID,
                            PubDetailID=reqID.PublishDetailID,
                            SaleArea=reqID.SaleAreaID,
                            BeginData=reqSchedule.BeginData,
                            EndData=reqSchedule.EndData,
                            ADLaunchDays=reqID.ADLaunchDays,
                            IsSelected=1,
                            CreateUserID=currentUserID                         
                        };

                        int cartid;
                        vmsg = CartInfo.Instance.InsertAPPV1_1_8(cartEntity, out cartid);
                        if (!string.IsNullOrEmpty(vmsg))
                        {
                            Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCartAPP 验证出错:" + vmsg);
                            return Common.Util.GetJsonDataByResult(null, vmsg, -1);
                        }
                    }
                }
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCartAPP end******");
                return Common.Util.GetJsonDataByResult(null, "操作成功");
            }
            catch (Exception ex)
            {
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******AddShoppingCartAPP 出错:" + ex.Message);
                return Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }
                                    
        }
        #endregion
        #region 删除购物车
        [HttpGet]
        [ApiLog]
        public JsonResult DeleteShoppingCart(string cartids)
        {
            #region 参数校验           
            if (string.IsNullOrEmpty(cartids))
            {
                return Common.Util.GetJsonDataByResult(null, "购物车ID串不能为空", -1);
            }
            #endregion

            try
            {
                //根据购物车Cartid删除广告位记录、删除排期信息
                CartInfo.Instance.DeleteV1_1(currentUserID, cartids);
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******DeleteShoppingCart end******");
                return Common.Util.GetJsonDataByResult(null, "操作成功");
            }
            catch (Exception ex)
            {
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******DeleteShoppingCart 出错:" + ex.Message);
                return Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }            
        }
        #endregion
        #region 购物车投放
        [HttpPost]
        [ApiLog]
        public JsonResult Delivery_ShoppingCart([FromBody]RequestDeliveryShoppingDto reqDto)
        {
            #region 参数校验
            string vmsg = string.Empty;
            if (!reqDto.CheckSelfModel(out vmsg))
            {
                return Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion
            try
            {
                #region 修改购物车投放信息
                foreach (RequestDeliveryShoppingIDDto reqID in reqDto.IDs)
                {
                    Entities.CartInfo cartEntity = new Entities.CartInfo() {
                        MediaType=reqID.MediaType,
                        CartID=reqID.CartID,
                        MediaID=reqID.MediaID,
                        PubDetailID=reqID.PublishDetailID,
                        SaleArea=reqID.SaleAreaID,
                        ADLaunchDays=reqID.ADLaunchDays,
                        IsSelected=reqID.IsSelected

                    };
                    vmsg = CartInfo.Instance.Delivery(cartEntity);
                    if(!string.IsNullOrEmpty(vmsg))
                        return Common.Util.GetJsonDataByResult(null, vmsg, -1);
                }
                #endregion
                #region 添加到待审项目
                if (!string.IsNullOrEmpty(reqDto.OrderID))
                {
                    if (reqDto.IDs.Where(p => p.IsSelected == 1).Count() == 0)
                        return Common.Util.GetJsonDataByResult(null, "请至少选择一个广告位添加到待审项目!", -1);

                    RequestADOrderDto resADOrder;
                    List<RequestMediaOrderInfoDto> resMOIList;
                    List<RequestADDetailDto> resADDetailsList;
                    ADOrderInfo.Instance.QueryAEOrderInfo(reqDto.OrderID, out resADOrder, out resMOIList, out resADDetailsList);
                    try
                    {
                        //加密
                        resADOrder.CustomerID = XYAuto.Utils.Security.DESEncryptor.Encrypt(resADOrder.CustomerIDINT.ToString(), LoginPwdKey);
                        //编码
                        resADOrder.CustomerID = System.Web.HttpUtility.UrlEncode(resADOrder.CustomerID, Encoding.UTF8);
                    }
                    catch (Exception ex)
                    {
                        Loger.Log4Net.Info("[Delivery_ShoppingCart]QueryAEOrderInfo 客户ID加密编码出错:->" + ex.Message);
                    }

                    //更新项目逻辑
                    //1拿到项目
                    if (resADOrder == null)
                        return Common.Util.GetJsonDataByResult(null, "更新项目失败,项目号:" + resADOrder.OrderID + "不存在!", -1);


                    //2拿到广告位
                    if (resADDetailsList.Count == 0)
                        return Common.Util.GetJsonDataByResult(null, "没有广告位,项目号:" + resADOrder.OrderID, -1);

                    foreach (RequestADDetailDto rowADDetailInfo in resADDetailsList)
                    {
                        rowADDetailInfo.ADScheduleInfos = ADScheduleInfo.Instance.QueryByADDetailID(rowADDetailInfo.RecID);
                    }

                    //3拿购物车中广告位
                    foreach (RequestDeliveryShoppingIDDto reqID in reqDto.IDs)
                    {
                        if (reqID.IsSelected == 1)
                        {
                            //排期查询
                            List<RequestADScheduleInfoDto> adSheduleList = CartScheduleInfo.Instance.QueryByCartID(reqID.CartID);

                            resADDetailsList.Add(new RequestADDetailDto()
                            {
                                CartID=reqID.CartID,
                                MediaType = reqID.MediaType,
                                MediaID = reqID.MediaID,
                                PubDetailID = reqID.PublishDetailID,
                                SaleAreaID=reqID.SaleAreaID,
                                ADScheduleInfos = adSheduleList
                            });
                        }
                    }

                    #region 合成后总的广告位不能重复(修改项目中验证)
                    //微信验证
                    //#region 按排期拆单前逻辑
                    ////var queryWeChat = resADDetailsList.Where(l => l.MediaType == 14001);
                    ////if (queryWeChat.GroupBy(l => new { l.MediaID, l.PubDetailID }).Where(g => g.Count() > 1).Count() > 0)
                    ////{
                    ////    IEnumerable<IGrouping<int, RequestADDetailDto>> query = queryWeChat.GroupBy(x => x.PubDetailID).Where(g => g.Count() > 1);
                    ////    foreach (IGrouping<int, RequestADDetailDto> info in query)
                    ////    {
                    ////        vmsg += info.Key + ",";
                    ////    }
                    ////    if (vmsg.Contains(","))
                    ////        vmsg = vmsg.Substring(0, vmsg.Length - 1);

                    ////    Loger.Log4Net.Info("[ShoppingCartV1_1Controller]*****Delivery_ShoppingCart广告位重复vmsg->" + vmsg + "******");
                    ////    return Common.Util.GetJsonDataByResult(null, "广告位ID重复:" + vmsg + "!\n", -1);
                    ////}
                    //#endregion

                    //var queryWeChat = resADDetailsList.Where(x => x.MediaType == 14001);
                    //var itemGroupsWeChat = queryWeChat.GroupBy(x => x.PubDetailID);
                    //foreach (var itemGroup in itemGroupsWeChat)
                    //{
                    //    if (itemGroup.Count() > 3)
                    //        vmsg += "微信同一广告位最多投放3个!\n";

                    //    List<RequestADScheduleInfoDto> allADScheduleInfos = new List<RequestADScheduleInfoDto>();
                    //    foreach (var item in itemGroup)
                    //    {
                    //        if (item.ADScheduleInfos == null || item.ADScheduleInfos.Count == 0 || item.ADScheduleInfos.Count > 1)
                    //        {
                    //            vmsg += "广告位必须且只能有1个排期!\n";
                    //        }
                    //        allADScheduleInfos.AddRange(item.ADScheduleInfos);
                    //    }
                    //    if (allADScheduleInfos.GroupBy(l => l.BeginData.Date).Where(g => g.Count() > 1).Count() > 0)
                    //    {
                    //        vmsg += "排期精确到天不能重复!\n";
                    //    }
                    //}
                    //#region APP广告位验证
                    //var queryAPP = resADDetailsList.Where(x => x.MediaType == 14002);
                    ///**
                    // * 广告位定义:广告位ID+区域ID
                    // * 1广告位自己的排期不可以有交集
                    // * 2不同广告位所属排期不可以有交集                   
                    //**/
                    //var itemGroups = queryAPP.GroupBy(l => l.PubDetailID);
                    //foreach (var itemGroup in itemGroups)
                    //{
                    //    var queryGroup2 = itemGroup.GroupBy(x => x.SaleAreaID);
                    //    foreach (var itemGroup2 in queryGroup2)
                    //    {
                    //        foreach (var item in itemGroup2)
                    //        {
                    //            if (item.ADScheduleInfos.Count > 1)
                    //            {
                    //                foreach (var itemADS in item.ADScheduleInfos)
                    //                {
                    //                    var queryADS = from t in item.ADScheduleInfos
                    //                                   where t.BeginData != itemADS.BeginData && t.EndData != itemADS.EndData
                    //                                    && ((Convert.ToDateTime(itemADS.BeginData.ToShortDateString()) >= Convert.ToDateTime(t.BeginData.ToShortDateString()) && Convert.ToDateTime(itemADS.BeginData.ToShortDateString()) <= Convert.ToDateTime(t.EndData.ToShortDateString()))
                    //                                        ||
                    //                                        (Convert.ToDateTime(itemADS.BeginData.ToShortDateString()) <= Convert.ToDateTime(t.BeginData.ToShortDateString()) && Convert.ToDateTime(itemADS.BeginData.ToShortDateString()) >= Convert.ToDateTime(t.EndData.ToShortDateString()))
                    //                                        ||
                    //                                        (Convert.ToDateTime(itemADS.BeginData.ToShortDateString()) <= Convert.ToDateTime(t.BeginData.ToShortDateString()) && Convert.ToDateTime(itemADS.EndData.ToShortDateString()) >= Convert.ToDateTime(t.BeginData.ToShortDateString()))
                    //                                        ||
                    //                                        (Convert.ToDateTime(itemADS.BeginData.ToShortDateString()) <= Convert.ToDateTime(t.EndData.ToShortDateString()) && Convert.ToDateTime(itemADS.EndData.ToShortDateString()) >= Convert.ToDateTime(t.EndData.ToShortDateString()))
                    //                                       )
                    //                                   select t;
                    //                    if (queryADS.Count() > 0)
                    //                    {
                    //                        return Common.Util.GetJsonDataByResult(null, "APP广告位排期有重复!", -1);
                    //                    }
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    //#endregion
                    #endregion

                    //4项目中的广告位和购物车选中广告位合成
                    RequestADOrderInfoDto resADOrderDto = new RequestADOrderInfoDto()
                    {
                        ADOrderInfo = resADOrder,
                        MediaOrderInfos = resMOIList,
                        ADDetails = resADDetailsList,
                        optType = 2
                    };
                    #region 生成项目媒体空记录
                    //var queryADDetails = from x in resADDetailsList
                    //                     select x.MediaType;
                    //var detailMediaType = queryADDetails.Distinct();
                    //var mediaOrderMediaType = from x in resMOIList
                    //                          select x.MediaType;
                    //var exceptMediaType = detailMediaType.Except(mediaOrderMediaType.Distinct());
                    //foreach (var item in exceptMediaType)
                    //{
                    //    resMOIList.Add(new RequestMediaOrderInfoDto()
                    //    {
                    //        MediaType = item
                    //    });
                    //}
                    #endregion
                    string orderid = string.Empty;
                    ADOrderInfo.Instance.AddOrderInfo(resADOrderDto, out orderid, out vmsg, true);
                    if (!string.IsNullOrEmpty(vmsg))
                    {
                        return Common.Util.GetJsonDataByResult(null, vmsg, -1);
                    }
                }
                #endregion
                return Common.Util.GetJsonDataByResult(null, "操作成功");
            }
            catch (Exception ex)
            {
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******Delivery_ShoppingCart 出错errormsg:" + ex.Message);
                return Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }
        }
        
        #endregion
        #region 查询购物车        
        [HttpGet]
        [ApiLog]
        public JsonResult GetInfo_ShoppingCart()
        {
            try
            {
                ResponseQueryShoppingDto responseDto = new ResponseQueryShoppingDto();
                responseDto.SelfMedia = new List<ResponseQuerySelfMediaDto>();
                responseDto.APP = new List<ResponseQueryAPPMediaDto>();

                #region 微信                 
                List<ResponseQuerySelfItemDto> mediaList = CartInfo.Instance.ADCartInfoDetailWeChat_Select(currentUserID);
               
                if (mediaList.Count > 0)
                {
                    var query = mediaList.GroupBy(x => x.Source);
                    foreach (var queryitem in query)
                    {
                        ResponseQuerySelfMediaDto selfMediaEntity = new ResponseQuerySelfMediaDto()
                        {
                            MediaOwner = queryitem.Key,
                            Medias = queryitem.ToList()
                        };
                        foreach (var mediaitem in selfMediaEntity.Medias)
                        {
                            //广告位失效、下架、过期 则不计算金额
                            if (mediaitem.expired == 0 && (mediaitem.PublishStatus == (int)Entities.Enum.AppPublishStatus.已上架
                                                            || mediaitem.PublishStatus == (int)Entities.Enum.PublishStatusEnum.已上架)
                                )
                                responseDto.TotalAmount += mediaitem.TotalAmmount;

                            mediaitem.ADSchedule = CartInfo.Instance.ADCartScheduleInfoWeChat_Select<ResponseQuerySelfADScheduleDto>(mediaitem.CartID);
                        }
                        responseDto.SelfMedia.Add(selfMediaEntity);
                    }
                }
                #endregion
                #region APP                
                List<ResponseQueryAPPItemDto> appMediaList = CartInfo.Instance.p_ADCartInfoDetailAPP_Select(currentUserID);
                
                var queryAPP = appMediaList.GroupBy(x => x.Source);
                foreach (var queryitem in queryAPP)
                {
                    ResponseQueryAPPMediaDto appEntity = new ResponseQueryAPPMediaDto()
                    {
                        MediaOwner = queryitem.Key,
                        Medias = queryitem.ToList()
                    };
                    foreach (var mediaitem in appEntity.Medias)
                    {
                        //广告位失效、下架、过期 则不计算金额
                        if (mediaitem.expired == 0 && (mediaitem.PublishStatus == (int)Entities.Enum.AppPublishStatus.已上架
                                                        || mediaitem.PublishStatus == (int)Entities.Enum.PublishStatusEnum.已上架)
                            )
                            responseDto.TotalAmount += mediaitem.TotalAmmount;

                        mediaitem.ADSchedule = CartInfo.Instance.ADCartScheduleInfoWeChat_Select<ResponseQueryAPPADScheduleDto>(mediaitem.CartID);
                        foreach (var adScheduleItem in mediaitem.ADSchedule)
                        {
                            List<ResponseQueryHolidayDto> listHoliday = new List<ResponseQueryHolidayDto>();
                            adScheduleItem.Holidays = CartInfo.Instance.p_CALHolidays(adScheduleItem.BeginData, adScheduleItem.EndData, out listHoliday);
                            adScheduleItem.Holiday = listHoliday;
                        }
                    }                    
                    responseDto.APP.Add(appEntity);
                }
                #endregion
                
                if(mediaList.Count==0 && appMediaList.Count==0)
                    return Common.Util.GetJsonDataByResult(null, "购物车时没有任何信息", -1);

                return Common.Util.GetJsonDataByResult(responseDto, "操作成功");
            }
            catch (Exception ex)
            {
                Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******GetInfo_ShoppingCart,errormsg:" + ex.Message);
                return Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }

        }
        #endregion
        #region 添加修改删除排期
        [HttpPost]
        [ApiLog]
        public JsonResult ADScheduleOpt_ShoppingCart([FromBody]RequestADScheduleOptDto requestDto)
        {
            #region 参数校验
            string vmsg = string.Empty;
            if (!requestDto.CheckSelfModel(out vmsg))
                return Common.Util.GetJsonDataByResult(null, vmsg, -1);

            #endregion

            try
            {
                int RecIDNew = 0;
                if(requestDto.MediaType==14001)
                    vmsg = BLL.CartInfo.Instance.CartScheduleInfo_OperV1_1_8(requestDto.OptType, requestDto.CartID, requestDto.RecID, requestDto.BeginTime, currentUserID,out RecIDNew);
                else
                    vmsg = BLL.CartInfo.Instance.CartScheduleInfoAPP_OperV1_1_8(requestDto.OptType, requestDto.CartID, requestDto.RecID, requestDto.BeginTime, requestDto.EndTime,currentUserID, out RecIDNew);

                if (!string.IsNullOrEmpty(vmsg))
                    return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);


                if (requestDto.OptType == 1)
                    return WebAPI.Common.Util.GetJsonDataByResult(null, RecIDNew.ToString());
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******ADScheduleOpt_ShoppingCart 出错:" + ex.Message);
                vmsg = "出错:" + ex.Message;
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }

            BLL.Loger.Log4Net.Info("[ShoppingCartV1_1Controller]******ADScheduleOpt_ShoppingCart end******");
            return WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功");
        }

        [TestMethod]
        public void AddOrderInfoTest()
        {
            RequestADOrderInfoDto reqDto = new RequestADOrderInfoDto();
            reqDto.optType = 1;
            RequestADOrderDto reqADOrder = new RequestADOrderDto() {
                OrderID = "CT20170622393",
                OrderName ="测试20170719-01hahahha",
                Status=16002,
                CustomerID= "gt86ZRCRjng%3d",
            };
            reqDto.ADOrderInfo = reqADOrder;

            List<RequestMediaOrderInfoDto> reqMediaOrderList = new List<RequestMediaOrderInfoDto>() {
                new RequestMediaOrderInfoDto() {
                    MediaType=14002,
                    Note="APP需求测试2",
                    UploadFileURL="adfadadfa"
                }
                ,
                new RequestMediaOrderInfoDto() {
                    MediaType=14001,
                    Note="wechat需求测试1",
                    UploadFileURL="adfadadfa"
                }
            };

            reqDto.MediaOrderInfos = reqMediaOrderList;

            List<RequestADDetailDto> reqADDetailList = new List<RequestADDetailDto>() {
                new RequestADDetailDto() {
                    MediaType=14001,
                    MediaID=16682,
                    PubDetailID=187342,
                    SaleAreaID=2,
                    CartID=5804,
                    ADScheduleInfos = new List<RequestADScheduleInfoDto>() {
                        new RequestADScheduleInfoDto() {
                            BeginData=DateTime.Today,
                            EndData =DateTime.Today.AddDays(1)
                        }
                    }
                }
                ,
                new RequestADDetailDto() {
                    MediaType=14001,
                    MediaID=16682,
                    PubDetailID=187342,
                    SaleAreaID=2,
                    CartID=5804,
                    ADScheduleInfos = new List<RequestADScheduleInfoDto>() {
                        new RequestADScheduleInfoDto() {
                            BeginData=DateTime.Today.AddDays(1),
                            EndData =DateTime.Today.AddDays(1)
                        }
                    }
                },
                new RequestADDetailDto() {
                    MediaType=14002,
                    MediaID=11,
                    PubDetailID=8121,
                    SaleAreaID=2501,
                    CartID=5801,
                    ADScheduleInfos = new List<RequestADScheduleInfoDto>() {
                        new RequestADScheduleInfoDto() {
                            BeginData=DateTime.Today.AddDays(1),
                            EndData =DateTime.Today.AddDays(10)
                        }
                    }
                }
                ,
                new RequestADDetailDto() {
                    MediaType=14002,
                    MediaID=11,
                    PubDetailID=8121,
                    SaleAreaID=2501,
                    CartID=5801,
                    ADScheduleInfos = new List<RequestADScheduleInfoDto>() {
                        new RequestADScheduleInfoDto() {
                            BeginData=DateTime.Today.AddDays(2),
                            EndData =DateTime.Today.AddDays(5)
                        }
                    }
                },
                //new RequestADDetailDto() {
                //    MediaType=14002,
                //    MediaID=521,
                //    PubDetailID=1080,
                //    SaleAreaID=1001,
                //    CartID=1,
                //    ADScheduleInfos = new List<RequestADScheduleInfoDto>() {
                //        new RequestADScheduleInfoDto() {
                //            BeginData=DateTime.Today.AddDays(1),
                //            EndData =DateTime.Today.AddDays(2)
                //        },                        
                //        new RequestADScheduleInfoDto() {
                //            BeginData=DateTime.Today.AddDays(3),
                //            EndData =DateTime.Today.AddDays(4)
                //        }
                //    }
                //}
            };
            reqDto.ADDetails = reqADDetailList;
            string orderid = string.Empty;
            string msg = string.Empty;
            BLL.ADOrderInfo.Instance.AddOrderInfo(reqDto, out orderid, out msg);           
            NUnit.Framework.Assert.AreEqual(string.Empty, msg);
        }
        [TestMethod]
        public void GetByOrderID_ADOrderInfoTest()
        {
            ret = ctl.GetByOrderID_ADOrderInfo("CT20170728802");
            NUnit.Framework.Assert.AreEqual(0, ret.Status);
        }
        [TestMethod]
        public void GetBySubOrderID_ADOrderInfoTest()
        {
            ret = ctl.GetBySubOrderID_ADOrderInfo("CT2017073167901");
            NUnit.Framework.Assert.AreEqual(0, ret.Status);
        }
        [TestMethod]
        public void QuerytAuditInfoTest()
        {
            ret = ctl.QuerytAuditInfo(1, 200);
            NUnit.Framework.Assert.AreEqual(0, ret.Status);
        }
        [TestMethod]
        public void QueryAPPByNameTest()
        {
            ret = ctl.QueryAPPByName("百合", -2);
            NUnit.Framework.Assert.AreEqual(0, ret.Status);
        }
        [TestMethod]
        public void GetADMasterTest()
        {
            ret = ctl.GetADMaster("测试", 2);
            NUnit.Framework.Assert.AreEqual(0, ret.Status);
        }


		public override void LoadSchedule(bool quickLoad)
		{
			LocalSchedule = BusinessObjects.Instance.ScheduleManager.GetLocalSchedule();
			InitThemeSelector();
			base.LoadSchedule(quickLoad);
		}

		protected override bool SaveSchedule(string scheduleName = "")
		{
			var nameChanged = !string.IsNullOrEmpty(scheduleName);
			if (nameChanged)
				LocalSchedule.Name = scheduleName;
			Controller.Instance.SaveSchedule(LocalSchedule, nameChanged, false, this);
			return base.SaveSchedule(scheduleName);
		}

		protected override IEnumerable<string> GetExistedScheduleNames()
		{
			return Core.AdSchedule.ScheduleManager.GetShortScheduleList().Select(s => s.ShortFileName);
		}

		private void InitThemeSelector()
		{
			FormThemeSelector.Link(Controller.Instance.DigitalPackageTheme, BusinessObjects.Instance.ThemeManager.GetThemes(SlideType.PrintWebPackage), Core.AdSchedule.SettingsManager.Instance.GetSelectedTheme(SlideType.PrintWebPackage), (t =>
			{
				Core.AdSchedule.SettingsManager.Instance.SetSelectedTheme(SlideType.PrintWebPackage, t.Name);
				Core.AdSchedule.SettingsManager.Instance.SaveSettings();
				SettingsNotSaved = true;
			}));
		}

		public override void Help_Click(object sender, EventArgs e)
		{
			HelpManager.OpenHelpLink("digitalpkg");
		}

		private void TrackOutput()
		{
			BusinessObjects.Instance.ActivityManager.AddActivity(new OutputActivity(Controller.Instance.TabDigitalPackage.Text, Schedule.BusinessName, PackageRecords.Sum(pr => pr.InvestmentCalculated)));
		}


        #region 测试用
        //public JSONQueryResultADOrerInfo Test([FromBody]JSONQueryResultADOrerInfo r)
        [HttpPost]
        public Common.JsonResult Test([FromBody] JSONAddOrUpadteRequest r)
        {
            return WebAPI.Common.Util.GetJsonDataByResult(r, "", 0);
        }
        #endregion
        #region 提交、修改主订单
        /// <summary>
        /// 提交修改订单,提交跟修改区别:就是对状态字段操作不同
        /// 修改不更新状态,提交设置状态为待审
        /// 提交(即新增):状态有(草稿、待审核)
        /// 修改:不对状态做操作(状态按原先状态值传递即可)
        /// </summary>
        /// <param name="optType"></param>
        /// <param name="orderInfo"></param>
        /// <param name="subDetailInfo"></param>
        /// <returns></returns>
        [HttpPost]
        [LoginAuthorize(IsCheckIP = false, IsCheckLogin = true)]
        public Common.JsonResult AddOrUpdate_ADOrderInfo([FromBody] JSONAddOrUpadteRequest r)
        {
            try
            {
                string listd = Newtonsoft.Json.JsonConvert.SerializeObject(r);
                BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo...JSONAddOrUpadteRequest->" + listd + "******");
            }
            catch (Exception ex)
            { }
            Entities.EnumAddModify optType = r.optType;
            BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo...begin...optType->" + optType + ",MediaTypeMediaType->" + r.ADOrderInfo.MediaType);
            //订单插入记录的初始状态是草稿
            //修改订单不影响订单状态            
            #region 参数校验
            string vmsg = string.Empty;
            if (!r.CheckSelfModel(out vmsg))
            {   
                //修改订单草稿状态下 没有广告位 要删除项目
                if (r.optType == Entities.EnumAddModify.Modify && r.ADOrderInfo.Status == (int)Entities.EnumOrderStatus.Draft && vmsg.Contains("没有广告位"))
                {                                        
                    return WebAPI.Common.Util.GetJsonDataByResult(null, BLL.ADOrderInfo.Instance.p_ADOrderAllInfo_Delete(r.ADOrderInfo.OrderID, r.ADOrderInfo.MediaType, true), -1);
                }
                return WebAPI.Common.Util.GetJsonDataByResult(null, vmsg, -1);
            }
            #endregion

            JSONADOrderInfo jorder = new JSONADOrderInfo();
            jorder = r.ADOrderInfo;
            List<JSONADDetailInfo2> jdetails = new List<JSONADDetailInfo2>();
            jdetails = r.ADDetails;
            Common.JsonResult jr = new Common.JsonResult();
            jr = WebAPI.Common.Util.GetJsonDataByResult(null, "操作成功", 0);
            try
            {
                switch (optType)
                {
                    case XYAuto.ITSC.Chitunion2017.Entities.EnumAddModify.ADD:
                        string orderid = "";
                        AddOrderInfo(jorder, jdetails, out orderid);
                        jr = WebAPI.Common.Util.GetJsonDataByResult(null, orderid, 0);
                        break;
                    case XYAuto.ITSC.Chitunion2017.Entities.EnumAddModify.Modify:
                        string msg = "";
                        ModifyOrderInfo(jorder, jdetails, out msg);
                        if (!string.IsNullOrEmpty(msg))
                        {
                            BLL.Loger.Log4Net.Info("[CommonTestController]*****ModifyOrderInfo 出错errormsg:" + msg);
                            jr = WebAPI.Common.Util.GetJsonDataByResult(null, msg, -1);
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo 出错errormsg:" + ex.Message);
                jr = WebAPI.Common.Util.GetJsonDataByResult(null, "出错:" + ex.Message, -1);
            }
            BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo...end...optType->" + optType + ",MediaTypeMediaType->" + r.ADOrderInfo.MediaType);
            return jr;
        }        
        public void AddOrderInfo(JSONADOrderInfo orderInfo, List<JSONADDetailInfo2> listDetail, out string orderid)
        {
            #region 生成主订单
            Entities.ADOrderInfo order = new Entities.ADOrderInfo();
            order.MediaType = orderInfo.MediaType;
            order.OrderName = orderInfo.OrderName;
            order.BeginTime = orderInfo.BeginTime;
            order.EndTime = orderInfo.EndTime;
            order.Note = orderInfo.Note;
            order.UploadFileURL = orderInfo.UploadFileURL;
            order.CreateTime = DateTime.Now;
            order.CreateUserID = currentUserID;
            order.Status = orderInfo.Status;
            try
            {
                //解码
                orderInfo.CustomerID = System.Web.HttpUtility.UrlDecode(orderInfo.CustomerID, Encoding.UTF8);
                //解密
                order.CustomerID = Convert.ToInt32(XYAuto.Utils.Security.DESEncryptor.Decrypt(orderInfo.CustomerID, LoginPwdKey));
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrderInfo 客户ID解码解密出错:->" + ex.Message);
            }

            orderid = BLL.ADOrderInfo.Instance.Insert(order);
            BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo...begin...optType->ADD,MediaTypeMediaType->" + orderInfo.MediaType + ",生成订单:" + orderid);
            if (!string.IsNullOrEmpty(orderInfo.UploadFileURL))
            {
                Entities.ADOrderInfo modelnew = BLL.ADOrderInfo.Instance.GetADOrderInfo(orderid);
                if (modelnew != null)
                {
                    List<string> listurl = new List<string>();
                    listurl.Add(orderInfo.UploadFileURL);
                    BLL.UploadFileInfo.UploadFileInfo.Instance.Excute(listurl, currentUserID, Entities.Enum.UploadFileEnum.OrderManage, modelnew.RecID, "ADOrderInfo");
                }
            }
            #endregion

            #region 遍历广告位 按媒体ID分组
            //自媒体记录MediaID串,APP记录PublishDetailID
            string cartids = "";
            //子订单定义:同一个媒体的所有广告位归类位一个子订单          
            IEnumerable<IGrouping<int, JSONADDetailInfo2>> query = listDetail.GroupBy(x => x.MediaID);
            decimal iprice = 0;//主订单金额
            foreach (IGrouping<int, JSONADDetailInfo2> info in query)
            {
                List<JSONADDetailInfo2> lgroup = info.ToList<JSONADDetailInfo2>();//分组后的集合

                decimal itotal = 0;
                int ipos = 0;
                string suborderid = "";
                foreach (JSONADDetailInfo2 item in lgroup)
                {
                    ipos++;

                    if (ipos == 1)
                    {
                        //生成子订单
                        Entities.SubADInfo submodel = new Entities.SubADInfo();
                        submodel.OrderID = orderid;
                        submodel.MediaType = orderInfo.MediaType;
                        submodel.MediaID = info.Key;
                        submodel.Status = orderInfo.Status;
                        submodel.CreateTime = DateTime.Now;
                        submodel.CreateUserID = currentUserID;

                        suborderid = BLL.SubADInfo.Instance.Insert(submodel);
                        BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo...begin...optType->ADD,MediaTypeMediaType->" + orderInfo.MediaType + ",生成子订单:" + suborderid);
                    }

                    //生成广告位
                    Entities.ADDetailInfo demodel = new Entities.ADDetailInfo();
                    demodel.OrderID = orderid;
                    demodel.SubOrderID = suborderid;
                    demodel.MediaType = item.MediaType;
                    demodel.MediaID = item.MediaID;
                    demodel.AdjustPrice = item.AdjustPrice;
                    demodel.AdjustDiscount = item.AdjustDiscount;
                    demodel.ADLaunchDays = item.ADLaunchDays;
                    demodel.CreateUserID = currentUserID;
                    demodel.PubDetailID = item.PubDetailID;
                    #region 根据广告位ID、媒体类型获取刊例基础信息
                    System.Data.DataTable pubDetailDT = BLL.ADOrderInfo.Instance.p_GetPubDetailInfo_Select(item.MediaType, item.PubDetailID);
                    if (pubDetailDT != null && pubDetailDT.Rows.Count > 0)
                    {
                        if (pubDetailDT.Rows[0]["PubID"] != null && pubDetailDT.Rows[0]["PubID"].ToString() != "")
                        {
                            demodel.PubID = int.Parse(pubDetailDT.Rows[0]["PubID"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["OriginalPrice"] != null && pubDetailDT.Rows[0]["OriginalPrice"].ToString() != "")
                        {
                            demodel.OriginalPrice = decimal.Parse(pubDetailDT.Rows[0]["OriginalPrice"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["PurchaseDiscount"] != null && pubDetailDT.Rows[0]["PurchaseDiscount"].ToString() != "")
                        {
                            demodel.PurchaseDiscount = decimal.Parse(pubDetailDT.Rows[0]["PurchaseDiscount"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["SaleDiscount"] != null && pubDetailDT.Rows[0]["SaleDiscount"].ToString() != "")
                        {
                            demodel.SaleDiscount = decimal.Parse(pubDetailDT.Rows[0]["SaleDiscount"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["ADLaunchIDs"] != null && pubDetailDT.Rows[0]["ADLaunchIDs"].ToString() != "")
                        {
                            demodel.ADLaunchIDs = pubDetailDT.Rows[0]["ADLaunchIDs"].ToString();
                        }
                        if (pubDetailDT.Rows[0]["ADLaunchStr"] != null && pubDetailDT.Rows[0]["ADLaunchStr"].ToString() != "")
                        {
                            demodel.ADLaunchStr = pubDetailDT.Rows[0]["ADLaunchStr"].ToString();
                        }

                        //广告位价格=销售折扣*成本价
                        //demodel.OriginalPrice = demodel.OriginalPrice * demodel.SaleDiscount;
                    }
                    #endregion

                    #region 计算价格
                    //计算价格草稿、待审状态下 成交价=销售价*折扣
                    if (orderInfo.Status == (int)Entities.EnumOrderStatus.Draft || orderInfo.Status == (int)Entities.EnumOrderStatus.PendingAudit)
                    {
                        if (orderInfo.MediaType == (int)Entities.EnumMediaType.APP)
                        {
                            demodel.AdjustPrice = demodel.OriginalPrice * demodel.SaleDiscount * demodel.ADLaunchDays;
                        }
                        else
                        {
                            demodel.AdjustPrice = demodel.OriginalPrice * demodel.SaleDiscount;
                        }
                    }
                    itotal += demodel.AdjustPrice;
                    #endregion
                    if (ipos == lgroup.Count)
                    {
                        //更新子工单金额
                        BLL.SubADInfo.Instance.UpdateTotalAmmount_SubADInfo(itotal, suborderid);
                    }


                    int detailid = 0;
                    detailid = BLL.ADDetailInfo.Instance.Insert(demodel);
                    BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrUpdate_ADOrderInfo...begin...optType->ADD,MediaTypeMediaType->" + orderInfo.MediaType + ",生成广告位:" + detailid);

                    #region APP-CPD排期
                    //CPD要保存排期信息ADLaunchIDs=11001为CPD广告
                    if (item.MediaType == (int)Entities.EnumMediaType.APP)
                    {
                        cartids += item.PubDetailID + ",";
                        int cpd = 0;
                        if (int.TryParse(demodel.ADLaunchIDs, out cpd) && cpd == 11001)
                        {
                            //生成排期信息                                                    
                            if (item.ADScheduleInfos.Count > 0)
                            {
                                List<Entities.ADScheduleInfo> list_ads = new List<Entities.ADScheduleInfo>();
                                foreach (JSONADScheduleInfo2 sc in item.ADScheduleInfos)
                                {
                                    Entities.ADScheduleInfo ads = new Entities.ADScheduleInfo();
                                    ads.ADDetailID = detailid;
                                    ads.OrderID = orderid;
                                    ads.SubOrderID = suborderid;
                                    ads.MediaID = item.MediaID;
                                    ads.PubID = demodel.PubID;
                                    ads.CreateTime = DateTime.Now;
                                    ads.CreateUserID = currentUserID;
                                    ads.BeginData = sc.BeginData;
                                    ads.EndData = sc.EndData;
                                    list_ads.Add(ads);
                                }
                                System.Data.DataTable mydt = BLL.Util.ListToDataTable<Entities.ADScheduleInfo>(list_ads);
                                BLL.ADScheduleInfo.Instance.Insert_BulkCopyToDB(mydt);
                            }
                            //if (item.ADScheduleInfos.EndsWith(";"))
                            //    item.ADScheduleInfos = item.ADScheduleInfos.Substring(0, item.ADScheduleInfos.Length - 1);
                            //foreach (string str in item.ADScheduleInfos.Split(';'))
                            //{
                            //    List<Entities.ADScheduleInfo> list_ads = new List<Entities.ADScheduleInfo>();
                            //    string[] sc = str.Split(',');
                            //    Entities.ADScheduleInfo ads = new Entities.ADScheduleInfo();
                            //    ads.ADDetailID = detailid;
                            //    ads.OrderID = orderid;
                            //    ads.SubOrderID = suborderid;
                            //    ads.MediaID = item.MediaID;
                            //    ads.PubID = demodel.PubID;
                            //    ads.CreateTime = DateTime.Now;
                            //    ads.CreateUserID = currentUserID;
                            //    ads.BeginData = Convert.ToDateTime(sc[0]);
                            //    ads.EndData = Convert.ToDateTime(sc[1]);
                            //    list_ads.Add(ads);
                            //    System.Data.DataTable mydt = BLL.Util.ListToDataTable<Entities.ADScheduleInfo>(list_ads);
                            //    BLL.ADScheduleInfo.Instance.Insert_BulkCopyToDB(mydt);
                            //}
                        }
                        else
                        {
                            BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrderInfo APP排期CPD转换int类型出错:->" + demodel.ADLaunchIDs);
                        }
                    }
                    else
                    {
                        //自媒体记录MediaID
                        cartids += item.MediaID + ",";
                    }
                    #endregion
                }
                //计算主订单金额
                iprice += itotal;
            }
            #endregion
            //更新主订单金额
            BLL.ADOrderInfo.Instance.UpdateTotalAmount_ADOrder(orderid, iprice);

            #region 清空购物车-当前订单相关的
            if (cartids.EndsWith(","))
            {
                cartids = cartids.Substring(0, cartids.Length - 1);
            }
            ClearCartInfo(orderInfo.MediaType, cartids);
            #endregion
        }
        public void ClearCartInfo(int mediaType, string cartids)
        {
            ShoppingCartController cart = new ShoppingCartController();
            cart.ClearAllCartInfo(mediaType, currentUserID, cartids);
        }
        public void ModifyOrderInfo(JSONADOrderInfo orderInfo, List<JSONADDetailInfo2> listDetail, out string msg)
        {
            BLL.Loger.Log4Net.Info("[CommonTestController]ModifyOrderInfo->订单号:" + orderInfo.OrderID + ",媒体类型:" + orderInfo.MediaType);
            msg = string.Empty;

            #region 查询并更新主订单
            Entities.ADOrderInfo order = new Entities.ADOrderInfo();
            order = BLL.ADOrderInfo.Instance.GetADOrderInfo(orderInfo.OrderID);
            if (order == null)
            {
                msg = "订单号:" + orderInfo.OrderID + ",不存在";
                return;
            }
            if (order.Status == (int)Entities.EnumOrderStatus.Draft || order.Status == (int)Entities.EnumOrderStatus.PendingAudit)
            {
                //可修改订单。
            }
            else
            {
                msg = "当前状态不允许修改订单";
                return;
            }
            //更新主订单
            order.MediaType = orderInfo.MediaType;
            order.OrderName = orderInfo.OrderName;
            order.BeginTime = orderInfo.BeginTime;
            order.EndTime = orderInfo.EndTime;
            order.Status = orderInfo.Status;
            order.Note = orderInfo.Note;
            try
            {
                //解码
                orderInfo.CustomerID = System.Web.HttpUtility.UrlDecode(orderInfo.CustomerID, Encoding.UTF8);
                //解密
                order.CustomerID = Convert.ToInt32(XYAuto.Utils.Security.DESEncryptor.Decrypt(orderInfo.CustomerID, LoginPwdKey));
            }
            catch (Exception ex)
            {
                BLL.Loger.Log4Net.Info("[CommonTestController]*****ModifyOrderInfo 客户ID解码解密出错:->" + ex.Message);
            }
            
            order.UploadFileURL = orderInfo.UploadFileURL;
            if (!string.IsNullOrEmpty(orderInfo.UploadFileURL))
            {
                List<string> listurl = new List<string>();
                listurl.Add(orderInfo.UploadFileURL);
                BLL.UploadFileInfo.UploadFileInfo.Instance.Excute(listurl, currentUserID, Entities.Enum.UploadFileEnum.OrderManage, order.RecID, "ADOrderInfo");
            }

            string orderid = orderInfo.OrderID;
            BLL.ADOrderInfo.Instance.Update(order);
            #endregion
            
            //删除排期子订单广告位
            BLL.ADOrderInfo.Instance.p_ADOrderAllInfo_Delete(orderid, order.MediaType, false);

            
            #region 遍历广告位 按媒体ID分组
            //自媒体记录MediaID串,APP记录PublishDetailID
            string cartids = "";
            //子订单定义:同一个媒体的所有广告位归类位一个子订单            
            IEnumerable<IGrouping<int, JSONADDetailInfo2>> query = listDetail.GroupBy(x => x.MediaID);
            decimal iprice = 0;//主订单金额
            foreach (IGrouping<int, JSONADDetailInfo2> info in query)
            {
                List<JSONADDetailInfo2> lgroup = info.ToList<JSONADDetailInfo2>();//分组后的集合

                decimal itotal = 0;
                int ipos = 0;
                string suborderid = "";
                foreach (JSONADDetailInfo2 item in lgroup)
                {
                    ipos++;
                    //先生成子工单
                    if (ipos == 1)
                    {
                        //生成子订单
                        Entities.SubADInfo submodel = new Entities.SubADInfo();
                        submodel.OrderID = orderid;
                        submodel.MediaType = orderInfo.MediaType;
                        submodel.MediaID = info.Key;
                        submodel.Status = order.Status;
                        submodel.CreateTime = order.CreateTime;
                        submodel.CreateUserID = order.CreateUserID;

                        suborderid = BLL.SubADInfo.Instance.Insert(submodel);
                    }

                    //生成广告位
                    Entities.ADDetailInfo demodel = new Entities.ADDetailInfo();
                    demodel.OrderID = orderid;
                    demodel.SubOrderID = suborderid;
                    demodel.MediaType = item.MediaType;
                    demodel.MediaID = item.MediaID;
                    demodel.PubDetailID = item.PubDetailID;

                    #region 根据广告位ID、媒体类型获取刊例基础信息
                    System.Data.DataTable pubDetailDT = BLL.ADOrderInfo.Instance.p_GetPubDetailInfo_Select(item.MediaType, item.PubDetailID);
                    if (pubDetailDT != null && pubDetailDT.Rows.Count > 0)
                    {
                        if (pubDetailDT.Rows[0]["PubID"] != null && pubDetailDT.Rows[0]["PubID"].ToString() != "")
                        {
                            demodel.PubID = int.Parse(pubDetailDT.Rows[0]["PubID"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["OriginalPrice"] != null && pubDetailDT.Rows[0]["OriginalPrice"].ToString() != "")
                        {
                            demodel.OriginalPrice = decimal.Parse(pubDetailDT.Rows[0]["OriginalPrice"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["PurchaseDiscount"] != null && pubDetailDT.Rows[0]["PurchaseDiscount"].ToString() != "")
                        {
                            demodel.PurchaseDiscount = decimal.Parse(pubDetailDT.Rows[0]["PurchaseDiscount"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["SaleDiscount"] != null && pubDetailDT.Rows[0]["SaleDiscount"].ToString() != "")
                        {
                            demodel.SaleDiscount = decimal.Parse(pubDetailDT.Rows[0]["SaleDiscount"].ToString());
                        }
                        if (pubDetailDT.Rows[0]["ADLaunchIDs"] != null && pubDetailDT.Rows[0]["ADLaunchIDs"].ToString() != "")
                        {
                            demodel.ADLaunchIDs = pubDetailDT.Rows[0]["ADLaunchIDs"].ToString();
                        }
                        if (pubDetailDT.Rows[0]["ADLaunchStr"] != null && pubDetailDT.Rows[0]["ADLaunchStr"].ToString() != "")
                        {
                            demodel.ADLaunchStr = pubDetailDT.Rows[0]["ADLaunchStr"].ToString();
                        }

                        //广告位价格=销售折扣*成本价
                        //demodel.OriginalPrice = demodel.OriginalPrice * demodel.SaleDiscount;
                    }
                    #endregion

                    demodel.AdjustPrice = item.AdjustPrice;
                    demodel.AdjustDiscount = item.AdjustDiscount;
                    demodel.ADLaunchDays = item.ADLaunchDays;
                    demodel.CreateUserID = order.CreateUserID;


                    #region 计算价格
                    //计算价格草稿、待审状态下 成交价=销售价*折扣
                    if (orderInfo.Status == (int)Entities.EnumOrderStatus.Draft || orderInfo.Status == (int)Entities.EnumOrderStatus.PendingAudit)
                    {
                        if (orderInfo.MediaType == (int)Entities.EnumMediaType.APP)
                        {
                            demodel.AdjustPrice = demodel.OriginalPrice * demodel.SaleDiscount * demodel.ADLaunchDays;
                        }
                        else
                        {
                            demodel.AdjustPrice = demodel.OriginalPrice * demodel.SaleDiscount;
                        }
                    }
                    itotal += demodel.AdjustPrice;
                    #endregion
                    if (ipos == lgroup.Count)
                    {
                        //更新子工单金额
                        BLL.SubADInfo.Instance.UpdateTotalAmmount_SubADInfo(itotal, suborderid);
                    }

                    int detailid = 0;
                    detailid = BLL.ADDetailInfo.Instance.Insert(demodel);

                    #region APP-CPD排期
                    //CPD要保存排期信息ADLaunchIDs=11001为CPD广告
                    if (item.MediaType == (int)Entities.EnumMediaType.APP)
                    {
                        cartids += item.PubDetailID + ",";
                        int cpd = 0;
                        if (int.TryParse(demodel.ADLaunchIDs, out cpd) && cpd == 11001)
                        {
                            //生成排期信息                           
                            if (item.ADScheduleInfos.Count > 0)
                            {
                                List<Entities.ADScheduleInfo> list_ads = new List<Entities.ADScheduleInfo>();
                                foreach (JSONADScheduleInfo2 sc in item.ADScheduleInfos)
                                {
                                    Entities.ADScheduleInfo ads = new Entities.ADScheduleInfo();
                                    ads.ADDetailID = detailid;
                                    ads.OrderID = orderid;
                                    ads.SubOrderID = suborderid;
                                    ads.MediaID = item.MediaID;
                                    ads.PubID = demodel.PubID;
                                    ads.CreateTime = DateTime.Now;
                                    ads.CreateUserID = currentUserID;
                                    ads.BeginData = sc.BeginData;
                                    ads.EndData = sc.EndData;
                                    list_ads.Add(ads);
                                }
                                System.Data.DataTable mydt = BLL.Util.ListToDataTable<Entities.ADScheduleInfo>(list_ads);
                                BLL.ADScheduleInfo.Instance.Insert_BulkCopyToDB(mydt);
                            }

                            //foreach (string str in item.ADScheduleInfos.Split(';'))
                            //{
                            //    List<Entities.ADScheduleInfo> list_ads = new List<Entities.ADScheduleInfo>();
                            //    foreach (string sc in str.Split(','))
                            //    {
                            //        Entities.ADScheduleInfo ads = new Entities.ADScheduleInfo();
                            //        ads.ADDetailID = detailid;
                            //        ads.OrderID = orderid;
                            //        ads.SubOrderID = suborderid;
                            //        ads.MediaID = item.MediaID;
                            //        ads.PubID = demodel.PubID;
                            //        ads.CreateTime = DateTime.Now;
                            //        ads.CreateUserID = currentUserID;
                            //        ads.BeginData = Convert.ToDateTime(sc[0].ToString());
                            //        ads.EndData = Convert.ToDateTime(sc[1].ToString());
                            //        list_ads.Add(ads);
                            //    }
                            //    System.Data.DataTable mydt = BLL.Util.ListToDataTable<Entities.ADScheduleInfo>(list_ads);
                            //    BLL.ADScheduleInfo.Instance.Insert_BulkCopyToDB(mydt);
                            //}
                        }
                        else
                        {
                            BLL.Loger.Log4Net.Info("[CommonTestController]*****AddOrderInfo APP排期CPD转换int类型出错:->" + demodel.ADLaunchIDs);
                        }
                    }
                    else
                    {
                        cartids += item.MediaID + ",";
                    }
                    #endregion
                }
                //计算主订单金额
                iprice += itotal;
            }

            #endregion
            //更新主订单金额
            BLL.ADOrderInfo.Instance.UpdateTotalAmount_ADOrder(orderid, iprice);

            #region 清空购物车-当前订单相关的
            if (cartids.EndsWith(","))
            {
                cartids = cartids.Substring(0, cartids.Length - 1);
            }
            //清空购物车
            ClearCartInfo(orderInfo.MediaType, cartids);
            #endregion
        }
            public bool CheckSelfModel(out string msg)
            {
                StringBuilder sb = new StringBuilder();
                msg = "";
                if (!Enum.IsDefined(typeof(Entities.EnumAddModify), optType))
                {
                    sb.Append("操作类型参数错误!");
                }
                if (ADOrderInfo == null)
                {
                    sb.Append("没有项目信息!");
                }
                else
                {

                    if (ADOrderInfo.MediaType == 0)
                    {
                        sb.Append("媒体类型值不能为0!\n");
                    }

                    if (!Enum.IsDefined(typeof(Entities.EnumOrderStatus), ADOrderInfo.Status))
                    {
                        sb.Append("订单状态错误!不能为:" + ADOrderInfo.Status);
                    }

                    #region 广告位记录必须有,但是自媒体可以没有选择具体的广告位值
                    if (ADDetails == null || ADDetails.Count == 0)
                    {
                        sb.Append("没有广告位信息!\n");
                    }
                    else
                    {
                        if (ADDetails.Count > 50)
                        {
                            sb.Append("广告位数量不能超过50!\n");
                        }
                        foreach (JSONADDetailInfo2 detail in ADDetails)
                        {
                            if (ADOrderInfo.MediaType != detail.MediaType)
                            {
                                sb.Append("广告位ID:" + detail.PubDetailID + ",媒体类型:" + detail.MediaType + "与项目类型:" + ADOrderInfo.MediaType + "必须相同!\n");
                            }
                        }
                    }
                    #endregion

                    #region 修改订单验证
                    if (optType == Entities.EnumAddModify.Modify)
                    {
                        if (string.IsNullOrEmpty(ADOrderInfo.OrderID))
                        {
                            sb.Append("修改订单操作订单号是必填项!\n");
                        }
                        if (ADOrderInfo.Status != (int)Entities.EnumOrderStatus.Draft)
                        {
                            DateTime tmpdate = new DateTime(1990, 1, 1);
                            if (ADOrderInfo.BeginTime < tmpdate || ADOrderInfo.EndTime < tmpdate)
                            {
                                sb.Append("执行周期时间格式不对!\n");
                            }                           

                            if (string.IsNullOrEmpty(ADOrderInfo.OrderName))
                            {
                                sb.Append("订单名称为必填项!\n");
                            }
                            if (string.IsNullOrEmpty(ADOrderInfo.Note))
                            {
                                sb.Append("需求说明为必填项!\n");
                            }
                            if (string.IsNullOrEmpty(ADOrderInfo.UploadFileURL))
                            {
                                sb.Append("补充附件为必填项!\n");
                            }
                            if (ADDetails != null && ADDetails.Count > 0)
                            {
                                #region 自媒体广告位媒体ID不能重复,APP广告位媒体ID和广告位ID不能重复
                                if (ADOrderInfo.MediaType != (int)Entities.EnumMediaType.APP)
                                {
                                    bool brepeat1 = ADDetails.GroupBy(l => l.MediaID).Where(g => g.Count() > 1).Count() > 0;
                                    if (brepeat1)
                                    {
                                        sb.Append("自媒体广告位媒体ID不能重复!\n");
                                    }
                                }
                                else
                                {
                                    bool brepeat2 = ADDetails.GroupBy(l => new { l.MediaID, l.PubDetailID }).Where(g => g.Count() > 1).Count() > 0;
                                    if (brepeat2)
                                    {
                                        sb.Append("APP广告位媒体ID和广告位ID不能重复!\n");
                                    }
                                }
                                #endregion
                            }
                            
                        }
                    }
                    #endregion
                }

                msg = sb.ToString();
                return msg.Length.Equals(0);
            }


		public void Init()
		{
			OutputManager.Init();
			PowerPointManager.Instance.SettingsChanged += (o, e) => OutputManager.UpdateColors();

			HelpManager.LoadHelpLinks();

			ThemeManager.Load();
			PowerPointManager.Instance.SettingsChanged += (o, e) => ThemeManager.Load();

			TabPageManager = new TabPageManager(Core.AdSchedule.ResourceManager.Instance.TabsConfigFile);
			ActivityManager = ActivityManager.OpenStorage();
			Gallery1Manager = new GalleryManager(Core.AdSchedule.ResourceManager.Instance.Gallery1ConfigFile);
			Gallery2Manager = new GalleryManager(Core.AdSchedule.ResourceManager.Instance.Gallery2ConfigFile);
			RateCardManager = new RateCardManager(Core.Common.ResourceManager.Instance.RateCardFolder);
			RateCardManager.LoadRateCards();
		}


		public void LoadSchedule(bool quickLoad)
		{
			LocalSchedule = BusinessObjects.Instance.ScheduleManager.GetLocalSchedule();
			InitThemeSelector();
			if (!quickLoad)
			{
				checkEditShowFlightDates.Text = String.Format("{0}", LocalSchedule.FlightDates);
				bool temp = AllowApplyValues;
				AllowApplyValues = false;
				AllowApplyValues = temp;
				Application.DoEvents();

				xtraTabControlProducts.SuspendLayout();
				Application.DoEvents();
				xtraTabControlProducts.SelectedPageChanged -= xtraTabControlProducts_SelectedPageChanged;
				xtraTabControlProducts.TabPages.Clear();
				_tabPages.RemoveAll(x => !LocalSchedule.DigitalProducts.Select(y => y.UniqueID).Contains(x.Product.UniqueID));
				foreach (var product in LocalSchedule.DigitalProducts)
				{
					if (string.IsNullOrEmpty(product.Name)) continue;
					var productTab = _tabPages.FirstOrDefault(x => x.Product.UniqueID.Equals(product.UniqueID));
					if (productTab == null)
					{
						productTab = new DigitalProductControl(this);
						AssignCloseActiveEditorsonOutSideClick(productTab);
						_tabPages.Add(productTab);
						Application.DoEvents();
					}
					productTab.Product = product;
					productTab.LoadValues();
					Application.DoEvents();
				}
				_tabPages.Sort((x, y) => x.Product.Index.CompareTo(y.Product.Index));
				xtraTabControlProducts.TabPages.AddRange(_tabPages.ToArray());

				var summaryControl = new DigitalSummaryControl(this);
				summaryControl.UpdateControls(_tabPages.Select(tp => tp.SummaryControl));
				xtraTabControlProducts.TabPages.Add(summaryControl);
				AssignCloseActiveEditorsonOutSideClick(summaryControl);

				Application.DoEvents();
				xtraTabControlProducts.ResumeLayout();

				LoadProduct(_tabPages.FirstOrDefault());
				Application.DoEvents();
				xtraTabControlProducts.SelectedPageChanged += xtraTabControlProducts_SelectedPageChanged;

				AllowApplyValues = true;
			}
			else
			{
				foreach (var product in LocalSchedule.DigitalProducts)
				{
					if (!string.IsNullOrEmpty(product.Name))
					{
						var productTab = _tabPages.FirstOrDefault(x => x.Product.UniqueID.Equals(product.UniqueID));
						if (productTab != null)
						{
							productTab.Product = product;
						}
						Application.DoEvents();
					}
				}
			}
			SettingsNotSaved = false;
		}

		protected override bool SaveSchedule(string scheduleName = "")
		{
			base.SaveSchedule(scheduleName);
			var nameChanged = !string.IsNullOrEmpty(scheduleName);
			if (nameChanged)
				LocalSchedule.Name = scheduleName;
			Controller.Instance.SaveSchedule((Schedule)LocalSchedule, nameChanged, false, this);
			SettingsNotSaved = false;
			return true;
		}

		private void InitThemeSelector()
		{
			FormThemeSelector.Link(Controller.Instance.DigitalProductTheme, BusinessObjects.Instance.ThemeManager.GetThemes(SlideType.PrintDigitalProduct), Core.AdSchedule.SettingsManager.Instance.GetSelectedTheme(SlideType.PrintDigitalProduct), (t =>
			{
				Core.AdSchedule.SettingsManager.Instance.SetSelectedTheme(SlideType.PrintDigitalProduct, t.Name);
				Core.AdSchedule.SettingsManager.Instance.SaveSettings();
				SettingsNotSaved = true;
			}));
		}

		public void Save_Click(object sender, EventArgs e)
		{
			SaveSchedule();
			Utilities.Instance.ShowInformation("Schedule Saved");
		}

		public void SaveAs_Click(object sender, EventArgs e)
		{
			using (var form = new FormNewSchedule(ScheduleManager.GetShortScheduleList().Select(s => s.ShortFileName)))
			{
				form.Text = "Save Schedule";
				form.laLogo.Text = "Please set a new name for your Schedule:";
				if (form.ShowDialog() == DialogResult.OK)
				{
					if (!string.IsNullOrEmpty(form.ScheduleName))
					{
						if (SaveSchedule(form.ScheduleName))
							Utilities.Instance.ShowInformation("Schedule was saved");
					}
					else
					{
						Utilities.Instance.ShowWarning("Schedule Name can't be empty");
					}
				}
			}
		}

		public void Help_Click(object sender, EventArgs e)
		{
			BusinessObjects.Instance.HelpManager.OpenHelpLink("digitalslides");
		}

Google.Api.Ads.AdWords.v201809.AdSchedule : Criterion

Constructors :

public AdSchedule()

Methods :

public DayOfWeek get_dayOfWeek()
public Void set_dayOfWeek(DayOfWeek value = )
public Boolean get_dayOfWeekSpecified()
public Void set_dayOfWeekSpecified(Boolean value = )
public Int32 get_startHour()
public Void set_startHour(Int32 value = )
public Boolean get_startHourSpecified()
public Void set_startHourSpecified(Boolean value = )
public MinuteOfHour get_startMinute()
public Void set_startMinute(MinuteOfHour value = )
public Boolean get_startMinuteSpecified()
public Void set_startMinuteSpecified(Boolean value = )
public Int32 get_endHour()
public Void set_endHour(Int32 value = )
public Boolean get_endHourSpecified()
public Void set_endHourSpecified(Boolean value = )
public MinuteOfHour get_endMinute()
public Void set_endMinute(MinuteOfHour value = )
public Boolean get_endMinuteSpecified()
public Void set_endMinuteSpecified(Boolean value = )
public Int64 get_id()
public Void set_id(Int64 value = )
public Boolean get_idSpecified()
public Void set_idSpecified(Boolean value = )
public CriterionType get_type()
public Void set_type(CriterionType value = )
public Boolean get_typeSpecified()
public Void set_typeSpecified(Boolean value = )
public String get_CriterionType()
public Void set_CriterionType(String value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()