<%@ WebHandler Language="C#"     Class="ShopService" %>

using System;
using System.Data;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Xml;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using HoWave.Web;
public class ShopService : HoWave.Web.Shop.Shop, IHttpHandler, IReadOnlySessionState
{
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain"; 
        string action = context.Request.Params["Action"];
        switch (action)
        {
            case "GetProductMessage":
                GetProductMessage(context);
                break;
            case "ShowOrderItem":
                ShowOrderItem(context);
                break;
            case "GetRequestMessage":
                GetRequestMessage(context);
                break;
            case "GetUnReadMsg":
                GetMessageCount(context);
                break;
            case "CheckLogin":
                CheckUserLogin(context);
                break;
            case "GetOrderList":
                GetOrderListByProductID(context);
                break;
            case "LeaveMsg":
                LeaveMsg(context);
                break;
            case "GetShopMsg":
                GetShopMsg(context);
                break;
            case "GetSalerRecommendProduct":
                ShowSalerRecommendProduct(context);
                break;
            case "GetAnnounceList":
                GetAnnounce(context);
                break;
                
          
                
                
        }
        context.Response.Flush();
        context.Response.Close();
    }

    private void GetMessageCount(HttpContext context)
    {
        MessageBll msg = new MessageBll();
        string m_UserName = context.Request.Params["UserName"];
        int unreadMsg = 0;
        if(m_UserName!=null && m_UserName!="")
            unreadMsg=msg.GetUnReadNumByUserName(m_UserName);
        context.Response.Write("("+unreadMsg.ToString()+")");
        

    }

    private void GetRequestMessage(HttpContext context)
    {
        int RequestID = Convert.ToInt32(context.Request.Params["ProductID"]);
        Shop_Message message = new Shop_Message();
        DataTable dt = message.GetMessageByRequestID(RequestID);
        int rows = dt.Rows.Count;
        string str = "暂无留言！";
        string ReplayUrl = "";
        if (rows > 0)
        {
            if (rows > 10)
                rows = 10;
            str = "<dl>";
            string m_SalerID = dt.Rows[0]["M_ReceiverID"].ToString();
            for (int i = 0; i < rows; i++)
            {
                ReplayUrl = "";
                string replayText = dt.Rows[i]["R_Content"].ToString();
                
                //如果登录的人和卖家ID相同则显示所有的留言,否则只显示已经回复过的留言.
                if (user.CheckUserLogin() && user.UserID.ToString() == m_SalerID)
                {
                    if (replayText == "")
                    {
                        ReplayUrl = "&nbsp;&nbsp;<a href='Replay_Product_Msg.aspx?msg_id=" + dt.Rows[i]["M_ID"].ToString() + "&requester_name=" + Server.UrlEncode(dt.Rows[i]["M_SenderName"].ToString()) + "&request_date=" + Server.UrlEncode(dt.Rows[i]["M_DateTime"].ToString()) + "&request_text=" + Server.UrlEncode(dt.Rows[i]["M_Content"].ToString()) + "&msgType=Request&RequestID=" + dt.Rows[i]["M_ProductID"].ToString() + "' target='_blank'>回复此留言</a>";
                    }

                }

                //显示问题
                str += "<dt><div>" + dt.Rows[i]["M_SenderName"].ToString() + "：" + dt.Rows[i]["M_Content"].ToString() + ReplayUrl + "</div><b>" + dt.Rows[i]["M_DateTime"].ToString() + "</b></dt>";
                //显示回复
                if (dt.Rows[i]["R_Content"].ToString() != "")
                    str += "<dd><div>" + dt.Rows[i]["M_ReceiverName"].ToString() + "：" + dt.Rows[i]["R_Content"].ToString() + "</div><b>" + dt.Rows[i]["R_DateTime"].ToString() + "</b></dd>";

            }
            str += "</dl>";
           
        }
        context.Response.Write(str);
    }

    private void GetProductMessage(HttpContext context)
    {
        int productID = Convert.ToInt32(context.Request.Params["ProductID"]);       
         Shop_Message message = new  Shop_Message();
        DataTable dt = message.GetMessageByProductID(productID);
        int rows = dt.Rows.Count;     
            
        string str = "暂无留言！";
        if (rows > 0)
        {
            string m_SalerID = dt.Rows[0]["M_ReceiverID"].ToString();
            str = "<dl>";
            if (rows > 15)
                rows = 15;
            
            for (int i = 0; i < rows; i++)
            {
                bool IsReplay = true;   
                string ReplayUrl = "";
                string replayText = dt.Rows[i]["M_Status"].ToString();
                if (replayText == "False")
                {
                    IsReplay = false;
                    ReplayUrl = "&nbsp;&nbsp;<a href=\"javascript:leaveAuctionMessage(" + dt.Rows[i]["M_ID"].ToString() + ",'" + dt.Rows[i]["M_SenderName"].ToString() + "')\">回复此留言</a>";
                }
                             
               
                //如果登录的人和卖家ID相同则显示所有的留言,否则只显示已经回复过的留言.
                if (user.CheckUserLogin() && user.UserID.ToString() == m_SalerID)
                {
                    IsReplay = true;
                }
               
                
                
                if (IsReplay)
                {
                    //显示问题
                    str += "<dt><div>" + dt.Rows[i]["M_SenderName"].ToString() + "：" + dt.Rows[i]["M_Content"].ToString() + ReplayUrl + "</div><b>" + dt.Rows[i]["M_DateTime"].ToString() + "</b></dt>";
                    //显示回复
                    if (dt.Rows[i]["R_Content"].ToString() != "")
                        str += "<dd><div>" + dt.Rows[i]["M_ReceiverName"].ToString() + "：" + dt.Rows[i]["R_Content"].ToString() + "</div><b>" + dt.Rows[i]["R_DateTime"].ToString() + "</b></dd>";

                }
                else
                {
//       for (int ii = 0; ii < dt.Columns.Count; ii++)
//{
//context.Response.Write(dt.Columns[ii].ColumnName+"--");


//}

//context.Response.End();
                    
                    if (user.CheckUserLogin() && user.UserID  == (int)dt.Rows[i]["M_UserID"])
                    {
                        str += "<dt><div>" + dt.Rows[i]["M_SenderName"].ToString() + "：" + dt.Rows[i]["M_Content"].ToString() + "</div><b>" + dt.Rows[i]["M_DateTime"].ToString() + "</b></dt>";

                    }

                    else  if (dt.Rows[i]["R_Content"].ToString() != "")
                        str += "<dd><div>" + dt.Rows[i]["ReceiverName"].ToString() + "：" + dt.Rows[i]["R_Content"].ToString() + "</div><b>" + dt.Rows[i]["R_DateTime"].ToString() + "</b></dd>";
                }

                    

            }
            str += "</dl>";
           
        }        
        context.Response.Write(str);

    }

    private void GetShopMsg(HttpContext context)
    {
        int ShopID = Convert.ToInt32(context.Request.Params["ShopID"]);
        int ShopOwnerID = Convert.ToInt32(context.Request.Params["ShopOwnerID"]); 
        string str = "";
        Shop_Message message = new Shop_Message();
        DataTable dt = message.GetMessageByShopIDLately(ShopID, "late");
        int Sum_rows = dt.Rows.Count;
        int show_rows = 15;
        if (Sum_rows > 0)
        {
            if (show_rows > Sum_rows)
                show_rows = Sum_rows;
           
            bool m_isShopOwner = false;
            if (user.CheckUserLogin()  )
            {
                if (user.UserID == ShopOwnerID )
                    m_isShopOwner = true;
            }
            for (int i = 0; i < show_rows; i++)
            {
                bool m_replay = false;
                if (dt.Rows[i]["M_Status"].ToString() == "1" || dt.Rows[i]["M_Status"].ToString() == "True")
                {
                    m_replay = true;
                }
                else
                {
                    if (m_isShopOwner)
                        m_replay = true;
                    //如果登录的人和卖家ID相同则显示所有的留言,否则只显示已经回复过的留言.
                    if (user.CheckUserLogin() && user.UserID == (int)dt.Rows[i]["M_UserID"] )
                    {
                        m_replay = true;
                    }
                }
                if (m_replay)
                {
                    if (i != 0 && (i + 1) % 2 == 0)
                        str += "<li class=\"Alt\">";
                    else
                        str += "<li>";
                    str += "<b><a href=\"#\">" + dt.Rows[i]["M_SenderName"].ToString() + "</a></b><em>" + dt.Rows[i]["M_DateTIme"].ToString() + "</em><p class=\"MessageContent\">" + dt.Rows[i]["M_Content"].ToString() + "</p>";
                    if (dt.Rows[i]["R_Content"].ToString() != "")
                        str += "<p class=\"Replay\">店长回复：" + dt.Rows[i]["R_Content"].ToString() + "</p>";
                    else
                    {
                        if (m_isShopOwner)
                            str += "<p class=\"Replay\"><a href=\"javascript:void(0)\" onclick=\"leaveShopMessage(" + dt.Rows[i]["M_ID"].ToString() + ",'" + dt.Rows[i]["M_SenderName"].ToString() + "',event)\">回复此留言</a></p>";
                        else
                            str += "<p class=\"Replay\">&nbsp;</p>";
                    }
                    str += "</li>";
                }
                else
                {
                    if ((show_rows + 1) <= Sum_rows)
                        show_rows++;

                }


            }
            if (str != "")
            {
                str = "<ul id=\"ShopLeaveMessage\">" + Environment.NewLine + str + Environment.NewLine;
                str += "</ul><div style=\"clear:both\"></div>";

            }
            else
            {
                str = "<div style=\"height:50px;line-height:50px;text-align:center;width:98%\">暂无留言！</div>";
            }

            

        }
        context.Response.Write(str); 

    }
   


    

    public void ShowOrderItem(HttpContext context)
    {      
        string m_type = context.Request["type"];
        switch (m_type)
        {
            case "bank":
                ShowBankRollItemByOrderFormID(context);
                break;
            case "deliver":
                ShowDeliverItemByOrderFormID(context);
                break;
            case "invoice":
                ShowInvoicedItemByOrderFormID(context);
                break;

        }

    }

    private void ShowBankRollItemByOrderFormID(HttpContext context)
    {
        int OrderFormID = Convert.ToInt32(context.Request["OrderFormID"]);
        Shop_BankrollItem _sbk = new Shop_BankrollItem();
        DataTable dt = _sbk.GetBanKrollItemByOrderFormID(OrderFormID);
        StringBuilder sb = new StringBuilder();
        if (dt.Rows.Count > 0)
        {
            sb.Append("<table class=\"tableHead\" ><tr><th>交易时间</th><th>交易方式</th><th>状态</th><th>金额</th><th>备注/说明</th></tr>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string m_payType = "汇款";
                switch (dt.Rows[i]["MoneyType"].ToString())
                {
                    case "0":
                        m_payType = "现金";
                        break;
                    case "1":
                        m_payType = "银行汇款";
                        break;
                    case "2":
                        m_payType = "在线支付";
                        break;
                    case "3":
                        m_payType = "虚拟货币";
                        break;
                    case "4":
                        m_payType = "邮寄汇款";
                        break;
                    case "5":
                        m_payType = "上门收款";
                        break;
                    case "6":
                        m_payType = "支票";
                        break;                    

                }
                sb.Append("<tr><td>" + dt.Rows[i]["DateAndTime"].ToString() + "</td><td>" + m_payType + "</td><td>" + dt.Rows[i]["Status"].ToString() + "</td><td>" + dt.Rows[i]["Money"].ToString() + "</td><td>" + dt.Rows[i]["Remark"].ToString() + "</td></tr>");
                
            }
            sb.Append("</table>");
            

        }
        else
            sb.Append("<br>暂无记录");
        context.Response.Write(sb.ToString());

    }
    private void ShowDeliverItemByOrderFormID(HttpContext context)
    {
        int OrderFormID = Convert.ToInt32(context.Request["OrderFormID"]);
        Shop_DeliverItem _sd = new Shop_DeliverItem();
        DataTable dt = _sd.GetDeliverItemByOrderFormID(OrderFormID);
        StringBuilder sb = new StringBuilder();
        if (dt.Rows.Count > 0)
        {           
            sb.Append("<table class=\"tableHead\" ><tr><th>日期</th><th>方向</th><th>快递公司</th><th>快递号</th><th>客户签收</th><th>经手人</th><th>备注</th></tr>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string m_type = (dt.Rows[i]["DeliverType"].ToString() == "0") ? "发货" : "退货";
                string m_receive = (dt.Rows[i]["Received"].ToString() == "False") ? "未签收" : "已签收";
                sb.Append("<tr><td>" + dt.Rows[i]["DeliverDate"].ToString() + "</td><td>" + m_type + "</td><td>" + dt.Rows[i]["DeliverCompany"].ToString() + "</td><td>" + dt.Rows[i]["ExpressNumber"].ToString() + "</td><td>" + m_receive + "</td><td>" + dt.Rows[i]["HandlerName"].ToString() + "</td><td>" + dt.Rows[i]["Remark"].ToString() + "</td></tr>");

            }
            sb.Append("</table>");
           

        }
        else
            sb.Append("<br>暂无记录");
        context.Response.Write(sb.ToString());

    }
    private void ShowInvoicedItemByOrderFormID(HttpContext context)
    {
        int OrderFormID = Convert.ToInt32(context.Request["OrderFormID"]);
        Shop_InvoiceItem _sd = new Shop_InvoiceItem();
        DataTable dt = _sd.GetInvoiceByOrderFormID(OrderFormID);
        StringBuilder sb = new StringBuilder();
        if (dt.Rows.Count > 0)
        {
            sb.Append("<table class=\"tableHead\"><tr><th>金额</th><th>类型</th><th>发票号</th><th>抬头</th><th>开票人</th><th>录入员</th><th>开票时间</th></tr>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string m_type = dt.Rows[i]["InvoiceType"].ToString();
                switch (m_type)
                {
                    case "0":
                        m_type = "地税普通发票";
                        break;
                    case "1":
                        m_type = "国税普通发票";
                        break;
                    case "2":
                        m_type = "增值税发票";
                        break;

                }
                sb.Append("<tr><td>" + dt.Rows[i]["TotalMoney"].ToString() + "</td><td>" + m_type + "</td><td>" + dt.Rows[i]["InvoiceNum"].ToString() + "</td><td>" + dt.Rows[i]["Invoicetitle"].ToString() + "</td><td>" + dt.Rows[i]["Drawer"].ToString() + "</td><td>" + dt.Rows[i]["Inputer"].ToString() + "</td><td>" + dt.Rows[i]["InputTime"].ToString() + "</td></tr>");

            }
            sb.Append("</table>");

        }
        else
            sb.Append("<br>暂无记录");
        context.Response.Write(sb.ToString());

    }

    protected void CheckUserLogin(HttpContext context)
    {
        string result = "0";
        if (!user.CheckUserLogin() )
        {
            result = "0";
        }
        else
        {
            string m_UserName = context.Request["UserName"];
            string m_UserPassword = context.Request["Password"];
            
            //UserBll user1 = new UserBll();
           // DataTable dt = user1.GetUserByUserName(m_UserName);
          
             
                if (user.Password .ToLower() == m_UserPassword.ToLower())
                {
                    result = "1";

                }
             
            result = "1";

        }
        context.Response.Write(result);
       
       

    }


    private void GetOrderListByProductID(HttpContext context)
    {
        StringBuilder sb = new StringBuilder();
        int productID = Convert.ToInt32(context.Request.Params["ProductID"]);
        int pageIndex = 0;
        try
        {
          pageIndex = Convert.ToInt32(context.Request.Params["Page"]);
        }
        catch { }
        int count = 0;
        try
        {
           count = Convert.ToInt32(context.Request.Params["Count"]);
        }
        catch { }
        if(pageIndex<=0)
            pageIndex=1;
        if(count<0 || count>1)
            count=0;
        sb.Append("<NewDataSet>");
        int i_recordCount = 0;
        int m_pageSize = 0;
        if (productID > 0)
        {
            Shop_Order _order = new Shop_Order(conn);
            DataTable dt2 = _order.GetProductSaleOrderByProductID(productID);
            if (dt2 != null && dt2.Rows.Count > 0)
            {
                //i_recordCount = (int)dt2.Rows[0]["Total"];
                //if (i_recordCount > 0)
                //{
                    m_pageSize = i_recordCount / 10;
                    DataTable dt = _order.GetProductSaleOrderByProductID(productID);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (m_pageSize > 0)
                            m_pageSize = m_pageSize + 1;
                        else
                            m_pageSize = 1;
                        string status = string.Empty;
                        foreach (DataRow dr in dt.Rows)
                        {
                            sb.Append("<Table>");
                            sb.Append("<UserID>" + dr["UserID"].ToString() + "</UserID>");
                            sb.Append("<ShopID>" + dr["ShopID"].ToString() + "</ShopID>");
                            sb.Append("<BuyerName>" + dr["buyername"].ToString() + "</BuyerName>");
                            sb.Append("<Price>" + dr["Price"].ToString() + "</Price>");
                            sb.Append("<UpdateTime>" + dr["UpdateTime"].ToString() + "</UpdateTime>");

                            if (dr["TradeType"].ToString().Equals("1"))  //一口价
                            {
                                status = HoWave.Web.Shop.TextFormat.GetPayStatus(dr["Status"].ToString());
                            }
                            else if (dr["TradeType"].ToString().Equals("2"))　　//拍卖
                            {
                                status = HoWave.Web.Shop.TextFormat.GetPayCheckStatus(dr["Status"].ToString());
                            }
                            else if (dr["TradeType"].ToString().Equals("3"))   //团购
                            {
                                status = HoWave.Web.Shop.TextFormat.GetTeamOrderStatus(dr["Status"].ToString());
                            }

                            sb.Append("<Status>" + status + "</Status>");
                            //等待付款  已付清款
                            sb.Append("<PayStatus>" + dr["PayStatus"].ToString() + "</PayStatus>");
                            sb.Append("<Quantity>" + dr["Quantity"].ToString() + "</Quantity>");
                             
                            sb.Append("</Table>");
                        }
                    }
                //}
            }
        }
        sb.Append("<PageSize>" + m_pageSize + "</PageSize>");
        sb.Append("<RecordCount>" + i_recordCount.ToString() + "</RecordCount>");
        sb.Append("</NewDataSet>");
        context.Response.ContentType = "text/xml";
        context.Response.Write(sb.ToString());

    }

    protected void LeaveMsg(HttpContext context)
    {
        string m_checkcode=context.Request.Params["checkcode"];
        string m_content = Server.HtmlEncode(context.Request.Params["content"]);
        string h_action = context.Request.Params["h_action"];
        string h_msgID = context.Request.Params["msgID"];
        string s_product_id = context.Request.Params["product_id"];
        string s_shop_id = context.Request.Params["shop_id"];
        string s_saler_id = context.Request.Params["saler_id"];
        string saler_name = context.Request.Params["saler_name"];
        string result = "-1";


        if (!user.CheckUserLogin())
        {
            result = "-1";
        }
            
        else if (m_checkcode.ToLower() == Session["CheckCode"].ToString().ToLower())
        {
            int shop_id = 0;
            int saler_id = 0;
            int user_id = user.UserID;
            int product_id = 0;
            string UserType = "buyer";
            string m_senderName = user.UserName;
            bool m_status = false;
            int m_msgType = 0;        

            if (s_product_id != "")
                product_id = Convert.ToInt32(s_product_id);
            if (s_saler_id != "")
                saler_id = Convert.ToInt32(s_saler_id);
            if (s_shop_id != "")
                shop_id = int.Parse(s_shop_id);

            if (user.CheckUserLogin()   && user_id == saler_id)
            {
                UserType = "saler";
                m_status = true;
            }
            if (shop_id > 0 && product_id == 0)
            {
                m_msgType = 1;

            }
            Shop_Message message = new Shop_Message();            
            if (h_action != null && h_action == "replay" && h_msgID != null && h_msgID != "")
            {
                int m_msgID = int.Parse(h_msgID);
                if (message.ReplayMessage(m_content, user_id, m_msgID, m_senderName))
                {
                    result = "1";
                }
                else
                {
                    result = "-2";
                }
            }
            else if ((product_id > 0 || shop_id > 0) && user_id > 0 && saler_id > 0 && saler_name != null && saler_name != "")
            {
                message.InsertMessage(m_msgType, product_id, shop_id, user_id, m_status, m_content, m_senderName, saler_id, saler_name, UserType, 0);
                result = "1";
            }
            else
            {
                result = "-2";

            }

               
        }
        else
        {
            result = "-1";

        }
        context.Response.Write(result);

        
    }
    protected void ShowSalerRecommendProduct(HttpContext context)
    {
        int ShopID = 0;
        int m_salerID=0;
        if (!string.IsNullOrEmpty(context.Request["SalerID"]) && HoWave.Common.Text.IsNum(context.Request["SalerID"]))
        {
            m_salerID = int.Parse(context.Request["SalerID"]);
        }
        if (m_salerID > 0)
        {

            Shop_Product _product = new Shop_Product(conn);
            ShopGroupBll shopgroup = new ShopGroupBll(conn);
            object a = conn.GetScalar("Select ShopID From [HL_User] Where UserID=" + m_salerID);
            if (a != DBNull.Value && a != null)
                ShopID = (int)a;
            int Recomnum = shopgroup.GetPowerByKey<int>("MaxElite", ShopID);
            DataTable dt;
            if (Recomnum > 0)
                dt = _product.GetRecommendProductBySalerID(m_salerID, Recomnum);
            else
                dt = _product.GetRecommendProductBySalerID(m_salerID);

            if (dt.Rows.Count > 0)
            {
                int num = dt.Rows.Count;
                if (dt.Rows.Count > 6)
                    num = 6;
                string str = "<ul>";
                for (int i = 0; i < num; i++)
                {
                    string m_imgUrl = dt.Rows[i]["ProductSmallImageUrl"].ToString();
                    if (string.IsNullOrEmpty(m_imgUrl) || m_imgUrl == "")
                    {
                        m_imgUrl = "/Images/nopicture.gif";
                    }
                    str += "<li><a href='/ShowProduct.aspx?ProductID=" + dt.Rows[i]["ProductID"].ToString() + "'><img src='../" + m_imgUrl + "' align='middle' /></a><em>" + dt.Rows[i]["CurrentPrice"].ToString() + "</em><a href='ShowProduct.aspx?ProductID=" + dt.Rows[i]["ProductID"].ToString() + "' title='" + dt.Rows[i]["ProductName"].ToString() + "'>";
                    if (dt.Rows[i]["ProductName"].ToString().Length > 25)
                        str += dt.Rows[i]["ProductName"].ToString().Substring(0, 26) + "</a></li>";
                    else
                        str += dt.Rows[i]["ProductName"].ToString() + "</a></li>";
                }
                str += "</ul>";
                context.Response.Write(str);
            }
            else 
            {
                context.Response.Write("暂无推荐商品");
            }
        }
        else
        {
            context.Response.Write("暂无推荐商品");
        }

    }

    protected void GetAnnounce(HttpContext context)
    {
        int m_nums = 5;
        if (context.Request["nums"] != null)
        {
            m_nums = int.Parse(context.Request["nums"]);            

        }
        AnnounceBll _announce = new AnnounceBll();
        context.Response.Write(_announce.GetAnnounceByAnnounceID(m_nums));

    }

}