using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using V5Shop.Data;
using System.Text;
using System.IO;

namespace InfoCenter
{
    public partial class V5Shop_OrderApi : System.Web.UI.Page
    {
        private string code = string.Empty;
        private string apiUrl = string.Empty;
        private string verifyCode = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string action = GetRequest("action");
            code = GetRequest("code");
            apiUrl = GetRequest("apiurl");

            switch (action)
            {
                case "getorder":
                    ShowNewOrder();
                    break;
            }
        }

        /// <summary>
        /// 获取最新订单
        /// </summary>
        private void ShowNewOrder()
        {
            //获取订单记录文本
            string orderListStr = string.Empty;
            string iniFileName = Server.MapPath("orderhistory.ini");
            if (File.Exists(iniFileName))
                orderListStr = File.ReadAllText(iniFileName);

            StringBuilder builder = new StringBuilder();
            StringBuilder orderListBuilder = new StringBuilder();

            //增加XML头文件
            builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
            //循环构造XML结构数据
            DataTable dt = DatabaseProvider.GetInstance().GetOrder();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //如果该订单已经输出过则不显示
                if (orderListStr.IndexOf(dt.Rows[i]["Number"].ToString() + "|") != -1)
                    continue;

                //生成订单XML
                builder.Append("<Order>\r\n");
                builder.Append("<Ver>1.0</Ver>\r\n");
                builder.Append("<OrderID>" + Guid.NewGuid().ToString() + "</OrderID>\r\n");
                builder.Append("<DateTime>" + dt.Rows[i]["Date"].ToString() + "</DateTime>\r\n");
                builder.Append("<BuyerID>" + dt.Rows[i]["UserName"].ToString() + "</BuyerID>\r\n");
                builder.Append("<BuyerName>" + dt.Rows[i]["ReceiveName"].ToString() + "</BuyerName>\r\n");
                builder.Append("<Country>--</Country>\r\n");
                builder.Append("<Province>--</Province>\r\n");
                builder.Append("<City>--</City>\r\n");
                builder.Append("<Town>--</Town>\r\n");
                builder.Append("<Adr>" + dt.Rows[i]["ReceiveAddress"].ToString() + "</Adr>\r\n");
                builder.Append("<Zip>" + dt.Rows[i]["ReceivePostCode"].ToString() + "</Zip>\r\n");
                builder.Append("<Email>" + dt.Rows[i]["SendEmail"].ToString() + "</Email>\r\n");
                builder.Append("<Phone>" + dt.Rows[i]["ReceiveMobile"].ToString() + "</Phone>\r\n");
                builder.Append("<Total>" + dt.Rows[i]["Price"].ToString() + "</Total>\r\n");
                builder.Append("<Postage>" + dt.Rows[i]["Fee"].ToString() + "</Postage>\r\n");
                builder.Append("<Remark>" + dt.Rows[i]["UserRemark"].ToString() + "</Remark>\r\n");
                builder.Append("<TradeNO>" + dt.Rows[i]["Number"].ToString() + "</TradeNO>\r\n");
                builder.Append("<TradeURL>" + GetTrueUrl().ToLower().Replace("member/infocenter/apilist/", "") + "</TradeURL>\r\n");

                DataTable dtProduct = GetProductByOrderNumber(dt.Rows[i]["Number"].ToString());
                for (int j = 0; j < dtProduct.Rows.Count; j++)
                {
                    builder.Append("<Item>\r\n");
                    builder.Append("<GoodsID>" + dtProduct.Rows[j]["Barcode"].ToString() + "</GoodsID>\r\n");
                    builder.Append("<GoodsName>" + dtProduct.Rows[j]["Name"].ToString() + "</GoodsName>\r\n");
                    builder.Append("<Price>" + dtProduct.Rows[j]["MemberPrice"].ToString() + "</Price>\r\n");
                    builder.Append("<Count>" + dtProduct.Rows[j]["Count"].ToString() + "</Count>\r\n");
                    builder.Append("<Reserved3></Reserved3>\r\n");
                    builder.Append("<Reserved4></Reserved4>\r\n");
                    builder.Append("</Item>\r\n");
                }

                builder.Append("</Order>\r\n");
                //记录该订单已经被同步
                orderListBuilder.Append(dt.Rows[i]["Number"].ToString() + "|");
                break;
            }
            //生成记录文本
            File.WriteAllText(iniFileName, orderListStr + orderListBuilder.ToString());
            //输出XML数据
            Response.Write(builder.ToString());
            Response.End();
        }

        /// <summary>
        /// 根据订单号查询商品信息
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        /// <remarks>添加标识: Add by 沈先强 2010-04-13</remarks>
        private DataTable GetProductByOrderNumber(string orderID)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(" SELECT o.*,t.Barcode ")
                .Append(" FROM Web_OrderProduct o")
                .Append(" INNER JOIN Web_TrueProduct t ON o.TrueProductId = t.ID")
                .Append(" WHERE OrderNumber = '" + orderID + "'");
            return DbHelper.ExecuteDataTable(sql.ToString());
        }

        /// <summary>
        /// 获取真实URL地址
        /// </summary>
        /// <returns></returns>
        public static string GetTrueUrl()
        {
            string TrueUrl = string.Empty;
            string TheUrl = HttpContext.Current.Request.Url.ToString();
            string[] UrlArray = TheUrl.Split('?')[0].Split('/');

            TrueUrl = TheUrl.Split('?')[0].Replace(UrlArray[UrlArray.Length - 1], "");

            return TrueUrl;
        }

        /// <summary>
        /// 获取传递过来的参数
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetRequest(string key)
        {
            return Request.QueryString[key] == null ? "" : Request.QueryString[key].ToString();
        }
    }
}