/// <summary>
        /// 獲取滿額滿件免運的信息
        /// </summary>
        /// <param name="query"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<PromotionsAmountFareQuery> Query(PromotionsAmountFareQuery query, out int totalCount)
        {
            try
            {
                List<PromotionsAmountFareQuery> _list = _promoFareDao.Query(query, out totalCount);
                if (_list.Count > 0)
                {
                    ParametersrcDao _parameterDao = new ParametersrcDao(connStr);
                    List<BLL.gigade.Model.Parametersrc> parameterList = _parameterDao.QueryParametersrcByTypes("product_freight", "event_type", "device", "payment");
                    foreach (PromotionsAmountFareQuery item in _list)
                    {
                        var alist = parameterList.Find(m => m.ParameterType == "product_freight" && m.ParameterCode == item.type.ToString());
                        var blist = parameterList.Find(m => m.ParameterType == "event_type" && m.ParameterCode == item.event_type.ToString());
                        var clist = parameterList.Find(m => m.ParameterType == "device" && m.ParameterCode == item.device.ToString());
                        if (alist != null)
                        {
                            item.typeName = alist.parameterName;
                        }
                        if (blist != null)
                        {
                            item.event_type_name = blist.parameterName;
                        }
                        if (clist != null)
                        {
                            item.deviceName = clist.parameterName;
                        }
                        if (!string.IsNullOrEmpty(item.payment_code))
                        {
                            string[] arryPayment = item.payment_code.Split(',');//將payment_code轉化為payment_name
                            for (int i = 0; i < arryPayment.Length; i++)
                            {
                                if (arryPayment[i] != "0")
                                {
                                    var dlist = parameterList.Find(m => m.ParameterType == "payment" && m.ParameterCode == arryPayment[i].ToString());
                                    if (dlist != null)
                                    {
                                        item.payment_name += dlist.parameterName + ",";
                                    }
                                }

                            }
                            item.payment_name = item.payment_name.TrimEnd(',');
                        }
                    }
                }
                return _list;
            }
            catch (Exception ex)
            {
                throw new Exception("PromotionsAmountFareMgr-->Query-->" + ex.Message, ex);
            }
        }
        /// <summary>
        /// 獲取列表信息
        /// </summary>
        /// <param name="query">查詢條件對象</param>
        /// <param name="totalCount">返回的數據總條數</param>
        /// <returns>數據列表</returns>
        public List<PromotionsAmountFareQuery> Query(PromotionsAmountFareQuery query, out int totalCount)
        {
            StringBuilder sql = new StringBuilder();
            try
            {
                query.Replace4MySQL();
                sql.Append(" select pf.id,pf.category_id,pf.condition_id, CONCAT(pf.event_type ,right(CONCAT('00000000',pf.id),6)) as 'event_id',pf.name,pf.event_desc,pf.delivery_store,vg.group_name,");
                sql.Append(" pf.brand_id,vb.brand_name,pf.class_id,pf.product_id,pf.amount,pf.quantity,pf.fare_percent,pf.off_times,pf.site, pf.url_by,pc.banner_image,pc.category_link_url,");
                sql.Append(" uc.condition_name,pf.type ,");
                sql.Append(" pf.event_type ,pf.payment_code,pf.active,");
                sql.Append("  pf.device,pf.start start_time,pf.end end_time,pf.vendor_coverage,pf.muser,mu.user_username");
                StringBuilder tbSQL = new StringBuilder(" from promotions_amount_fare pf");
                tbSQL.Append(" left join product_category pc on pc.category_id=pf.category_id");
                tbSQL.Append(" left join vip_user_group vg on vg.group_id=pf.group_id");
                tbSQL.Append(" left join vendor_brand vb on vb.brand_id=pf.brand_id ");
                tbSQL.Append(" left join user_condition  uc on uc.condition_id =pf.condition_id ");
                tbSQL.Append(" LEFT JOIN manage_user mu ON pf.muser=mu.user_id ");
                tbSQL.Append(" where pf.status=1  ");
                if (query.expired == 0)//是未過期
                {
                    tbSQL.AppendFormat(" and pf.end >= '{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else if (query.expired == 1)
                {
                    tbSQL.AppendFormat(" and pf.end < '{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                tbSQL.Append("   order by pf.id desc");
                totalCount = 0;
                if (query.IsPage)
                {
                    System.Data.DataTable _dt = _access.getDataTable(" select count(pf.id) as totalCount " + tbSQL.ToString());
                    if (_dt != null && _dt.Rows.Count > 0)
                    {
                        totalCount = Convert.ToInt32(_dt.Rows[0]["totalCount"]);
                    }
                    tbSQL.AppendFormat(" limit {0},{1};", query.Start, query.Limit);
                }

                sql.Append(tbSQL.ToString());

                return _access.getDataTableForObj<PromotionsAmountFareQuery>(sql.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception("PromotionsAmountFareDao-->Query-->" + ex.Message + sql.ToString(), ex);
            }
        }
        /// <summary>
        /// 修改狀態
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateActive(PromotionsAmountFareQuery model)
        {
            int i = 0;
            MySqlCommand mySqlCmd = new MySqlCommand();
            MySqlConnection mySqlConn = new MySqlConnection(connStr);
            StringBuilder sql = new StringBuilder();
            try
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConn.Open();
                }
                mySqlCmd.Connection = mySqlConn;
                mySqlCmd.Transaction = mySqlConn.BeginTransaction();
                mySqlCmd.CommandType = System.Data.CommandType.Text;

                sql.Append(_prodPromoDao.DeleteProdProm(model.event_id));//先刪除在新增當active=0時照樣刪除只有active=1時才新增
                if (model.active)
                {
                    ProductCategorySet querySet = new ProductCategorySet();
                    querySet.Category_Id = Convert.ToUInt32(model.category_id);
                    ProductCategorySetDao _setDao = new ProductCategorySetDao(connStr);
                    List<ProductCategorySet> lmodelSet = _setDao.Query(querySet);
                    foreach (ProductCategorySet item in lmodelSet)
                    {
                        ProdPromo ppmodel = new ProdPromo();
                        ppmodel.product_id = Convert.ToInt32(item.Product_Id);
                        ppmodel.event_id = model.event_id;
                        ppmodel.event_type = model.event_type;
                        ppmodel.event_desc = model.event_desc;
                        ppmodel.start = model.start;
                        ppmodel.end = model.end;
                        ppmodel.page_url = model.category_link_url;
                        if (model.group_id == 0 && model.condition_id == 0)
                        {
                            ppmodel.user_specified = 0;
                        }
                        else
                        {
                            ppmodel.user_specified = 1;
                        }
                        ppmodel.kuser = model.muser;
                        ppmodel.kdate = model.modified;
                        ppmodel.muser = model.muser;
                        ppmodel.mdate = model.modified;
                        ppmodel.status = model.status;
                        sql.Append(_prodPromoDao.SaveProdProm(ppmodel));
                    }
                }
                if (model.id != 0)
                {
                    sql.Append(UpdatePromoFare(model));
                    PromotionsAmountReduce parModel = new PromotionsAmountReduce();
                    parModel.id = model.id;
                    parModel.name = model.name;
                    parModel.delivery_store = model.delivery_store;
                    parModel.group_id = model.group_id;
                    parModel.type = model.type;
                    parModel.amount = model.amount;
                    parModel.quantity = model.quantity;
                    parModel.start = model.start;
                    parModel.end = model.end;
                    parModel.created = model.created;
                    parModel.updatetime = model.modified;
                    parModel.active = model.active ? 1 : 0;
                    parModel.status = model.status;
                    sql.Append(_promAmountReduceDao.Update(parModel));
                }
                mySqlCmd.CommandText = sql.ToString();
                i += mySqlCmd.ExecuteNonQuery();
                mySqlCmd.Transaction.Commit();
            }
            catch (Exception ex)
            {
                mySqlCmd.Transaction.Rollback();
                throw new Exception("PromotionsAmountFareDao-->UpdateActive-->" + ex.Message + sql.ToString(), ex);
            }
            finally
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
                {
                    mySqlConn.Close();
                }
            }
            return i;
        }
 /// <summary>
 /// 修改promotionsamountfare的sql語句,用於事物的調用
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public string UpdatePromoFare(PromotionsAmountFareQuery model)
 {
     model.Replace4MySQL();
     StringBuilder sql = new StringBuilder();
     try
     {
         sql.AppendFormat("update  promotions_amount_fare  set ");
         sql.AppendFormat("name='{0}',display='{1}',delivery_store='{2}',group_id='{3}',class_id='{4}'", model.name, model.display, model.delivery_store, model.group_id, model.class_id);
         sql.AppendFormat(",brand_id='{0}',category_id='{1}',product_id='{2}',type='{3}',amount='{4}',quantity='{5}'", model.brand_id, model.category_id, model.product_id, model.type, model.amount, model.quantity);
         sql.AppendFormat(",start='{0}',end='{1}',active={2},event_desc='{3}'", CommonFunction.DateTimeToString(model.start), CommonFunction.DateTimeToString(model.end), model.active ? 1 : 0, model.event_desc);
         sql.AppendFormat(",event_type='{0}',condition_id='{1}',device='{2}',fare_percent='{3}',payment_code='{4}'", model.event_type, model.condition_id, model.device, model.fare_percent, model.payment_code);
         sql.AppendFormat(",off_times='{0}',url_by='{1}',modified='{2}',muser='******',site='{4}',status='{5}',vendor_coverage='{6}'", model.off_times, model.url_by, CommonFunction.DateTimeToString(model.modified), model.muser, model.site, model.status, model.vendor_coverage);
         sql.AppendFormat("  where id='{0}';", model.id);
         return sql.ToString();
     }
     catch (Exception ex)
     {
         throw new Exception("PromotionsAmountFareDao-->UpdatePromoFare-->" + ex.Message, ex);
     }
 }
 public int Delete(int id)
 {
     int i = 0;
     MySqlCommand mySqlCmd = new MySqlCommand();
     MySqlConnection mySqlConn = new MySqlConnection(connStr);
     string sqlSW = "";
     try
     {
         if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
         {
             mySqlConn.Open();
         }
         mySqlCmd.Connection = mySqlConn;
         mySqlCmd.Transaction = mySqlConn.BeginTransaction();
         mySqlCmd.CommandType = System.Data.CommandType.Text;
         PromotionsAmountFareQuery query = new PromotionsAmountFareQuery();
         if (id != 0)
         {
             query = Select(id);
             sqlSW += DeletePromoFare(query.id);
             sqlSW += _promAmountReduceDao.Delete(query.id);
             if (query.category_id != 0)
             {
                 sqlSW += _cateDao.Delete(query.category_id);
                 sqlSW += _prodCateSetDao.DelProdCateSet(query.category_id);
                 sqlSW += _usconDao.DeleteUserCon(query.condition_id);
             }
             if (!string.IsNullOrEmpty(query.event_id))
             {
                 sqlSW += _prodPromoDao.DelProdProm(query.event_id);
                 sqlSW += _promoAllDao.DeletePromAll(query.event_id);
             }
         }
         mySqlCmd.CommandText = sqlSW.ToString();
         i += mySqlCmd.ExecuteNonQuery();
         mySqlCmd.Transaction.Commit();
     }
     catch (Exception ex)
     {
         mySqlCmd.Transaction.Rollback();
         throw new Exception("PromotionsAmountFareDao-->Delete-->" + ex.Message + sqlSW.ToString(), ex);
     }
     finally
     {
         if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
         {
             mySqlConn.Close();
         }
     }
     return i;
 }
        public int Update(PromotionsAmountFareQuery model, string oldEventId)
        {
            int i = 0;
            MySqlCommand mySqlCmd = new MySqlCommand();
            MySqlConnection mySqlConn = new MySqlConnection(connStr);
            StringBuilder sbExSql = new StringBuilder();
            try
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConn.Open();
                }
                mySqlCmd.Connection = mySqlConn;
                mySqlCmd.Transaction = mySqlConn.BeginTransaction();
                mySqlCmd.CommandType = System.Data.CommandType.Text;
                StringBuilder sqlf = new StringBuilder();

                mySqlCmd.CommandText = _prodPromoDao.DeleteProdProm(model.event_id);
                sbExSql.Append(mySqlCmd.CommandText);
                mySqlCmd.ExecuteNonQuery();//刪除ProdPromo

                mySqlCmd.CommandText = _promoAllDao.DelPromAll(model.event_id);
                sbExSql.Append(_promoAllDao.DelPromAll(mySqlCmd.CommandText));
                mySqlCmd.ExecuteNonQuery();//刪除PromAll

                if (model.allClass == 0)
                {
                    //刪除全館商品
                    ProductCategorySet qgSet = new ProductCategorySet();
                    qgSet.Category_Id = model.category_id;
                    qgSet.Product_Id = 999999;//全館商品刪除 id=999999
                    //根據category_id刪除product_category_set表數據
                    mySqlCmd.CommandText = _prodCateSetDao.DelProdCateSetByCPID(qgSet);
                    sbExSql.Append(mySqlCmd.CommandText);
                    mySqlCmd.ExecuteNonQuery();//刪除全館別商品999999

                    if (model.brand_id != 0)//當品牌不為空時講該品牌下的所有商品加入set表
                    {
                        sqlf.Append(_prodCateSetDao.DeleteProdCateSet(model.category_id));

                        mySqlCmd.CommandText = sqlf.ToString();
                        sbExSql.Append(mySqlCmd.CommandText);
                        mySqlCmd.ExecuteNonQuery();
                        sqlf.Clear();

                        QueryVerifyCondition query = new QueryVerifyCondition();//根據條件從product表中獲取符合條件的商品并添加到set和prodprom表中
                        query.brand_id = Convert.ToUInt32(model.brand_id);//品牌
                        query.site_ids = model.site;
                        query.combination = 1;
                        PromotionsMaintainDao _promoMainDao = new PromotionsMaintainDao(connStr);
                        query.IsPage = false;
                        int totalCount = 0;
                        List<QueryandVerifyCustom> qvcList = _promoMainDao.GetProList(query, out totalCount);

                        List<uint> categorysetProduct = new List<uint>();
                        foreach (QueryandVerifyCustom qvcItem in qvcList)
                        {
                            if (categorysetProduct.Contains(qvcItem.product_id))
                            {
                                continue;
                            }
                            categorysetProduct.Add(qvcItem.product_id);
                            ProductCategorySet pcsModel = new ProductCategorySet();
                            pcsModel.Product_Id = qvcItem.product_id;
                            pcsModel.Brand_Id = Convert.ToUInt32(model.brand_id);
                            pcsModel.Category_Id = model.category_id;
                            //刪除已有的 新增異動的
                            sqlf.Append(_prodCateSetDao.SaveProdCategorySet(pcsModel));

                        }
                    }
                    if (!string.IsNullOrEmpty(sqlf.ToString()))
                    {
                        mySqlCmd.CommandText = sqlf.ToString();
                        sbExSql.Append(mySqlCmd.CommandText);
                        mySqlCmd.ExecuteNonQuery();
                        sqlf.Clear();
                    }

                }
                else//全館時
                {
                    sqlf.Clear();
                    sqlf.AppendFormat(_prodCateSetDao.DeleteProdCateSet(model.category_id));


                    ProductCategorySet pcs = new ProductCategorySet();
                    pcs.Category_Id = model.category_id;
                    pcs.Product_Id = 999999;
                    pcs.Brand_Id = 0;
                    sqlf.Append(_prodCateSetDao.SaveProdCategorySet(pcs));
                    mySqlCmd.CommandText = sqlf.ToString();
                    sbExSql.Append(_promoAllDao.DeletePromAll(mySqlCmd.CommandText));
                    mySqlCmd.ExecuteNonQuery();

                }
                sqlf.Clear();
                PromoAll pamodel = new PromoAll();
                pamodel.event_id = model.event_id;
                pamodel.event_type = model.event_type;
                pamodel.category_id = Convert.ToInt32(model.category_id);
                pamodel.startTime = model.start;
                pamodel.end = model.end;
                pamodel.status = model.status;
                pamodel.kuser = model.kuser;
                pamodel.kdate = model.created;
                pamodel.muser = model.muser;
                pamodel.mdate = model.modified;
                pamodel.product_id = model.product_id;
                pamodel.class_id = model.class_id;
                pamodel.brand_id = model.brand_id;
                sqlf.AppendFormat(_promoAllDao.SavePromAll(pamodel));
                ProductCategoryDao _categoryDao = new ProductCategoryDao(connStr);
                ProductCategory pcmodel = _categoryDao.GetModelById(Convert.ToUInt32(model.category_id));
                pcmodel.category_id = Convert.ToUInt32(model.category_id);
                pcmodel.category_name = model.name;
                pcmodel.banner_image = model.banner_image;
                pcmodel.category_link_url = model.category_link_url;
                pcmodel.category_father_id = model.category_father_id;
                pcmodel.category_updatedate = (uint)BLL.gigade.Common.CommonFunction.GetPHPTime(model.modified.ToString());
                pcmodel.category_display = Convert.ToUInt32(model.status);
                sqlf.AppendFormat(_cateDao.UpdateProdCate(pcmodel));
                PromotionsAmountReduce parModel = new PromotionsAmountReduce();
                parModel.id = model.id;
                parModel.name = model.name;
                parModel.delivery_store = model.delivery_store;
                parModel.group_id = model.group_id;
                parModel.type = model.type;
                parModel.amount = model.amount;
                parModel.quantity = model.quantity;
                parModel.start = model.start;
                parModel.end = model.end;
                parModel.updatetime = model.modified;
                parModel.created = model.created;
                parModel.active = model.active ? 1 : 0;
                parModel.status = model.status;
                sqlf.AppendFormat(_promAmountReduceDao.Update(parModel));
                mySqlCmd.CommandText = sqlf + UpdatePromoFare(model);
                i += mySqlCmd.ExecuteNonQuery();
                mySqlCmd.Transaction.Commit();
            }
            catch (Exception ex)
            {
                mySqlCmd.Transaction.Rollback();
                throw new Exception("PromotionsAmountFareDao-->Update-->sql:" + sbExSql.ToString() + ex.Message, ex);
            }
            finally
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
                {
                    mySqlConn.Close();
                }
            }
            return i;
        }
 /// <summary>
 /// 頁面的第一次保存,向product_category和promotionsAmountFare中新增基本數據并分別獲取category_id和id
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public int Save(PromotionsAmountFareQuery model)
 {
     model.Replace4MySQL();
     int id = 0;
     MySqlCommand mySqlCmd = new MySqlCommand();
     MySqlConnection mySqlConn = new MySqlConnection(connStr);
     try
     {
         if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
         {
             mySqlConn.Open();
         }
         mySqlCmd.Connection = mySqlConn;
         mySqlCmd.Transaction = mySqlConn.BeginTransaction();
         mySqlCmd.CommandType = System.Data.CommandType.Text;
         //#region 保存第一步到product_category 獲取prodduct_amount_fare的category_id
         ProductCategory pmodel = new ProductCategory();
         pmodel.category_name = model.name;
         pmodel.category_createdate = (uint)BLL.gigade.Common.CommonFunction.GetPHPTime();
         pmodel.category_father_id = model.category_father_id;
         pmodel.category_ipfrom = model.category_ipfrom;
         pmodel.category_display = Convert.ToUInt32(model.status);
         mySqlCmd.CommandText = _cateDao.SaveCategory(pmodel);
         model.category_id = Convert.ToUInt32(mySqlCmd.ExecuteScalar());
         //修改表serial
         Serial serial = new Serial();
         serial.Serial_id = 12;
         serial.Serial_Value = Convert.ToUInt32(model.category_id);
         mySqlCmd.CommandText = _serialDao.UpdateAutoIncreament(serial);
         id = Convert.ToInt32(mySqlCmd.ExecuteScalar());
         //#endregion
         PromotionsAmountFare pfmodel = new PromotionsAmountFare();
         pfmodel.name = model.name;
         pfmodel.event_desc = model.event_desc;
         pfmodel.vendor_coverage = model.vendor_coverage;
         pfmodel.event_type = model.event_type;
         pfmodel.kuser = model.kuser;
         pfmodel.created = model.created;
         pfmodel.active = model.active;
         pfmodel.category_id = model.category_id;
         pfmodel.status = model.status;
         pfmodel.payment_code = model.payment_code;
         mySqlCmd.CommandText = SavePromoFare(pfmodel);
         id = Convert.ToInt32(mySqlCmd.ExecuteScalar());
         mySqlCmd.Transaction.Commit();
     }
     catch (Exception ex)
     {
         mySqlCmd.Transaction.Rollback();
         throw new Exception("PromotionsAmountFareDao-->Save-->" + ex.Message, ex);
     }
     finally
     {
         if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
         {
             mySqlConn.Close();
         }
     }
     return id;
 }
        public int UpdateActive(PromotionsAmountFareQuery model)
        {
            try
            {
                return _promoFareDao.UpdateActive(model);
            }
            catch (Exception ex)
            {
                throw new Exception("PromotionsAmountFareMgr-->UpdateActive-->" + ex.Message, ex);
            }

        }
        public int Update(PromotionsAmountFareQuery model, string oldEventId)
        {
            try
            {
                return _promoFareDao.Update(model, oldEventId);
            }
            catch (Exception ex)
            {
                throw new Exception("PromotionsAmountFareMgr-->Update-->" + ex.Message, ex);
            }

        }
        public HttpResponseBase GetPromoAmountFareList()
        {

            List<PromotionsAmountFareQuery> store = new List<PromotionsAmountFareQuery>();
            string json = string.Empty;
            try
            {
                PromotionsAmountFareQuery query = new PromotionsAmountFareQuery();
                query.Start = Convert.ToInt32(Request.Params["start"] ?? "0");

                if (!string.IsNullOrEmpty(Request.Params["limit"]))
                {
                    query.Limit = Convert.ToInt32(Request.Params["limit"]);
                }
                else
                {
                    query.Limit = 25;
                }

                if (!string.IsNullOrEmpty(Request.Params["expiredSel"]))
                {
                    query.expired = Convert.ToInt32(Request.Params["expiredSel"]);
                }
                _promoAmountFareMgr = new PromotionsAmountFareMgr(mySqlConnectionString);
                _parasrcMgr = new ParameterMgr(mySqlConnectionString);
                int totalCount = 0;//獲取所有數據的行數
                store = _promoAmountFareMgr.Query(query, out totalCount);
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
                //这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式     
                timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

                foreach (var item in store)
                {
                    if (item.banner_image != "")
                    {
                        item.banner_image = imgServerPath + promoPath + item.banner_image;
                    }
                    else
                    {
                        item.banner_image = defaultImg;
                    }

                }
                json = "{success:true,totalCount:" + totalCount + ",data:" + JsonConvert.SerializeObject(store, Formatting.Indented, timeConverter) + "}";//返回json數據
            }
            catch (Exception ex)
            {
                Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
                logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
                logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                log.Error(logMessage);
                json = "{success:false,totalCount:0,data:[]}";
            }
            this.Response.Clear();
            this.Response.Write(json);
            this.Response.End();
            return this.Response;
        }
        public HttpResponseBase SecondSaveFare()
        {
            string jsonStr = String.Empty;
            int stringTranInt = 0;//使用tryParse使string轉換為int時保存轉換的值
            try
            {
                string rowID = Request.Params["rowid"].ToString() ?? "0";
                string isEdit = Request.Params["isEdit"].ToString() ?? "";
                _promoAmountFareMgr = new PromotionsAmountFareMgr(mySqlConnectionString);
                PromotionsAmountFareQuery model = new PromotionsAmountFareQuery();

                PromotionsAmountFareQuery OldModel = _promoAmountFareMgr.Select(Convert.ToInt32(rowID));

                #region 獲取數據
                if (!string.IsNullOrEmpty(Request.Params["rowid"]))
                {
                    model.id = Convert.ToInt32(Request.Params["rowid"]);
                }
                else
                {
                    model.id = 0;
                }
                model.category_id = OldModel.category_id;
                if (!string.IsNullOrEmpty(Request.Params["name"]))
                {
                    model.name = Request.Params["name"].ToString();
                }
                else
                {
                    model.name = OldModel.name;
                }
                if (!string.IsNullOrEmpty(Request.Params["desc"]))
                {
                    model.event_desc = Request.Params["desc"].ToString();
                }

                else
                {
                    model.event_desc = OldModel.event_desc;
                }
                if (!string.IsNullOrEmpty(Request.Params["vendor_coverage"]))
                {
                    model.vendor_coverage = Convert.ToInt32(Request.Params["vendor_coverage"].ToString());
                }
                else
                {
                    model.vendor_coverage = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["sclass_id"]))
                {
                    if (int.TryParse(Request.Params["sclass_id"].ToString(), out stringTranInt))
                    {
                        model.class_id = Convert.ToInt32(Request.Params["sclass_id"].ToString() == "" ? "0" : Request.Params["sclass_id"].ToString());
                    }
                    else
                    {
                        model.class_id = OldModel.class_id;
                    }
                }
                else
                {
                    model.class_id = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["sbrand_id"]))
                {
                    if (int.TryParse(Request.Params["sbrand_id"].ToString(), out stringTranInt))
                    {
                        model.brand_id = Convert.ToInt32(Request.Params["sbrand_id"].ToString() == "" ? "0" : Request.Params["sbrand_id"].ToString());

                    }
                    else
                    {
                        model.brand_id = OldModel.brand_id;
                    }
                }
                else
                {
                    model.brand_id = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["allClass"]))
                {
                    model.allClass = Convert.ToInt32(Request.Params["allClass"].ToString() == "1" ? "1" : "0");
                    if (1 == model.allClass)
                    {
                        model.product_id = 999999;
                    }

                }
                else
                {
                    model.allClass = 0;
                }

                if (!string.IsNullOrEmpty(Request.Params["event_type"]))
                {
                    //獲取event_type和category_father_id
                    _parasrcMgr = new ParameterMgr(mySqlConnectionString);
                    List<Parametersrc> fatherIdResult = _parasrcMgr.QueryUsed(new Parametersrc { ParameterType = "event_type", parameterName = Request.Params["event_type"].ToString(), Used = 1 });
                    if (fatherIdResult.Count == 1)
                    {
                        model.event_type = fatherIdResult[0].ParameterCode;
                        model.category_father_id = Convert.ToUInt32(fatherIdResult[0].ParameterProperty);
                    }
                }

                if (!string.IsNullOrEmpty(Request.Params["amount"]))
                {
                    model.amount = Convert.ToInt32(Request.Params["amount"].ToString());
                }
                else
                {
                    model.amount = OldModel.amount;
                }
                if (!string.IsNullOrEmpty(Request.Params["quantity"]))
                {
                    model.quantity = Convert.ToInt32(Request.Params["quantity"].ToString());
                }
                else
                {
                    model.quantity = OldModel.quantity;
                }
                if (!string.IsNullOrEmpty(Request.Params["fare_percent"]))
                {
                    model.fare_percent = Convert.ToInt32(Request.Params["fare_percent"].ToString());
                }
                else
                {
                    model.fare_percent = OldModel.fare_percent;
                }
                if (!string.IsNullOrEmpty(Request.Params["off_times"]))
                {
                    model.off_times = Convert.ToInt32(Request.Params["off_times"].ToString());
                }
                else
                {
                    model.off_times = OldModel.off_times;
                }
                if (model.id != 0)
                {
                    model.event_id = BLL.gigade.Common.CommonFunction.GetEventId(model.event_type, model.id.ToString());
                }

                if (Request.Params["group_id"].ToString() != "")
                {//會員群組不為空時,要清空已存在的會員條件
                    if (!string.IsNullOrEmpty(Request.Params["group_id"].ToString()) && int.TryParse(Request.Params["group_id"].ToString(), out stringTranInt))//group_id
                    {
                        model.group_id = Convert.ToInt32(Request.Params["group_id"].ToString());
                    }
                    else
                    {
                        model.group_id = OldModel.group_id;
                    }
                    if (Request.Params["condition_id"].ToString() != "" && Request.Params["condition_id"].ToString() != "0")
                    {
                        UserCondition uc = new UserCondition();
                        uc.condition_id = Convert.ToInt32(Request.Params["condition_id"]);
                        _ucMgr = new UserConditionMgr(mySqlConnectionString);
                        if (_ucMgr.Delete(uc) > 0)
                        {
                            jsonStr = "{success:true}";
                            model.condition_id = 0;
                        }
                        else
                        {
                            jsonStr = "{success:false,msg:3}";
                            this.Response.Clear();
                            this.Response.Write(jsonStr.ToString());
                            this.Response.End();
                            return this.Response;
                        }
                    }

                }
                else if (Request.Params["condition_id"].ToString() != "" && Request.Params["condition_id"].ToString() != "0")
                {
                    try//condition_id
                    {
                        model.condition_id = Convert.ToInt32(Request.Params["condition_id"].ToString());
                    }
                    catch (Exception)
                    {
                        model.condition_id = OldModel.condition_id;
                    }
                    model.group_id = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["type"]) && int.TryParse(Request.Params["type"].ToString(), out stringTranInt))
                {
                    model.type = Convert.ToInt32(Request.Params["type"].ToString());
                }
                else
                {
                    model.type = OldModel.type;
                }
                if (!string.IsNullOrEmpty(Request.Params["deliver"].ToString()) && int.TryParse(Request.Params["deliver"].ToString(), out stringTranInt))
                {
                    model.delivery_store = Convert.ToInt32(Request.Params["deliver"].ToString());
                }
                else
                {
                    model.delivery_store = OldModel.delivery_store;
                }
                if (!string.IsNullOrEmpty(Request.Params["devicename"].ToString()))
                {
                    model.device = Convert.ToInt32(Request.Params["devicename"].ToString());
                }
                else
                {
                    model.device = OldModel.device;
                }
                if (!string.IsNullOrEmpty(Request.Params["payment"].ToString()))
                {
                    Regex reg = new Regex("^([0-9]+,)*[0-9]+$");
                    if (reg.IsMatch(Request.Params["payment"].ToString()))
                    {
                        model.payment_code = Request.Params["payment"].ToString();
                    }
                    else
                    {
                        model.payment_code = OldModel.payment_code;
                    }
                }
                if (!string.IsNullOrEmpty(Request.Params["start_time"].ToString()))
                {
                    model.start = Convert.ToDateTime(Request.Params["start_time"].ToString());
                }
                else
                {
                    model.start = OldModel.start_time;
                }
                if (!string.IsNullOrEmpty(Request.Params["end_time"].ToString()))
                {
                    model.end = Convert.ToDateTime(Request.Params["end_time"].ToString());
                }
                else
                {
                    model.end = OldModel.end_time;
                }
                if (!string.IsNullOrEmpty(Request.Params["site"].ToString()))
                {
                    Regex reg = new Regex("^([0-9]+,)*[0-9]+$");
                    if (reg.IsMatch(Request.Params["site"].ToString()))
                    {
                        model.site = Request.Params["site"].ToString();
                    }
                    else
                    {
                        model.site = OldModel.site;
                    }
                }

                model.status = 1;
                if (!string.IsNullOrEmpty(Request.Params["url_by"].ToString()))
                {
                    model.url_by = Convert.ToInt32(Request.Params["url_by"].ToString());
                }
                else
                {
                    model.url_by = OldModel.url_by;
                }

                #endregion
                ////講圖片和鏈接保存至product_category中

                if (model.url_by == 1)
                {
                    #region 上傳圖片
                    try
                    {
                        string path = Server.MapPath(xmlPath);
                        SiteConfigMgr _siteConfigMgr = new SiteConfigMgr(path);
                        SiteConfig extention_config = _siteConfigMgr.GetConfigByName("PIC_Extention_Format");
                        SiteConfig minValue_config = _siteConfigMgr.GetConfigByName("PIC_Length_MinValue");
                        SiteConfig maxValue_config = _siteConfigMgr.GetConfigByName("PIC_Length_MaxValue");
                        SiteConfig admin_userName = _siteConfigMgr.GetConfigByName("ADMIN_USERNAME");
                        SiteConfig admin_passwd = _siteConfigMgr.GetConfigByName("ADMIN_PASSWD");

                        //擴展名、最小值、最大值
                        string extention = extention_config.Value == "" ? extention_config.DefaultValue : extention_config.Value;
                        string minValue = minValue_config.Value == "" ? minValue_config.DefaultValue : minValue_config.Value;
                        string maxValue = maxValue_config.Value == "" ? maxValue_config.DefaultValue : maxValue_config.Value;

                        string localPromoPath = imgLocalPath + promoPath;//圖片存儲地址

                        Random rand = new Random();
                        int newRand = rand.Next(1000, 9999);//獲取隨機數重命名圖片


                        if (Request.Files.Count > 0)
                        {

                            HttpPostedFileBase file = Request.Files[0];
                            string fileName = string.Empty;//當前文件名

                            string fileExtention = string.Empty;//當前文件的擴展名

                            fileName = Path.GetFileName(file.FileName);
                            if (fileName != "")
                            {
                                // string returnName = imgServerPath;
                                bool result = false;
                                string NewFileName = string.Empty;

                                fileExtention = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
                                NewFileName = model.event_id + newRand + fileExtention;

                                string ServerPath = string.Empty;
                                //判斷目錄是否存在,不存在則創建
                                CreateFolder(localPromoPath.Substring(0, localPromoPath.Length - promoPath.Length + 1), promoPath.Substring(1, promoPath.Length - 2).Split('/'));
                                fileName = NewFileName;
                                NewFileName = localPromoPath + NewFileName;//絕對路徑
                                ServerPath = Server.MapPath(imgLocalServerPath + promoPath);
                                string ErrorMsg = string.Empty;
                                //上傳之前刪除已有的圖片
                                string oldFileName = OldModel.banner_image;
                                FTP ftp = new FTP(localPromoPath, ftpuser, ftppwd);
                                List<string> tem = ftp.GetFileList();
                                if (tem.Contains(oldFileName))
                                {
                                    FTP ftps = new FTP(localPromoPath + oldFileName, ftpuser, ftppwd);
                                    ftps.DeleteFile(localPromoPath + oldFileName);//刪除ftp:71.159上的舊圖片
                                    DeletePicFile(ServerPath + oldFileName);//刪除本地圖片
                                }
                                FileManagement fileLoad = new FileManagement();
                                //上傳
                                result = fileLoad.UpLoadFile(file, ServerPath, NewFileName, extention, int.Parse(maxValue), int.Parse(minValue), ref ErrorMsg, ftpuser, ftppwd);
                                if (result)//上傳成功
                                {
                                    model.banner_image = fileName;
                                }

                            }
                            else
                            {
                                model.banner_image = OldModel.banner_image;
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
                        logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name + "->圖片上傳失敗!", ex.Source, ex.Message);
                        logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                        log.Error(logMessage);
                        jsonStr = "{success:false,msg:0}";
                        model.banner_image = OldModel.banner_image;
                    }

                    #endregion
                    if (!string.IsNullOrEmpty(Request.Params["banner_url"].ToString()))
                    {
                        model.category_link_url = Request.Params["banner_url"].ToString();
                    }
                    else
                    {
                        model.category_link_url = OldModel.category_link_url;
                    }

                }
                else//url_by=0
                {
                    //刪除上傳的圖片
                    string oldFileName = OldModel.banner_image;
                    FTP ftp = new FTP(imgLocalPath + promoPath, ftpuser, ftppwd);
                    List<string> tem = ftp.GetFileList();
                    if (tem.Contains(oldFileName))
                    {
                        FTP ftps = new FTP(imgLocalPath + promoPath + oldFileName, ftpuser, ftppwd);
                        ftps.DeleteFile(imgLocalPath + promoPath + oldFileName);//刪除ftp:71.159上的舊圖片
                        DeletePicFile(Server.MapPath(imgLocalServerPath + promoPath) + oldFileName);//刪除本地圖片
                    }
                    model.category_link_url = "";
                    model.banner_image = "";
                }

                _promoAmountFareMgr = new PromotionsAmountFareMgr(mySqlConnectionString);
                if (string.IsNullOrEmpty(isEdit))
                {
                    model.kuser = (System.Web.HttpContext.Current.Session["caller"] as Caller).user_id.ToString();
                    model.created = DateTime.Now;
                    model.muser = model.kuser;
                    model.modified = model.created;
                    if (_promoAmountFareMgr.ReSave(model) > 0)
                    {
                        jsonStr = "{success:true,msg:0}";//返回json數據
                    }
                    else
                    {
                        jsonStr = "{success:false,msg:0}";//返回json數據
                    }
                }
                else
                {
                    model.kuser = OldModel.kuser;
                    model.created = OldModel.created;
                    model.muser = (System.Web.HttpContext.Current.Session["caller"] as Caller).user_id.ToString();
                    model.modified = DateTime.Now;
                    if (_promoAmountFareMgr.Update(model, OldModel.event_id) > 0)
                    {
                        jsonStr = "{success:true,msg:0}";//返回json數據
                    }
                    else
                    {
                        jsonStr = "{success:false,msg:0}";//返回json數據
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
                logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
                logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                log.Error(logMessage);
                jsonStr = "{success:false,msg:0}";
            }
            this.Response.Clear();
            this.Response.Write(jsonStr.ToString());
            this.Response.End();
            return this.Response;
        }
        public HttpResponseBase FirstSaveFare()
        {
            string jsonStr = String.Empty;
            try
            {
                PromotionsAmountFareQuery model = new PromotionsAmountFareQuery();
                if (!string.IsNullOrEmpty(Request.Params["name"].ToString()))
                {
                    model.name = Request.Params["name"].ToString();
                }
                else
                {
                    model.name = string.Empty;
                }
                if (!string.IsNullOrEmpty(Request.Params["desc"].ToString()))
                {
                    model.event_desc = Request.Params["desc"].ToString();
                }
                else
                {
                    model.event_desc = string.Empty;
                }
                if (!string.IsNullOrEmpty(Request.Params["vendor_coverage"]))
                {
                    model.vendor_coverage = Convert.ToInt32(Request.Params["vendor_coverage"].ToString());
                }
                else
                {
                    model.vendor_coverage = 0;
                }

                if (!string.IsNullOrEmpty(Request.Params["amount"].ToString()))
                {
                    model.amount = Convert.ToInt32(Request.Params["amount"].ToString());
                }
                else
                {
                    model.amount = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["quantity"].ToString()))
                {
                    model.quantity = Convert.ToInt32(Request.Params["quantity"].ToString());
                }
                else
                {
                    model.quantity = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["fare_percent"].ToString()))
                {
                    model.fare_percent = Convert.ToInt32(Request.Params["fare_percent"].ToString());
                }
                else
                {
                    model.fare_percent = 0;
                }
                if (!string.IsNullOrEmpty(Request.Params["off_times"].ToString()))
                {
                    model.off_times = Convert.ToInt32(Request.Params["off_times"].ToString());
                }
                else
                {
                    model.off_times = 0;
                }




                model.kuser = (System.Web.HttpContext.Current.Session["caller"] as Caller).user_id.ToString();
                model.created = DateTime.Now;
                model.status = 0;

                //獲取event_type和category_father_id
                _parasrcMgr = new ParameterMgr(mySqlConnectionString);
                List<Parametersrc> fatherIdResult = _parasrcMgr.QueryUsed(new Parametersrc { ParameterType = "event_type", parameterName = Request.Params["event_type"].ToString(), Used = 1 });
                if (fatherIdResult.Count == 1)
                {
                    model.event_type = fatherIdResult[0].ParameterCode;
                    model.category_father_id = Convert.ToUInt32(fatherIdResult[0].ParameterProperty);
                }

                model.category_ipfrom = Request.UserHostAddress;//獲取當前ip

                _promoAmountFareMgr = new PromotionsAmountFareMgr(mySqlConnectionString);
                PromotionsAmountFare query = new PromotionsAmountFare();
                query.id = _promoAmountFareMgr.Save(model);
                System.Data.DataTable dt = _promoAmountFareMgr.Select(query);

                if (dt.Rows.Count > 0)
                {
                    jsonStr = "{success:true,\"id\":\"" + dt.Rows[0]["id"] + "\",\"cateID\":\"" + dt.Rows[0]["category_id"] + "\",\"event_type\":\"" + dt.Rows[0]["event_type"] + "\"}";
                }
                else
                {
                    jsonStr = "{success:false }";
                }
            }
            catch (Exception ex)
            {
                Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
                logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
                logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                log.Error(logMessage);
                jsonStr = "{success:false}";
            }

            this.Response.Clear();
            this.Response.Write(jsonStr.ToString());
            this.Response.End();
            return this.Response;
        }