using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Top.Api;
using Top.Api.Domain;
using Top.Api.Parser;
using Top.Api.Request;
using Top.Api.Response;

public partial class webXabara_shop_taobao : System.Web.UI.Page
{
    XabaraCom xc = new XabaraCom();

    protected void Page_Load(object sender, EventArgs e)
    {
        this.js();  //定时刷新

        xc.CheckAdminLogin("");

        if (!IsPostBack)
        {
            dbDataFunction db = new dbDataFunction();

            DataTable dt;
            string strDim = "@classID,@num_iid,@title,@nick,@pic_url,@price,@click_url,@commission,@commission_rate,@commission_num,@commission_volume,@shop_click_url,@seller_credit_score,@item_location,@volume,@updateDate,@postID,@postDate,@postIP,@isGood,@isBad,@wordID,@ppID";
            string[] strValue = new string[30];

            string appkey = xc.readXmlData("xabara.config", "taobaoKeAppKey");
            if (string.IsNullOrEmpty(appkey as string))
            {
                Response.Redirect("../frame/otherSet.aspx", true);
            }
            string appsecret = xc.readXmlData("xabara.config", "taobaoKeAppSecret");
            string url = xc.readXmlData("xabara.config", "taobaoKeUrl");
            string alimamaID = xc.readXmlData("xabara.config", "taobaoKeAlimamaID");    //淘宝客推广ID

            ITopClient client = new DefaultTopClient(url, appkey, appsecret);

            Response.Write("根据分类自动同步店铺宝贝开始，如出现死机或出错，重新点击 <a href=\"taobao.aspx\">自动更新</a> 即可；<br />");

            DateTime t = DateTime.Now;
            string strSql = "select * from keywordid where isBad=0 order by updateDate ASC LIMIT 0,1";
            //Response.Write(strSql);
            //Response.End();
            dt = db.getDataTable(strSql);
            if (dt.Rows.Count > 0)
            {
                string classID = dt.Rows[0]["treeID"].ToString().Trim();
                string updateID = dt.Rows[0]["id"].ToString().Trim();
                string wordID = "0";
                string ppID = "0";
                string useType = dt.Rows[0]["useType"].ToString().Trim();
                if (useType.Equals("pp"))
                {
                    ppID = updateID;
                }
                else
                {
                    wordID = updateID;
                }
                string keyword = dt.Rows[0]["keywords"].ToString().Trim();
                Response.Write("<br />" + keyword + "　正在同步，请等待下一个关键词更新...");

                TaobaokeItemsGetRequest req = new TaobaokeItemsGetRequest();
                req.Fields = "num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume";
                req.Nick = alimamaID;
                req.Keyword = keyword;
                req.StartPrice = dt.Rows[0]["startPrice"].ToString().Trim();
                req.EndPrice = dt.Rows[0]["endPrice"].ToString().Trim();
                req.StartTotalnum = "2";
                req.EndTotalnum = "1000000";
                req.Sort = "commissionVolume_desc";
                req.MallItem = dt.Rows[0]["isTmall"].ToString().Trim();
                req.PageNo = 1L;
                req.PageSize = 40L;
                TaobaokeItemsGetResponse response = client.Execute(req);

                long shopNums = response.TaobaokeItems.Count;

                for (int i = 0; i < shopNums; i++)
                {
                    if (!string.IsNullOrEmpty(response.TaobaokeItems[i].NumIid.ToString() as string))
                    {
                        string titleStr = xc.SafeHtml(response.TaobaokeItems[i].Title);

                        strValue[0] = classID;
                        strValue[1] = response.TaobaokeItems[i].NumIid.ToString();
                        strValue[2] = titleStr;
                        strValue[3] = response.TaobaokeItems[i].Nick;
                        strValue[4] = response.TaobaokeItems[i].PicUrl;
                        strValue[5] = response.TaobaokeItems[i].Price;
                        strValue[6] = response.TaobaokeItems[i].ClickUrl;
                        strValue[7] = response.TaobaokeItems[i].Commission;
                        strValue[8] = response.TaobaokeItems[i].CommissionRate;
                        strValue[9] = response.TaobaokeItems[i].CommissionNum;
                        strValue[10] = response.TaobaokeItems[i].CommissionVolume;
                        strValue[11] = response.TaobaokeItems[i].ShopClickUrl;
                        strValue[12] = response.TaobaokeItems[i].SellerCreditScore.ToString();
                        strValue[13] = response.TaobaokeItems[i].ItemLocation;
                        long volume = response.TaobaokeItems[i].Volume;
                        strValue[14] = volume.ToString();
                        strValue[15] = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd HH:mm:ss");
                        strValue[16] = xc.adminID;
                        strValue[17] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        strValue[18] = xc.GetIP();
                        strValue[19] = "0";
                        if (volume > 49 && Convert.ToDouble(response.TaobaokeItems[i].Commission) > 10)    //直接推荐商品
                        {
                            strValue[19] = "1";
                        }
                        strValue[20] = "0";
                        strValue[21] = wordID;
                        strValue[22] = ppID;


                        DataTable dtIf = db.getDataTable("select * from taobaoKe where num_iid=" + response.TaobaokeItems[i].NumIid.ToString());  //防止重复插入
                        if (dtIf.Rows.Count > 0)
                        {
                            strValue[17] = Convert.ToDateTime(dtIf.Rows[0]["postDate"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                            if (useType.Equals("pp"))
                            {
                                strValue[21] = dtIf.Rows[0]["wordID"].ToString().Trim();
                            }
                            else
                            {
                                strValue[22] = dtIf.Rows[0]["ppID"].ToString().Trim();
                            }

                            db.InsertUpdateDB("taobaoKe", strDim, strValue, "num_iid=" + response.TaobaokeItems[i].NumIid.ToString());
                        }
                        else
                        {
                            db.InsertUpdateDB("taobaoKe", strDim, strValue, string.Empty);
                        }
                        dtIf.Dispose();
                    }
                }

                strValue[0] = DateTime.Now.ToString();
                db.InsertUpdateDB("keywordid", "@updateDate", strValue, "id=" + updateID); //更新关键词同步时间
            }
            else
            {
                Response.Redirect("taobaoke.aspx?tkType=1", true);
            }
            //宝贝同步结束
            dt.Dispose();
        }
    }

    /// <summary>
    /// js方式输出
    /// </summary>
    /// <param name="str">js代码</param>
    /// <returns></returns>
    private void js()
    {
        string str = "<script type=\"text/javascript\">window.setTimeout(\"window.location.href='taobao.aspx?tmp=" + xc.GetRnd("123", 6) + "'\",10000)</script>";

        ClientScriptManager cs = ((Page)HttpContext.Current.CurrentHandler).ClientScript;
        cs.RegisterClientScriptBlock(this.GetType(), "ClientScriptBlock", str);
    }
}