public string ComboPriceSave()
        {
            string json = "{success:true}";
            if (!PriceMaster.CheckProdName(Request.Form["product_name"]))
            {
                return "{success:false,msg:'" + Resources.Product.FORBIDDEN_CHARACTER + "'}";
            }
            ProductTemp pTemp = new ProductTemp();
            List<PriceMasterTemp> pMasterListT = new List<PriceMasterTemp>();
            List<PriceMaster> pMasterList = new List<PriceMaster>();

            List<List<ItemPrice>> ItemPList = new List<List<ItemPrice>>();
            PriceMasterTemp pMasterTemp = new PriceMasterTemp();


            if (!string.IsNullOrEmpty(Request.Form["OldProductId"]))
            {
                pTemp.Product_Id = Request.Form["OldProductId"];
                pMasterTemp.product_id = Request.Form["OldProductId"];
            }
            string paramValue = Request.Params["paramValue"];
            #region 參數
            int writer_id = (Session["caller"] as Caller).user_id;
            string product_name = PriceMaster.Product_Name_FM(Request.Params["product_name"]);
            string price_type = Request.Params["price_type"];
            string product_price_list = Request.Params["product_price_list"];
            string default_bonus_percent = Request.Params["default_bonus_percent"];
            string price = Request.Params["price"];
            string cost = Request.Params["cost"];
            string max_price = Request.Params["max_price"];
            string bonus_percent = Request.Params["bonus_percent"];
            string event_price = Request.Params["event_price"];
            string event_cost = Request.Params["event_cost"];
            string max_event_price = Request.Params["max_event_price"];
            string event_start = Request.Params["event_start"];
            string event_end = Request.Params["event_end"];
            string site_id = Request.Params["site_id"];
            string user_level = Request.Params["user_level"];
            string user_mail = Request.Params["user_mail"];
            string bag_check_money = Request.Params["bag_check_money"] == "" ? "0" : Request.Params["bag_check_money"];
            string accumulated_bonus = Request.Params["accumulated_bonus"];
            string bonus_percent_start = Request.Params["bonus_percent_start"];
            string bonus_percent_end = Request.Params["bonus_percent_end"];
            string same_price = Request.Params["same_price"];
            string show_listprice = Request.Params["show_listprice"];
            string valid_start = Request.Params["valid_start"];
            string valid_end = Request.Params["valid_end"];

            #endregion
            List<MakePriceCustom> PriceStore = new List<MakePriceCustom>();
            if (price_type == "2")//各自定價
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string priceStr = Request.Params["priceStr"];
                PriceStore = jss.Deserialize<List<MakePriceCustom>>(priceStr);
            }

            if (!string.IsNullOrEmpty(Request.Params["product_id"]))
            {
                #region 正式表操作
                List<PriceMaster> pMList = new List<PriceMaster>();

                //插入price_master
                _priceMasterMgr = new PriceMasterMgr(connectionString);
                _priceMasterTsMgr = new PriceMasterTsMgr(connectionString);
                PriceMaster pMaster = new PriceMaster();

                //查詢price_master
                if (!string.IsNullOrEmpty(Request.Params["price_master_id"]))
                {
                    pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = uint.Parse(Request.Params["price_master_id"]) }).FirstOrDefault();
                }

                pMaster.product_id = uint.Parse(Request.Params["product_id"]);
                pMaster.child_id = int.Parse(Request.Params["product_id"]);
                pMaster.site_id = uint.Parse(site_id);


                uint userId = 0;
                if (!string.IsNullOrEmpty(Request.Form["user_mail"]))
                {
                    _usersMgr = new UsersMgr(connectionString);
                    System.Data.DataTable dt_User = _usersMgr.Query(Request.Form["user_mail"]);
                    if (dt_User != null && dt_User.Rows.Count > 0)
                    {
                        userId = Convert.ToUInt32(dt_User.Rows[0]["user_id"]);
                    }
                }
                if (userId != 0)
                {
                    pMaster.user_id = userId;
                }
                if (user_level != "")
                {
                    pMaster.user_level = uint.Parse(user_level);
                }
                pMaster.product_name = product_name;
                pMaster.bonus_percent = float.Parse(bonus_percent);
                pMaster.cost = int.Parse(cost);
                pMaster.price = int.Parse(price);
                pMaster.max_price = int.Parse(max_price);
                pMaster.max_event_price = int.Parse(max_event_price);
                pMaster.default_bonus_percent = float.Parse(default_bonus_percent);
                pMaster.event_price = int.Parse(event_price);
                pMaster.event_cost = int.Parse(event_cost);
                pMaster.same_price = int.Parse(same_price);
                pMaster.price_status = 2;//申請審核
                pMaster.accumulated_bonus = uint.Parse(accumulated_bonus);

                #region 時間 活動時間
                if (event_start != "")
                {
                    pMaster.event_start = Convert.ToUInt32(CommonFunction.GetPHPTime(event_start));
                }
                if (event_end != "")
                {
                    pMaster.event_end = Convert.ToUInt32(CommonFunction.GetPHPTime(event_end));
                }
                if (bonus_percent_start != "")
                {
                    pMaster.bonus_percent_start = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_percent_start));
                }
                if (bonus_percent_end != "")
                {
                    pMaster.bonus_percent_end = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_percent_end));
                }
                if (!string.IsNullOrEmpty(valid_start))
                {
                    pMaster.valid_start = Convert.ToInt32(CommonFunction.GetPHPTime(valid_start));
                }
                if (!string.IsNullOrEmpty(valid_end))
                {
                    pMaster.valid_end = Convert.ToInt32(CommonFunction.GetPHPTime(valid_end));
                }


                #endregion

                _functionMgr = new FunctionMgr(connectionString);
                string function = Request.Params["function"] ?? "";
                Function fun = _functionMgr.QueryFunction(function, "/ProductCombo");
                int functionid = fun == null ? 0 : fun.RowId;
                HistoryBatch batch = new HistoryBatch { functionid = functionid };
                batch.batchno = Request.Params["batch"] ?? "";
                batch.kuser = (Session["caller"] as Caller).user_email;

                List<ItemPrice> update = new List<ItemPrice>();
                if (price_type == "2")  //各自定價
                {
                    CreateList(PriceStore, pMaster, null, same_price, ItemPList, pMasterListT, pMasterList, update);
                }
                pMasterList.Add(pMaster);

                try
                {
                    //價格修改 申請審核
                    PriceUpdateApply priceUpdateApply = new PriceUpdateApply();
                    priceUpdateApply.apply_user = Convert.ToUInt32((Session["caller"] as Caller).user_id);

                    //價格審核記錄
                    PriceUpdateApplyHistory applyHistroy = new PriceUpdateApplyHistory();
                    applyHistroy.user_id = Convert.ToInt32(priceUpdateApply.apply_user);
                    applyHistroy.price_status = 1;
                    //applyHistroy.type = 3;
                    applyHistroy.type = 1;//edit by wwei0216w 所作操作為 1:申請審核的操作 

                    _priceUpdateApplyMgr = new PriceUpdateApplyMgr(connectionString);
                    _priceUpdateApplyHistoryMgr = new PriceUpdateApplyHistoryMgr(connectionString);
                    _tableHistoryMgr = new TableHistoryMgr(connectionString);

                    ArrayList excuteSql = new ArrayList();
                    if (!string.IsNullOrEmpty(Request.Params["price_master_id"]))
                    {
                        #region 修改

                        priceUpdateApply.price_master_id = pMaster.price_master_id;
                        PriceMaster priceMster = _priceMasterMgr.QueryPMaster(new PriceMaster()
                        {
                            site_id = uint.Parse(site_id),
                            user_level = uint.Parse(user_level == "" ? "0" : user_level),
                            user_id = userId,
                            product_id = uint.Parse(Request.Params["product_id"]),
                            price_master_id = uint.Parse(Request.Params["price_master_id"])
                        });

                        //更新price_master
                        if (priceMster != null)
                        {
                            json = "{success:true,msg:'" + Resources.Product.SITE_EXIST + "'}";
                        }
                        else
                        {
                            int apply_id = _priceUpdateApplyMgr.Save(priceUpdateApply);
                            if (apply_id != -1)
                            {
                                bool flag = false;
                                foreach (var item in pMasterList)
                                {
                                    item.apply_id = (uint)apply_id;
                                    excuteSql = new ArrayList();
                                    if (item == pMaster)
                                    {
                                        pMaster.apply_id = Convert.ToUInt32(apply_id);
                                        applyHistroy.apply_id = apply_id;
                                        excuteSql.Add(_priceUpdateApplyHistoryMgr.SaveSql(applyHistroy));
                                    }
                                    //excuteSql.Add(_priceMasterMgr.Update(item));
                                    excuteSql.Add(_priceMasterTsMgr.UpdateTs(item));//edit by xiangwang0413w 2014/07/16 將數據更新到pirce_master_ts表
                                    flag = _tableHistoryMgr.SaveHistory<PriceMaster>(item, batch, excuteSql);
                                }
                                if (flag)
                                {
                                    //更新item_price
                                    //_itemPriceMgr = new ItemPriceMgr("");
                                    _itemPriceTsMgr = new ItemPriceTsMgr(connectionString);
                                    foreach (var iPrice in update)
                                    {
                                        iPrice.apply_id = (uint)apply_id;
                                        excuteSql = new ArrayList();
                                        //excuteSql.Add(_itemPriceMgr.Update(iPrice));
                                        excuteSql.Add(_itemPriceTsMgr.UpdateTs(iPrice));//edit by xiangwang0413w 2014/07/17 將數據更新到pirce_master_ts表
                                        if (!_tableHistoryMgr.SaveHistory<ItemPrice>(iPrice, batch, excuteSql))
                                        {
                                            json = "{success:true,msg:'" + Resources.Product.EDIT_FAIL + "'}";
                                        }
                                    }
                                    json = "{success:true,msg:'" + Resources.Product.EDIT_SUCCESS + "'}";
                                }
                                else
                                {
                                    json = "{success:true,msg:'" + Resources.Product.EDIT_FAIL + "'}";
                                }
                            }
                            else
                            {
                                json = "{success:true,msg:'" + Resources.Product.EDIT_FAIL + "'}";
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region 新增

                        string msg = string.Empty;

                        int status = 0;

                        List<ItemPrice> iprice = (ItemPList == null || ItemPList.Count == 0) ? null : ItemPList[pMasterList.IndexOf(pMaster)];
                        int priceMasterId = _priceMasterMgr.Save(pMaster, iprice, null, ref msg);
                        if (priceMasterId != -1)
                        {
                            priceUpdateApply.price_master_id = Convert.ToUInt32(priceMasterId);
                            int apply_id = _priceUpdateApplyMgr.Save(priceUpdateApply);

                            if (apply_id != -1)
                            {
                                pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                                pMaster.apply_id = Convert.ToUInt32(apply_id);
                                excuteSql.Add(_priceMasterMgr.Update(pMaster));
                                excuteSql.Add(_priceMasterTsMgr.UpdateTs(pMaster)); //edit by xiangwang0413w 2014/07/22 更新price_master_ts表後同時更新price_master_ts表,以便價格審核

                                foreach (var item in pMasterList.FindAll(m => m.product_id != m.child_id))
                                {
                                    iprice = (ItemPList == null || ItemPList.Count == 0) ? null : ItemPList[pMasterList.IndexOf(item)];
                                    priceMasterId = _priceMasterMgr.Save(item, iprice, null, ref msg);
                                    pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();

                                    if (priceMasterId != -1)
                                    {
                                        priceUpdateApply.price_master_id = Convert.ToUInt32(priceMasterId);
                                        pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                                        pMaster.apply_id = Convert.ToUInt32(apply_id);
                                        excuteSql.Add(_priceMasterMgr.Update(pMaster));
                                        excuteSql.Add(_priceMasterTsMgr.UpdateTs(pMaster)); //edit by xiangwang0413w 2014/07/22 更新price_master_ts表後同時更新price_master_ts表,以便價格審核
                                    }
                                    else { status = 2; }
                                }
                            }
                            else { status = 3; }
                        }
                        else { status = 3; }

                        excuteSql.Add(_priceUpdateApplyHistoryMgr.SaveSql(applyHistroy));
                        _tableHistoryMgr = new TableHistoryMgr(connectionString);
                        if (_tableHistoryMgr.SaveHistory<PriceMaster>(pMaster, batch, excuteSql))
                        {
                            status = 1;
                        }
                        else { status = 2; }

                        //foreach (var item in pMasterList)
                        //{
                        //    List<ItemPrice> iprice = (ItemPList == null || ItemPList.Count == 0) ? null : ItemPList[pMasterList.IndexOf(item)];
                        //    int priceMasterId = _priceMasterMgr.Save(item, iprice, null, ref msg);
                        //    if (apply_id != -1)
                        //    {
                        //        pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                        //    }

                        //    if (priceMasterId != -1)
                        //    {
                        //        if (item != pMaster) { status = 1; continue; }
                        //        priceUpdateApply.price_master_id = Convert.ToUInt32(priceMasterId);
                        //        int apply_id = _priceUpdateApplyMgr.Save(priceUpdateApply);
                        //        if (apply_id != -1)
                        //        {
                        //            pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                        //            pMaster.apply_id = Convert.ToUInt32(apply_id);
                        //            applyHistroy.apply_id = apply_id;

                        //            excuteSql.Add(_priceMasterMgr.Update(pMaster));
                        //            excuteSql.Add(_priceMasterTsMgr.UpdateTs(pMaster)); //edit by xiangwang0413w 2014/07/22 更新price_master_ts表後同時更新price_master_ts表,以便價格審核
                        //            excuteSql.Add(_priceUpdateApplyHistoryMgr.SaveSql(applyHistroy));
                        //            _tableHistoryMgr = new TableHistoryMgr(connectionString);
                        //            if (_tableHistoryMgr.SaveHistory<PriceMaster>(pMaster, batch, excuteSql))
                        //            {
                        //                status = 1;
                        //            }
                        //            else { status = 2; }
                        //        }
                        //        else { status = 2; }
                        //    }
                        //    else { status = 3; }
                        //}

                        if (status == 1)
                        {
                            json = "{success:true,msg:'" + Resources.Product.ADD_SUCCESS + "'}";
                        }
                        else if (status == 2)
                        {
                            json = "{success:false,msg:'" + Resources.Product.SAVE_FAIL + "'}";
                        }
                        else
                        {
                            json = "{success:false,msg:'" + msg + "'}";
                        }

                        #endregion
                    }
                }
                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,msg:'" + Resources.Product.SAVE_FAIL + "'}";
                }
                #endregion
            }
            else
            {
                #region 新增至臨時表
                try
                {
                    _productTempMgr = new ProductTempMgr(connectionString);
                    _pMasterTempMgr = new PriceMasterTempMgr(connectionString);

                    //product_temp
                    pTemp.Product_Price_List = uint.Parse(product_price_list);
                    pTemp.Writer_Id = writer_id;
                    pTemp.Combo_Type = COMBO_TYPE;
                    pTemp.Price_type = int.Parse(price_type);
                    pTemp.Bag_Check_Money = uint.Parse(bag_check_money);
                    pTemp.show_listprice = uint.Parse(show_listprice);
                    pTemp.Bonus_Percent = float.Parse(bonus_percent);
                    pTemp.Default_Bonus_Percent = float.Parse(default_bonus_percent);

                    //Price_Master
                    pMasterTemp.product_name = product_name; ;
                    pMasterTemp.default_bonus_percent = float.Parse(default_bonus_percent);
                    pMasterTemp.writer_Id = writer_id;
                    pMasterTemp.combo_type = COMBO_TYPE;
                    //默認站臺1:吉甲地,(按統一價格比例拆分)會員等級1:普通會員
                    pMasterTemp.site_id = 1;
                    pMasterTemp.user_level = 1;
                    pMasterTemp.same_price = int.Parse(same_price);
                    pMasterTemp.accumulated_bonus = uint.Parse(accumulated_bonus);
                    pMasterTemp.bonus_percent = float.Parse(bonus_percent);
                    pMasterTemp.price = int.Parse(price);
                    pMasterTemp.cost = int.Parse(cost);
                    pMasterTemp.max_price = int.Parse(max_price);
                    pMasterTemp.max_event_price = int.Parse(max_event_price);
                    pMasterTemp.event_price = int.Parse(event_price);
                    pMasterTemp.event_cost = int.Parse(event_cost);
                    #region 時間 活動時間
                    if (event_start != "")
                    {
                        pMasterTemp.event_start = Convert.ToUInt32(CommonFunction.GetPHPTime(event_start));
                    }
                    if (event_end != "")
                    {
                        pMasterTemp.event_end = Convert.ToUInt32(CommonFunction.GetPHPTime(event_end));
                    }
                    if (bonus_percent_start != "")
                    {
                        pMasterTemp.bonus_percent_start = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_percent_start));
                        pTemp.Bonus_Percent_Start = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_percent_start));
                    }
                    if (bonus_percent_end != "")
                    {
                        pMasterTemp.bonus_percent_end = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_percent_end));
                        pTemp.Bonus_Percent_End = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_percent_end));
                    }
                    if (!string.IsNullOrEmpty(valid_start))
                    {
                        pMasterTemp.valid_start = Convert.ToInt32(CommonFunction.GetPHPTime(valid_start));
                    }
                    if (!string.IsNullOrEmpty(valid_end))
                    {
                        pMasterTemp.valid_end = Convert.ToInt32(CommonFunction.GetPHPTime(valid_end));
                    }

                    #endregion

                    pMasterTemp.price_status = 1;

                    _productItemMgr = new ProductItemMgr(connectionString);

                    string oldProductId = "0";
                    if (!string.IsNullOrEmpty(Request.Form["OldProductId"]))
                    {
                        oldProductId = Request.Form["OldProductId"];
                    }

                    List<ItemPrice> update = new List<ItemPrice>();

                    if (price_type == "2")
                    {
                        _combTempMgr = new ProductComboTempMgr(connectionString);
                        List<ProductComboCustom> combResultList = _combTempMgr.priceComboQuery(new ProductComboCustom { Writer_Id = writer_id, Parent_Id = int.Parse(oldProductId.ToString()) });
                        bool match = true;
                        if (combResultList.Count() > 0)
                        {
                            int countBySearchPile = combResultList.GroupBy(m => m.Pile_Id).Count();      //庫中原有價格數據
                            int countByStorePile = PriceStore.GroupBy(m => m.Pile_Id).Count();           //頁面store數據
                            //判斷群組數量是否相同
                            if (countBySearchPile == countByStorePile)
                            {
                                for (int i = 1; i <= countBySearchPile; i++)
                                {
                                    //組合類型為固定或任選時pile_id為0;
                                    var tempSearch = combResultList.Where(m => m.Pile_Id == (combResultList[0].Pile_Id == 0 ? 0 : i)).ToList().GroupBy(m => m.Child_Id).ToList();
                                    var tempPrice = PriceStore.Where(m => m.Pile_Id == (combResultList[0].Pile_Id == 0 ? 0 : i)).ToList().GroupBy(m => m.Child_Id).ToList();
                                    //判斷當前組中子商品的數量是否相同
                                    if (tempSearch.Count() == tempPrice.Count())
                                    {
                                        foreach (var item in tempPrice)
                                        {
                                            if (tempSearch.Where(m => m.Key == item.Key.ToString()).ToList().Count() <= 0)//edit 2014/09/24
                                            {
                                                match = false;
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        match = false;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                match = false;
                            }
                        }
                        else
                        {
                            match = false;
                        }

                        if (!match)
                        {
                            _combTempMgr = new ProductComboTempMgr(connectionString);

                            _combTempMgr.comboPriceDelete(new ProductComboTemp { Writer_Id = writer_id, Combo_Type = COMBO_TYPE, Parent_Id = oldProductId });

                            PriceStore.ForEach(rec => rec.price_master_id = 0);

                        }

                        CreateList(PriceStore, null, pMasterTemp, same_price, ItemPList, pMasterListT, pMasterList, update);
                    }

                    pMasterListT.Add(pMasterTemp);

                    //如果原價格為複製價格,則需刪除原複製價格並將child_id設為oldProductId
                    if (oldProductId != "0")
                    {
                        pMasterListT.ForEach(m =>
                        {
                            if (m.child_id == "0")
                            {
                                m.child_id = oldProductId;
                            }
                        });
                    }

                    //查詢                 

                    PriceMasterProductCustom queryReust = _pMasterTempMgr.Query(new PriceMasterTemp() { writer_Id = writer_id, child_id = oldProductId, product_id = oldProductId, combo_type = COMBO_TYPE });
                    //檢查價格類型是否有變動,如果有則刪除原有價格數據
                    if (queryReust != null)
                    {
                        if (!price_type.Equals(queryReust.price_type.ToString()))
                        {
                            _combTempMgr = new ProductComboTempMgr(connectionString);
                            _combTempMgr.comboPriceDelete(new ProductComboTemp { Writer_Id = writer_id, Combo_Type = COMBO_TYPE, Parent_Id = oldProductId.ToString() });
                            queryReust = null;
                        }
                    }

                    if (queryReust == null)//插入
                    {
                        if (price_type == "1")
                        {
                            _pMasterTempMgr.Save(pMasterListT, null, null);
                        }
                        else
                        {
                            _pMasterTempMgr.Save(pMasterListT, ItemPList, null);
                        }
                    }
                    else//更新
                    {
                        if (price_type == "1")
                        {
                            _pMasterTempMgr.Update(pMasterListT, null);
                        }
                        else
                        {
                            _pMasterTempMgr.Update(pMasterListT, update);
                        }
                    }
                    _productTempMgr.PriceBonusInfoSave(pTemp);

                }
                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,msg:'" + Resources.Product.SAVE_FAIL + "'}";
                }
                #endregion
            }
            return json;
        }
Example #2
0
        public HttpResponseBase SaveItemPrice()
        {
            string json = string.Empty;
            string msg = string.Empty;
            try
            {
                if (!PriceMaster.CheckProdName(Request.Form["product_name"]))
                {
                    json = "{success:false,msg:'" + Resources.Product.FORBIDDEN_CHARACTER + "'}";
                    this.Response.Clear();
                    this.Response.Write(json);
                    this.Response.End();
                    return this.Response;
                }
                JavaScriptSerializer jsSer = new JavaScriptSerializer();
                string items = Request.Form["Items"];
                float default_bonus_percent = 0;
                float.TryParse(Request.Form["default_bonus_percent"] ?? "1", out default_bonus_percent);
                float bonus_percent = 0;
                float.TryParse(Request.Form["bonus_percent"] ?? "1", out bonus_percent);
                int same_price = (Request.Form["same_price"] ?? "") == "on" ? 1 : 0;
                int accumulated_bonus = (Request.Form["accumulated_bonus"] ?? "") == "on" ? 1 : 0;
                string start = Request.Form["event_product_start"] ?? Request.Form["event_start"];
                string end = Request.Form["event_product_end"] ?? Request.Form["event_end"];
                string bonus_start = Request.Form["bonus_percent_start"];
                string bonus_end = Request.Form["bonus_percent_end"];
                string valid_start = Request.Form["valid_start"];
                string valid_end = Request.Form["valid_end"];
                if (!string.IsNullOrEmpty(Request.Form["ProductId"]) && !string.IsNullOrEmpty(Request.Form["site_name"]))
                {
                    #region price_master,item_price  新增站台价格

                    List<ItemPrice> itemPrices = jsSer.Deserialize<List<ItemPrice>>(items);

                    PriceMaster priceMaster = new PriceMaster { bonus_percent = bonus_percent, default_bonus_percent = default_bonus_percent };
                    if (!string.IsNullOrEmpty(start))
                    {
                        priceMaster.event_start = Convert.ToUInt32(CommonFunction.GetPHPTime(start));
                    }
                    if (!string.IsNullOrEmpty(end))
                    {
                        priceMaster.event_end = Convert.ToUInt32(CommonFunction.GetPHPTime(end));
                    }
                    priceMaster.product_name = PriceMaster.Product_Name_FM(Request.Form["product_name"]);
                    priceMaster.site_id = uint.Parse(Request.Form["site_name"]);
                    priceMaster.product_id = uint.Parse(Request.Form["ProductId"]);
                    priceMaster.user_level = uint.Parse(Request.Form["user_level"] ?? "1");
                    priceMaster.same_price = same_price;
                    priceMaster.accumulated_bonus = Convert.ToUInt32(accumulated_bonus);
                    priceMaster.price_status = 2;//申請審核
                    priceMaster.price = Convert.ToInt32(itemPrices.Min(m => m.item_money));
                    priceMaster.event_price = Convert.ToInt32(itemPrices.Min(m => m.event_money));
                    priceMaster.cost = Convert.ToInt32(itemPrices.Min(m => m.item_cost));
                    priceMaster.event_cost = Convert.ToInt32(itemPrices.Min(m => m.event_cost));
                    if (same_price == 0)
                    {
                        priceMaster.max_price = Convert.ToInt32(itemPrices.Max(m => m.item_money));
                        priceMaster.max_event_price = Convert.ToInt32(itemPrices.Max(m => m.event_money));
                    }
                    if (!string.IsNullOrEmpty(bonus_start))
                    {
                        priceMaster.bonus_percent_start = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_start));
                    }
                    if (!string.IsNullOrEmpty(bonus_start))
                    {
                        priceMaster.bonus_percent_end = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_end));
                    }
                    if (!string.IsNullOrEmpty(valid_start))
                    {
                        priceMaster.valid_start = Convert.ToInt32(CommonFunction.GetPHPTime(valid_start));
                    }
                    if (!string.IsNullOrEmpty(valid_end))
                    {
                        priceMaster.valid_end = Convert.ToInt32(CommonFunction.GetPHPTime(valid_end));
                    }

                    _usersMgr = new UsersMgr(connectionString);
                    System.Data.DataTable dt_User = _usersMgr.Query(Request.Form["user_id"] ?? "");
                    if (dt_User != null && dt_User.Rows.Count > 0)
                    {
                        priceMaster.user_id = Convert.ToUInt32(dt_User.Rows[0]["user_id"]);
                    }

                    Resource.CoreMessage = new CoreResource("Product");
                    _priceMasterMgr = new PriceMasterMgr(connectionString);
                    _priceMasterTsMgr = new PriceMasterTsMgr("");
                    int priceMasterId = _priceMasterMgr.Save(priceMaster, itemPrices, null, ref msg);
                    if (priceMasterId != -1)
                    {
                        //價格修改 申請審核
                        PriceUpdateApply priceUpdateApply = new PriceUpdateApply { price_master_id = Convert.ToUInt32(priceMasterId) };
                        priceUpdateApply.apply_user = Convert.ToUInt32((Session["caller"] as Caller).user_id);

                        //價格審核記錄
                        PriceUpdateApplyHistory applyHistroy = new PriceUpdateApplyHistory();
                        applyHistroy.user_id = Convert.ToInt32(priceUpdateApply.apply_user);
                        //applyHistroy.price_status = 1;
                        //applyHistroy.type = 3;
                        applyHistroy.price_status = 1; //edit by wwei0216w 2014/12/16 價格修改時 price_status為 2申請審核
                        applyHistroy.type = 1;//edit by wwei0216w 所作操作為 1:申請審核的操作 


                        _priceUpdateApplyMgr = new PriceUpdateApplyMgr(connectionString);
                        _priceUpdateApplyHistoryMgr = new PriceUpdateApplyHistoryMgr(connectionString);

                        int apply_id = _priceUpdateApplyMgr.Save(priceUpdateApply);
                        if (apply_id != -1)
                        {
                            priceMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                            priceMaster.apply_id = Convert.ToUInt32(apply_id);
                            applyHistroy.apply_id = apply_id;
                            ArrayList excuteSql = new ArrayList();
                            excuteSql.Add(_priceMasterMgr.Update(priceMaster));
                            excuteSql.Add(_priceMasterTsMgr.UpdateTs(priceMaster));//edit by xiangwang0413w 2014/07/22 更新price_master_ts表後用時更新price_master_ts表,以便價格審核
                            excuteSql.Add(_priceUpdateApplyHistoryMgr.SaveSql(applyHistroy));

                            _functionMgr = new FunctionMgr(connectionString);
                            string function = Request.Params["function"] ?? "";
                            Function fun = _functionMgr.QueryFunction(function, "/Product/ProductSave");
                            int functionid = fun == null ? 0 : fun.RowId;
                            HistoryBatch batch = new HistoryBatch { functionid = functionid };
                            batch.batchno = Request.Params["batch"] ?? "";
                            batch.kuser = (Session["caller"] as Caller).user_email;

                            _tableHistoryMgr = new TableHistoryMgr(connectionString);
                            if (_tableHistoryMgr.SaveHistory<PriceMaster>(priceMaster, batch, excuteSql))
                            {
                                json = "{success:true}";
                            }
                            else
                            {
                                json = "{success:false,msg:'" + Resources.Product.SAVE_FAIL + "'}";
                            }
                        }
                        else
                        {
                            json = "{success:false,msg:'" + Resources.Product.SAVE_FAIL + "'}";
                        }
                    }
                    else
                    {
                        json = "{success:false,msg:'" + msg + "'}";
                    }
                    #endregion
                }
                else
                {
                    #region product_item_temp 修改临时表数据

                    ProductTemp proTemp = new ProductTemp { Bonus_Percent = bonus_percent, Default_Bonus_Percent = default_bonus_percent };
                    List<ProductItemTemp> proItemTemps = jsSer.Deserialize<List<ProductItemTemp>>(items);
                    if (!string.IsNullOrEmpty(Request.Form["OldProductId"]))
                    {
                        proTemp.Product_Id = Request.Form["OldProductId"];
                        proItemTemps.ForEach(m => m.Product_Id = proTemp.Product_Id);
                    }

                    if (!string.IsNullOrEmpty(start))
                    {
                        proTemp.Bonus_Percent_Start = Convert.ToUInt32(CommonFunction.GetPHPTime(start));
                        proItemTemps.ForEach(m => m.Event_Product_Start = proTemp.Bonus_Percent_Start);
                    }
                    if (!string.IsNullOrEmpty(end))
                    {
                        proTemp.Bonus_Percent_End = Convert.ToUInt32(CommonFunction.GetPHPTime(end));
                        proItemTemps.ForEach(m => m.Event_Product_End = proTemp.Bonus_Percent_End);
                    }
                    if (!string.IsNullOrEmpty(Request.Form["product_price_list"]))
                    {
                        uint product_price_list = 0;
                        uint.TryParse(Request.Form["product_price_list"] ?? "0", out product_price_list);
                        proTemp.Product_Price_List = product_price_list;
                    }
                    if (!string.IsNullOrEmpty(Request.Form["bag_check_money"]))
                    {
                        proTemp.Bag_Check_Money = uint.Parse(Request.Form["bag_check_money"]);
                    }
                    proTemp.show_listprice = Convert.ToUInt32((Request.Form["show_listprice"] ?? "") == "on" ? 1 : 0);
                    proTemp.Writer_Id = (Session["caller"] as Caller).user_id;
                    proTemp.Combo_Type = COMBO_TYPE;
                    proItemTemps.ForEach(m => m.Writer_Id = proTemp.Writer_Id);

                    _productTempMgr = new ProductTempMgr(connectionString);
                    #region PriceMasterTemp
                    PriceMasterTemp priceMasterTemp = new PriceMasterTemp { price_status = 1, default_bonus_percent = default_bonus_percent, bonus_percent = bonus_percent, same_price = same_price };
                    priceMasterTemp.accumulated_bonus = Convert.ToUInt32(accumulated_bonus);
                    priceMasterTemp.product_id = proTemp.Product_Id;
                    priceMasterTemp.combo_type = COMBO_TYPE;
                    priceMasterTemp.product_name = PriceMaster.Product_Name_FM(Request.Form["product_name"] ?? "");
                    priceMasterTemp.writer_Id = proTemp.Writer_Id;
                    priceMasterTemp.site_id = 1;//默認站臺1:吉甲地
                    priceMasterTemp.user_level = 1;
                    priceMasterTemp.price = Convert.ToInt32(proItemTemps.Min(m => m.Item_Money));
                    priceMasterTemp.event_price = Convert.ToInt32(proItemTemps.Min(m => m.Event_Item_Money));
                    priceMasterTemp.cost = Convert.ToInt32(proItemTemps.Min(m => m.Item_Cost));
                    priceMasterTemp.event_cost = Convert.ToInt32(proItemTemps.Min(m => m.Event_Item_Cost));
                    if (same_price == 0)
                    {
                        priceMasterTemp.max_price = Convert.ToInt32(proItemTemps.Max(m => m.Item_Money));
                        priceMasterTemp.max_event_price = Convert.ToInt32(proItemTemps.Max(m => m.Event_Item_Money));
                    }
                    if (!string.IsNullOrEmpty(bonus_start))
                    {
                        priceMasterTemp.bonus_percent_start = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_start));
                    }
                    if (!string.IsNullOrEmpty(bonus_start))
                    {
                        priceMasterTemp.bonus_percent_end = Convert.ToUInt32(CommonFunction.GetPHPTime(bonus_end));
                    }
                    if (!string.IsNullOrEmpty(start))
                    {
                        priceMasterTemp.event_start = Convert.ToUInt32(CommonFunction.GetPHPTime(start));
                    }
                    if (!string.IsNullOrEmpty(end))
                    {
                        priceMasterTemp.event_end = Convert.ToUInt32(CommonFunction.GetPHPTime(end));
                    }
                    if (!string.IsNullOrEmpty(valid_start))
                    {
                        priceMasterTemp.valid_start = Convert.ToInt32(CommonFunction.GetPHPTime(valid_start));
                    }
                    if (!string.IsNullOrEmpty(valid_end))
                    {
                        priceMasterTemp.valid_end = Convert.ToInt32(CommonFunction.GetPHPTime(valid_end));
                    }
                    #endregion

                    _productItemTempMgr = new ProductItemTempMgr(connectionString);
                    _priceMasterTempMgr = new PriceMasterTempMgr(connectionString);
                    if (_productItemTempMgr.UpdateCostMoney(proItemTemps) && _productTempMgr.PriceBonusInfoSave(proTemp) > 0)
                    {
                        bool result = false;
                        PriceMasterTemp query = new PriceMasterTemp { writer_Id = priceMasterTemp.writer_Id, product_id = proTemp.Product_Id, combo_type = COMBO_TYPE };
                        if (_priceMasterTempMgr.Query(query) == null)//插入
                        {
                            result = _priceMasterTempMgr.Save(new List<PriceMasterTemp> { priceMasterTemp }, null, null);
                        }
                        else//更新
                        {
                            result = _priceMasterTempMgr.Update(new List<PriceMasterTemp> { priceMasterTemp }, null);
                        }
                        json = "{success:" + result.ToString().ToLower() + "}";
                    }
                    else
                    {
                        json = "{success:false}";
                    }
                    #endregion
                }
            }
            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,msg:'" + Resources.Product.SAVE_FAIL + "'}";
            }
            this.Response.Clear();
            this.Response.Write(json);
            this.Response.End();
            return this.Response;
        }
        /// <summary>
        /// 批量新增組合商品價格
        /// </summary>
        /// <param name="pmc"></param>
        /// <param name="batch"></param>
        /// <param name="typePrice"></param>
        /// <param name="list_priceMaster"></param>
        /// <param name="chkCost">0 為 活動成本 設定 原成本,1 為 活動成本 依 折數 計算</param>  //add by zhuoqin0830w  2015/04/02
        /// <returns></returns>
        public string AddItemProduct(PriceMasterCustom pmc, HistoryBatch batch, string typePrice, List<PriceMaster> list_priceMaster, int chkCost)
        {
            ProductTemp pTemp = new ProductTemp();
            //List<List<ItemPrice>> ItemPList = new List<List<ItemPrice>>();
            PriceMasterTemp pMasterTemp = new PriceMasterTemp();
            string json = "{success:true}";
            if (!string.IsNullOrEmpty(pmc.product_id.ToString()))
            {
                #region 正式表操作
                //插入price_master
                _priceMasterMgr = new PriceMasterMgr(connectionString);
                _priceMasterTsMgr = new PriceMasterTsMgr(connectionString);
                PriceMaster gigade = list_priceMaster.Where(m => m.product_id == pmc.product_id).FirstOrDefault();
                PriceMaster pMaster = new PriceMaster();
                pMaster.product_id = pmc.product_id;
                if (pmc.combination == 1)
                {
                    pMaster.child_id = 0;
                }
                else if (pmc.combination != 1 && pmc.combination != 0)
                {
                    pMaster.child_id = Convert.ToInt32(pmc.product_id);
                }

                pMaster.site_id = pmc.site_id;
                uint userId = 0;
                if (userId != 0)
                {
                    pMaster.user_id = userId;
                }
                if (pmc.user_level.ToString() != "")
                {
                    pMaster.user_level = pmc.user_level;
                }
                pMaster.product_name = pmc.product_name;
                pMaster.bonus_percent = gigade.bonus_percent;
                pMaster.cost = pmc.cost_at;
                pMaster.price = pmc.price_at;
                pMaster.max_price = pmc.max_price;
                pMaster.max_event_price = pmc.max_price;
                pMaster.default_bonus_percent = gigade.default_bonus_percent;
                if (typePrice == "discount")
                {
                    pMaster.event_price = CommonFunction.ArithmeticalDiscount(pmc.price, pmc.event_price_discount);//Convert.ToInt32(Convert.ToDouble(pmc.price) * (pmc.event_price_discount * 0.01));
                    //add by zhuoqin0830w  2015/04/02  判斷是否是  依原成本設定值
                    if (chkCost == 1)
                    {
                        //eidt by zhuoqin0830w  更改商品活動成本驗算公式使活動價乘以折扣  2015/02/27
                        pMaster.event_cost = CommonFunction.ArithmeticalDiscount(pmc.event_price, pmc.event_cost_discount);// Convert.ToInt32(Convert.ToDouble(pmc.cost) * (pmc.event_cost_discount * 0.01));
                    }
                    else { pMaster.event_cost = pmc.event_cost; }
                }
                else
                {
                    pMaster.event_price = pmc.event_price;
                    pMaster.event_cost = pmc.event_cost;
                }
                pMaster.same_price = gigade.same_price;
                pMaster.price_status = 2;//申請審核
                pMaster.accumulated_bonus = gigade.accumulated_bonus;

                #region 時間 活動時間
                if (pmc.event_start.ToString() != "")
                {
                    pMaster.event_start = pmc.event_start;
                }
                if (pmc.event_end.ToString() != "")
                {
                    pMaster.event_end = pmc.event_end;
                }
                #endregion

                //價格修改 申請審核
                PriceUpdateApply priceUpdateApply = new PriceUpdateApply();
                priceUpdateApply.apply_user = Convert.ToUInt32((Session["caller"] as Caller).user_id);

                //價格審核記錄
                PriceUpdateApplyHistory applyHistroy = new PriceUpdateApplyHistory();
                applyHistroy.user_id = Convert.ToInt32(priceUpdateApply.apply_user);
                applyHistroy.price_status = 1;
                //applyHistroy.type = 3;
                applyHistroy.type = 1;//edit by wwei0216w 所作操作為 1:申請審核的操作 

                _priceUpdateApplyMgr = new PriceUpdateApplyMgr(connectionString);
                _priceUpdateApplyHistoryMgr = new PriceUpdateApplyHistoryMgr(connectionString);
                _tableHistoryMgr = new TableHistoryMgr(connectionString);
                ArrayList excuteSql = new ArrayList();
                #region 新增
                string msg = string.Empty;
                int status = 0;
                int priceMasterId = 0;
                IPriceMasterImplMgr i = new PriceMasterMgr(connectionString);
                List<ItemPrice> iprice = i.AddSingleProduct(pmc, typePrice);
                var result = _priceMasterMgr.Query(pMaster);
                if (result.Count > 0)
                {
                    priceMasterId = -1;
                    msg = pMaster.product_id.ToString();
                    return msg;
                }
                if (typePrice == "discount")
                {
                    pMaster.price = CommonFunction.ArithmeticalDiscount(pmc.price, pmc.price_discount);// Convert.ToInt32(Convert.ToDouble(pmc.price) * (pmc._discount * 0.01));
                    pMaster.cost = CommonFunction.ArithmeticalDiscount(pmc.cost, pmc.cost_discount);// Convert.ToInt32(Convert.ToDouble(pmc.cost) * (pmc._cost_discount * 0.01));
                    pMaster.event_price = CommonFunction.ArithmeticalDiscount(pmc.price, pmc.event_price_discount);// Convert.ToInt32(Convert.ToDouble(pmc.price) * (pmc.event_price_discount * 0.01));
                    //add by zhuoqin0830w  2015/04/02  判斷是否是  依原成本設定值
                    if (chkCost == 1)
                    {
                        pMaster.event_cost = CommonFunction.ArithmeticalDiscount(pmc.event_price, pmc.event_cost_discount);// Convert.ToInt32(Convert.ToDouble(pmc.cost) * (pmc.event_cost_discount * 0.01));
                    }
                    else { pMaster.event_cost = pmc.cost; }
                }

                priceMasterId = _priceMasterMgr.Save(pMaster, iprice, null, ref msg);
                if (priceMasterId != -1)
                {
                    priceUpdateApply.price_master_id = Convert.ToUInt32(priceMasterId); //價格更新申請記錄(設置更新記錄中,更新的價格id)
                    int apply_id = _priceUpdateApplyMgr.Save(priceUpdateApply);//價格更新申請記錄(新增或者更新價格后,將記錄下來插入該表)返回更新記錄的Id號
                    if (apply_id != -1)
                    {
                        pMaster = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                        pMaster.apply_id = Convert.ToUInt32(apply_id);
                        applyHistroy.apply_id = apply_id;

                        excuteSql.Add(_priceMasterMgr.Update(pMaster));
                        excuteSql.Add(_priceMasterTsMgr.UpdateTs(pMaster)); //edit by xiangwang0413w 2014/07/22 更新price_master_ts表後同時更新price_master_ts表,以便價格審核
                        excuteSql.Add(_priceUpdateApplyHistoryMgr.SaveSql(applyHistroy));
                        _tableHistoryMgr = new TableHistoryMgr(connectionString);
                        if (_tableHistoryMgr.SaveHistory<PriceMaster>(pMaster, batch, excuteSql))
                        {
                            status = 1;
                        }
                        else { status = 2; }
                    }
                    else { status = 2; }
                }
                else { status = 3; }
                if (status == 1)
                {
                    return "success";
                }
                else if (status == 2)
                {
                    return json = "商品:" + pmc.product_name + Resources.Product.SAVE_FAIL + "'}";
                }
                else
                {
                    return json = msg;
                }
                #endregion

                #endregion
            }
            return "";
        }
        /// <summary>
        /// 商品列表中各 自定價類型 商品的新增
        /// <param name="productID">商品Id號</param>
        /// add by wangwei0216w 2014/8/28
        /// <param name="chkCost">0 為 活動成本 設定 原成本,1 為 活動成本 依 折數 計算</param>  //add by zhuoqin0830w  2015/04/02
        /// </summary>
        public string ProductByPriceEach(PriceMasterCustom pmc, HistoryBatch batch, List<PriceMaster> list_priceMaster, int chkCost)
        {
            //價格修改 申請審核
            PriceUpdateApply priceUpdateApply = new PriceUpdateApply();
            priceUpdateApply.apply_user = Convert.ToUInt32((Session["caller"] as Caller).user_id);

            //價格審核記錄
            PriceUpdateApplyHistory applyHistroy = new PriceUpdateApplyHistory();
            applyHistroy.user_id = Convert.ToInt32(priceUpdateApply.apply_user);
            applyHistroy.price_status = 1;
            //applyHistroy.type = 3;
            applyHistroy.type = 1;//edit by wwei0216w 所作操作為 1:申請審核的操作 
            _priceUpdateApplyMgr = new PriceUpdateApplyMgr(connectionString);
            _priceUpdateApplyHistoryMgr = new PriceUpdateApplyHistoryMgr(connectionString);
            _tableHistoryMgr = new TableHistoryMgr(connectionString);
            ArrayList excuteSql = new ArrayList();
            string msg = "";  //定義json字符串
            _priceMasterMgr = new PriceMasterMgr(connectionString);
            //定義priceMaster對象
            var priceStores = list_priceMaster.FindAll(m => m.product_id == pmc.product_id);  //獲取各自定價商品的各自信息

            priceStores.ForEach(m =>
            {
                m.site_id = pmc.site_id;
                m.user_level = pmc.user_level;
                m.user_id = pmc.user_id;

                int event_price = m.event_price;
                int event_cost = m.event_cost;
                //將p對象賦予pm
                m.price = CommonFunction.ArithmeticalDiscount(event_price, pmc.price_discount);// Convert.ToInt32(Convert.ToDouble(event_price) * (pmc._discount * 0.01));  //新的售價
                m.cost = CommonFunction.ArithmeticalDiscount(event_cost, pmc.cost_discount); //Convert.ToInt32(Convert.ToDouble(event_cost) * (pmc._cost_discount * 0.01));//新的成本
                m.event_price = CommonFunction.ArithmeticalDiscount(event_price, pmc.event_price_discount);// Convert.ToInt32(Convert.ToDouble(event_price) * (pmc.event_price_discount * 0.01));//活動售價
                //eidt by zhuoqin0830w  更改商品活動成本驗算公式使活動價乘以折扣  2015/02/27
                if (chkCost == 1)
                {
                    m.event_cost = CommonFunction.ArithmeticalDiscount(m.event_price, pmc.event_cost_discount);// Convert.ToInt32(Convert.ToDouble(event_cost) * (pmc.event_cost_discount * 0.01));//活動成本
                }
                else { m.event_cost = event_cost; }
                m.price_status = 2;                                                                        //設置狀態為申請審核
                if (pmc.event_start.ToString() != "")
                {
                    m.event_start = pmc.event_start;
                }
                if (pmc.event_end.ToString() != "")
                {
                    m.event_end = pmc.event_end;   //設置時間
                }

            });
            var parent = priceStores.Find(m => m.product_id == m.child_id);
            //為parent賦予值
            uint userId = 0;
            int priceMasterId = -1;
            var result = _priceMasterMgr.Query(new PriceMaster { product_id = parent.product_id, child_id = parent.child_id, user_id = userId, site_id = parent.site_id });
            if (result.Count > 0)
            {
                msg = parent.product_id.ToString();
                return msg;
            }

            priceMasterId = _priceMasterMgr.Save(parent, null, null, ref msg);
            var pm = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
            int apply_id = -1;
            if (priceMasterId != -1)
            {
                priceUpdateApply.price_master_id = Convert.ToUInt32(priceMasterId);
                apply_id = _priceUpdateApplyMgr.Save(priceUpdateApply);
                if (apply_id == -1) return msg = parent.product_id.ToString();
                applyHistroy.apply_id = apply_id;
                pm.apply_id = (uint)apply_id;
                excuteSql.Add(_priceMasterMgr.Update(pm));
                excuteSql.Add(_priceMasterTsMgr.UpdateTs(pm)); //edit by xiangwang0413w 2014/07/22 更新price_master_ts表後同時更新price_master_ts表,以便價格審核
                excuteSql.Add(_priceUpdateApplyHistoryMgr.SaveSql(applyHistroy));
            }

            foreach (PriceMaster p in priceStores.FindAll(m => m.product_id != m.child_id))                 //遍歷集合
            {
                priceMasterId = _priceMasterMgr.Save(p, null, null, ref msg);
                if (priceMasterId == -1) return msg = parent.product_id.ToString();
                pm = _priceMasterMgr.Query(new PriceMaster { price_master_id = Convert.ToUInt32(priceMasterId) }).FirstOrDefault();
                pm.apply_id = (uint)apply_id;
                excuteSql.Add(_priceMasterMgr.Update(pm));
                excuteSql.Add(_priceMasterTsMgr.UpdateTs(pm)); //edit by xiangwang0413w 2014/07/22 更新price_master_ts表後同時更新price_master_ts表,以便價格審核
            }

            _tableHistoryMgr = new TableHistoryMgr(connectionString);
            if (_tableHistoryMgr.SaveHistory<PriceMaster>(parent, batch, excuteSql))
            {
                msg = "success";
            }
            else { msg = parent.product_id.ToString(); }
            return msg;
        }
Example #5
0
        public void PrepareData(List<CombinationExcel> source)
        {
            if (source != null)
            {
                source.ForEach(m => m.Validate());
                var parents = source.Where(m => m.combination.Trim() != "299" && string.IsNullOrEmpty(m.msg));

                _productMgr = new ProductMgr(strConn);
                _productItemMgr = new ProductItemMgr(strConn);
                _vendorMgr = new VendorMgr(strConn);
                _vendorBrandMgr = new VendorBrandMgr(strConn);
                _siteMgr = new SiteMgr(strConn);
                _productMigrationMgr = new ProductMigrationMgr(strConn);
                _productComboMgr = new ProductComboMgr(strConn);
                _cateMgr = new ProductCategoryMgr(strConn);
                _productCategorySetMgr = new ProductCategorySetMgr(strConn);
                _productNoticeSetMgr = new ProductNoticeSetMgr(strConn);
                _productTagSetMgr = new ProductTagSetMgr(strConn);
                _productPictureMgr = new ProductPictureMgr(strConn);
                _productStatusHistoryMgr = new ProductStatusHistoryMgr(strConn);

                foreach (var parent in parents)
                {
                    form.change(1);
                    uint product_id = uint.Parse(parent.product_id);
                    #region Product

                    ProductMigrationMap prodMigra = _productMigrationMgr.GetSingle(new ProductMigrationMap { temp_id = parent.is_exist.ToUpper().Trim().Equals("OLD") ? parent.product_id : parent.temp_id });
                    if (prodMigra != null)
                    {
                        parent.msg = "此記錄暫時編號(temp_id)已經存在;";
                        continue;
                    }

                    Product newPro = parent.is_exist.ToUpper().Trim() == "OLD" ? _productMgr.Query(new Product { Product_Id = product_id }).FirstOrDefault() : new Product();
                    if (newPro == null)
                    {
                        parent.msg = "商品不存在";
                        continue;
                    }
                    newPro.Product_Name = parent.product_name.Trim();
                    VendorBrand brand = _vendorBrandMgr.GetProductBrand(new VendorBrand { Brand_Name = parent.brand_name.Trim() });
                    if (brand == null)
                    {
                        parent.msg = "品牌不存在";
                        continue;
                    }
                    newPro.Brand_Id = brand.Brand_Id;
                    switch (parent.combination.Trim())
                    {
                        case "2":
                            newPro.Combination = 2; break;
                        case "3":
                            newPro.Combination = 3; break;
                        case "4":
                            newPro.Combination = 4; break;
                        default: break;
                    }
                    switch (parent.status.Trim().ToUpper())
                    {
                        case "SAME":
                            break;
                        case "ON":
                            newPro.Product_Status = 5; break;
                        case "OFF":
                            newPro.Product_Status = 6; break;
                        case "NEW":
                            newPro.Product_Status = 0; break;
                        default:
                            break;
                    }
                    newPro.Price_type = 1;
                    newPro.Product_Spec = 0;
                    newPro.Spec_Title_1 = string.Empty;
                    newPro.Spec_Title_2 = string.Empty;
                    newPro.Ignore_Stock = 0;// parent.ignore_stock.ToUpper().Trim() == "Y" ? 1 : 0;
                    newPro.Shortage = 0;// parent.shortage.ToUpper().Trim() == "Y" ? 1 : 0;
                    newPro.Cate_Id = parent.cate_id.Trim();
                    var vendor = _vendorMgr.GetSingle(new Vendor { vendor_id = brand.Vendor_Id });
                    if (vendor == null)
                    {
                        parent.msg = "供應商不存在";
                        continue;
                    }
                    newPro.user_id = vendor.product_manage;
                    if (!string.IsNullOrEmpty(parent.service_fee))
                    { 
                        uint bag_check_money=0;
                        uint.TryParse(parent.service_fee,out bag_check_money);
                        newPro.Bag_Check_Money = bag_check_money;
                    }
                    #endregion

                    bool result = true;
                    ArrayList sqls = new ArrayList();
                    #region PriceMaster

                    Site site = _siteMgr.Query(new Site { Site_Name = parent.site.Trim() }).FirstOrDefault();
                    if (site == null)
                    {
                        parent.msg = "價格檔站臺不存在";
                        result = false;
                        break;
                    }
                    List<PriceMaster> priceMasters = new List<PriceMaster>();
                    //首先默認加入一筆吉甲地站臺
                    PriceMaster newPriceMaster = new PriceMaster { site_id = 1, user_level = 1, same_price = 1, accumulated_bonus = 1, default_bonus_percent = 1, bonus_percent = 1 };
                    newPriceMaster.product_name = newPro.Product_Name;
                    newPriceMaster.price_status = 1;

                    var item = _productItemMgr.Query(new ProductItem { Product_Id = newPro.Product_Id }).FirstOrDefault();
                    if (item == null)
                    {
                        parent.msg = "商品細項不存在";
                        continue;
                    }
                    #region 成本

                    int cost = 0;
                    if (!string.IsNullOrEmpty(parent.cost))
                    {
                        int.TryParse(parent.cost, out cost);
                    }
                    else
                    {
                        cost = Convert.ToInt32(item.Item_Cost);
                    }
                    newPriceMaster.cost = cost;
                    #endregion

                    #region 售價

                    int price = 0;
                    if (!string.IsNullOrEmpty(parent.price))
                    {
                        int.TryParse(parent.price, out price);
                    }
                    else
                    {
                        price = Convert.ToInt32(item.Item_Money);
                    }
                    newPriceMaster.price = price;
                    #endregion

                    newPriceMaster.event_price = Convert.ToInt32(item.Event_Item_Money);
                    newPriceMaster.event_start = item.Event_Product_Start;
                    newPriceMaster.event_end = item.Event_Product_End;
                    priceMasters.Add(newPriceMaster);

                    if (site.Site_Id != 1)
                    {
                        //如果站臺不是吉甲地就把吉甲地站臺的價格狀態改為4(下架)
                        priceMasters[0].price_status = 4;
                        //再加入非吉甲地站臺
                        newPriceMaster = new PriceMaster { site_id = site.Site_Id, user_level = 1, same_price = 1, accumulated_bonus = 1, default_bonus_percent = 1, bonus_percent = 1 };
                        newPriceMaster.product_name = newPro.Product_Name;
                        newPriceMaster.price_status = 1;
                        #region 成本

                        cost = 0;
                        if (!string.IsNullOrEmpty(parent.cost))
                        {
                            int.TryParse(parent.cost, out cost);
                        }
                        else
                        {
                            cost = Convert.ToInt32(item.Item_Cost);
                        }
                        newPriceMaster.cost = cost;
                        #endregion

                        #region 售價

                        price = 0;
                        if (!string.IsNullOrEmpty(parent.price))
                        {
                            int.TryParse(parent.price, out price);
                        }
                        else
                        {
                            price = Convert.ToInt32(item.Item_Money);
                        }
                        newPriceMaster.price = price;
                        #endregion
                        newPriceMaster.event_price = Convert.ToInt32(item.Event_Item_Money);
                        newPriceMaster.event_start = item.Event_Product_Start;
                        newPriceMaster.event_end = item.Event_Product_End;
                        priceMasters.Add(newPriceMaster);
                    }

                    #region 其他站臺價格

                    var child = source.Where(m =>
                                    m.combination.Trim() == "299"
                                    && m.formula.ToUpper().Trim() == parent.temp_id.ToUpper().Trim()
                                    && string.IsNullOrEmpty(m.msg)
                                    && m.new_old.ToUpper().Trim() == "NEW"
                                    && m.formula.ToUpper().Trim().StartsWith("P"));
                    if (child != null)
                    {
                        foreach (var c in child)
                        {
                            item = _productItemMgr.Query(new ProductItem { Product_Id = uint.Parse(c.product_id) }).FirstOrDefault();
                            if (item == null)
                            {
                                c.msg = "價格檔商品細項不存在";
                                result = false;
                                break;
                            }
                            site = _siteMgr.Query(new Site { Site_Name = c.site.Trim() }).FirstOrDefault();
                            if (site == null)
                            {
                                c.msg = "站臺不存在";
                                result = false;
                                break;
                            }
                            if (priceMasters.Exists(m => m.site_id == site.Site_Id))
                            {
                                c.msg = "站臺重複";
                                result = false;
                                break;
                            }
                            newPriceMaster = new PriceMaster { user_level = 1, same_price = 1, accumulated_bonus = 1, default_bonus_percent = 1, bonus_percent = 1 };
                            newPriceMaster.product_name = c.product_name.Trim();
                            newPriceMaster.site_id = site.Site_Id;
                            newPriceMaster.price_status = 1;
                            #region 成本

                            cost = 0;
                            if (!string.IsNullOrEmpty(c.cost))
                            {
                                int.TryParse(c.cost, out cost);
                            }
                            else
                            {
                                cost = Convert.ToInt32(item.Item_Cost);
                            }
                            newPriceMaster.cost = cost;
                            #endregion

                            #region 售價

                            price = 0;
                            if (!string.IsNullOrEmpty(c.price))
                            {
                                int.TryParse(c.price, out price);
                            }
                            else
                            {
                                price = Convert.ToInt32(item.Item_Money);
                            }
                            newPriceMaster.price = price;
                            #endregion
                            newPriceMaster.event_price = Convert.ToInt32(item.Event_Item_Money);
                            newPriceMaster.event_start = item.Event_Product_Start;
                            newPriceMaster.event_end = item.Event_Product_End;
                            priceMasters.Add(newPriceMaster);

                            if (site.Site_Name.Trim().ToLower() == "chinatrust")
                            {
                                ArrayList category_set = CategorySet(c, brand.Brand_Id);
                                if (category_set == null)
                                {
                                    result = false;
                                    break;
                                }
                                else
                                {
                                    sqls.AddRange(category_set);
                                }
                            }
                        }
                        if (!result) continue;
                    }
                    #endregion

                    #endregion

                    #region ProductCombo

                    string[] strIds = parent.formula.IndexOf(",") != -1 ? parent.formula.Trim().Split(',') : new string[] { parent.formula.Trim() };
                    string[] nums = parent.number.IndexOf(",") != -1 ? parent.number.Trim().Split(',') : new string[] { parent.number.Trim() };

                    List<Product> children = new List<Product>();
                    ProductCombo tmp;
                    for (int i = 0; i < strIds.Length; i++)
                    {
                        tmp = new ProductCombo();
                        if (parent.combination.Trim() != "2")
                        {
                            tmp.Buy_Limit = parent.buylimit.Trim().ToUpper() == "Y" ? 1 : 0;
                        }
                        else
                        {
                            tmp.S_Must_Buy = int.Parse(i >= nums.Length ? nums[nums.Length - 1] : nums[i]);
                        }
                        if (parent.combination.Trim() == "3")//為3任選時 數量為G_Must_Buy
                        {
                            tmp.G_Must_Buy = int.Parse(nums[0]);
                        }
                        switch (parent.new_old.Trim().ToUpper())
                        {
                            case "NEW":
                                var map = _productMigrationMgr.GetSingle(new ProductMigrationMap { temp_id = strIds[i] });
                                if (map == null)
                                {
                                    parent.msg = "原料編號未找到對應";
                                    break;
                                }
                                tmp.Child_Id = Convert.ToInt32(map.product_id);
                                break;
                            case "OLD":
                                tmp.Child_Id = int.Parse(strIds[i]);
                                break;
                            case "BOTH":
                                if (strIds[i].ToUpper().Trim().StartsWith("P"))
                                {
                                    var tMap = _productMigrationMgr.GetSingle(new ProductMigrationMap { temp_id = strIds[i] });
                                    if (tMap == null)
                                    {
                                        parent.msg = "原料編號未找到對應";
                                        break;
                                    }
                                    tmp.Child_Id = Convert.ToInt32(tMap.product_id);
                                }
                                else
                                {
                                    tmp.Child_Id = int.Parse(strIds[i]);
                                }
                                break;
                        }
                        if (tmp.Child_Id == 0)
                        {
                            result = false;
                            break;
                        }
                        else
                        {
                            Product tmpPro = _productMgr.Query(new Product { Product_Id = Convert.ToUInt32(tmp.Child_Id) }).FirstOrDefault();
                            if (tmpPro == null)
                            {
                                parent.msg = strIds[i] + "不存在";
                                result = false;
                                break;
                            }
                            if (tmpPro.Product_Status == 0 || tmpPro.Product_Status ==1)
                            {
                                parent.msg = strIds[i] + "商品状态不為新增、申請審核";
                                result = false;
                                break;
                            }
                            if (tmpPro.Combination != 0 && tmpPro.Combination != 1)
                            {
                                parent.msg = strIds[i] + "不是單一商品";
                                result = false;
                                break;
                            }
                            switch (newPro.Product_Freight_Set)
                            {
                                case 1:
                                case 3:
                                    if (tmpPro.Product_Freight_Set != 1 && tmpPro.Product_Freight_Set != 3) 
                                    {
                                        parent.msg = strIds[i] + "运费模式与主商品不匹配";
                                        result = false;
                                    }
                                    break;
                                case 2:
                                case 4:
                                    if (tmpPro.Product_Freight_Set != 2 && tmpPro.Product_Freight_Set != 4)
                                    {
                                        parent.msg = strIds[i] + "运费模式与主商品不匹配";
                                        result = false;
                                    }
                                    break;
                                case 5:
                                case 6:
                                    if (tmpPro.Product_Freight_Set != 5 && tmpPro.Product_Freight_Set != 6)
                                    {
                                        parent.msg = strIds[i] + "运费模式与主商品不匹配";
                                        result = false;
                                    }
                                    break;
                                default:
                                    break;
                            }
                            if (!result) break;
                            children.Add(tmpPro);
                        }
                        sqls.Add(_productComboMgr.Save(tmp));
                    }
                    if (!result) continue;
                    #endregion

                    #region product_category_set
                    if (!string.IsNullOrEmpty(parent.display))
                    {
                        ArrayList category_set = CategorySet(parent, brand.Brand_Id);
                        if (category_set == null)
                            continue;
                        else
                        {
                            foreach (var set in category_set)
                            {
                                if (!sqls.Contains(set))
                                {
                                    sqls.Add(set);
                                }
                            }
                        }
                    }
                    else
                    {
                        sqls.Add(_productCategorySetMgr.SaveFromOtherPro(new ProductCategorySet { Product_Id = product_id }));
                    }
                    #endregion

                    #region product_migration_map

                    ProductMigrationMap pMap = new ProductMigrationMap();
                    if (parent.is_exist.ToUpper().Equals("OLD"))
                    {
                        pMap.temp_id = parent.product_id;
                    }
                    else if (parent.is_exist.ToUpper().Equals("NEW"))
                    {
                        pMap.temp_id = parent.temp_id;
                    }
                    sqls.Add(_productMigrationMgr.SaveNoPrid(pMap));

                    #endregion

                    #region notice tag picture

                    sqls.Add(_productNoticeSetMgr.SaveFromOtherPro(new ProductNoticeSet { product_id = product_id }));
                    sqls.Add(_productTagSetMgr.SaveFromOtherPro(new ProductTagSet { product_id = product_id }));
                    sqls.Add(_productPictureMgr.SaveFromOtherPro(new ProductPicture { product_id = Convert.ToInt32(product_id) }));
                    sqls.Add(_productStatusHistoryMgr.SaveNoProductId(new ProductStatusHistory { type = 7, product_status = Convert.ToInt32(newPro.Product_Status) }));
                    #endregion

                    string str = string.Empty;
                    if (_productMgr.ProductMigration(newPro, priceMasters, null, null, sqls, null))
                    {
                        str = "匯入成功";
                    }
                    else
                    {
                        str = "保存至數據庫失敗";
                    }
                    parent.msg = str;
                    source.FindAll(m =>
                                    m.combination.Trim() == "299"
                                    && m.formula.ToUpper().Trim() == parent.temp_id.ToUpper().Trim()
                                    && string.IsNullOrEmpty(m.msg)
                                    && m.new_old.ToUpper().Trim() == "NEW"
                                    && m.formula.ToUpper().Trim().StartsWith("P")).ForEach(m => m.msg = str);
                }

                #region 其他站臺價格

                var pChild = source.Where(m => m.combination.Trim() == "299" && m.new_old.ToUpper().Trim() == "OLD" && string.IsNullOrEmpty(m.msg));
                if (pChild != null)
                {
                    ProductItem item;
                    PriceMaster newPriceMaster;
                    Site site;
                    _priceMasterMgr = new PriceMasterMgr(strConn);
                    foreach (var c in pChild)
                    {
                        ProductMigrationMap prodMigra = _productMigrationMgr.GetSingle(new ProductMigrationMap { temp_id = c.formula.Trim() });
                        if (prodMigra == null)
                        {
                            c.msg = "原料編號對照不存在";
                            continue;
                        }
                        item = _productItemMgr.Query(new ProductItem { Product_Id = uint.Parse(c.product_id) }).FirstOrDefault();
                        if (item == null)
                        {
                            c.msg = "價格檔商品細項不存在";
                            continue;
                        }
                        site = _siteMgr.Query(new Site { Site_Name = c.site.Trim() }).FirstOrDefault();
                        if (site == null)
                        {
                            c.msg = "站臺不存在";
                            continue;
                        }
                        newPriceMaster = new PriceMaster { user_level = 1, same_price = 1, accumulated_bonus = 1, default_bonus_percent = 1, bonus_percent = 1 };
                        newPriceMaster.product_name = c.product_name.Trim();
                        newPriceMaster.product_id = prodMigra.product_id;
                        newPriceMaster.child_id = Convert.ToInt32(prodMigra.product_id);
                        newPriceMaster.site_id = site.Site_Id;
                        newPriceMaster.price_status = 1;
                        #region 成本

                        int cost = 0;
                        if (!string.IsNullOrEmpty(c.cost))
                        {
                            int.TryParse(c.cost, out cost);
                        }
                        else
                        {
                            cost = Convert.ToInt32(item.Item_Cost);
                        }
                        newPriceMaster.cost = cost;
                        #endregion

                        #region 售價

                        int price = 0;
                        if (!string.IsNullOrEmpty(c.price))
                        {
                            int.TryParse(c.price, out price);
                        }
                        else
                        {
                            price = Convert.ToInt32(item.Item_Money);
                        }
                        newPriceMaster.price = price;
                        #endregion
                        newPriceMaster.event_price = Convert.ToInt32(item.Event_Item_Money);
                        newPriceMaster.event_start = item.Event_Product_Start;
                        newPriceMaster.event_end = item.Event_Product_End;

                        ArrayList category_set = new ArrayList();
                        if (site.Site_Name.Trim().ToLower() == "chinatrust")
                        {
                            Product pro= _productMgr.Query(new Product { Product_Id = item.Product_Id }).FirstOrDefault();
                            if (pro == null)
                            {
                                c.msg = "商品不存在";
                                continue;
                            }
                            #region 更新該站臺商品的 product_category_set
                            
                            bool result = true;
                            System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex("^[0-9]*$");
                            string[] cateArray = c.display.Split(',');
                            foreach (string strcate in cateArray)
                            {
                                if (!string.IsNullOrEmpty(strcate))
                                {
                                    if (regx.IsMatch(strcate))
                                    {
                                        ProductCategory query = _cateMgr.QueryAll(new ProductCategory { category_id = uint.Parse(strcate) }).FirstOrDefault();
                                        if (query == null || strcate.Equals("0"))
                                        {
                                            c.msg = "display:" + strcate + " 不存在;";
                                            result = false;
                                            break;
                                        }
                                        else
                                        {
                                            ProductCategorySet category = new ProductCategorySet { Brand_Id = pro.Brand_Id, Category_Id = uint.Parse(strcate), Product_Id = prodMigra.product_id };
                                            if (_productCategorySetMgr.Query(category).FirstOrDefault() == null)
                                            {
                                                category_set.Add(_productCategorySetMgr.Save(category));
                                            }
                                            else
                                            {
                                                c.msg = "display:" + strcate + " 已存在;";
                                                result = false;
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        c.msg = "display:" + strcate + " 格式不正確 ";
                                        result = false;
                                        break;
                                    }
                                }
                            }
                            if (!result) continue;
                            #endregion
                        }

                        string str = string.Empty;
                        if (_priceMasterMgr.Save(newPriceMaster, null, category_set, ref str) > 0)
                        {
                            c.msg = "匯入成功";
                        }
                        else
                        {
                            c.msg = string.IsNullOrEmpty(str) ? "保存至數據庫失敗" : str;
                        }
                    }
                }
                #endregion
            }
        }