using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using LitJson;

public partial class Plugins_tableUpdate : System.Web.UI.Page
{
    public string UserArea = "Application";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.UrlReferrer == null) return;
        if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower()) return;
        if (!eConfig.portMapping && Request.Url.Port != Request.UrlReferrer.Port) return;

        eUser user = new eUser(eBase.getUserArea(UserArea));
        if (!user.Logined) eResult.Error("登录后操作!");
        user.Check();

        string json = eBase.getPostJsonString();
        if (json.Length > 10 && json.StartsWith("{") && json.EndsWith("}"))
        {
            JsonData jd = JsonMapper.ToObject(json);
            string datasource = jd.Contains("datasource") ? jd["datasource"].ToString() : "";
            string name = jd.Contains("name") ? jd["name"].ToString() : "";
            if (name.Length > 0 && jd.Contains("fields"))
            {
                eDataBase db = eBase.DataBase;
                if (datasource.Length > 0) db = new eDataBase(datasource);


                JsonData fields = JsonMapper.ToObject("[]");
                if (jd["fields"].IsObject) fields.Add(jd["fields"]);
                if (jd["fields"].IsArray) fields = jd["fields"];

                foreach (JsonData item in fields)
                {
                    eList list = new eList(name, db);
                    list.Fields.Add(list.primaryKey);
                    foreach (string key in item.Keys())
                    {
                        list.Where.Add(key, "=", item[key]);
                    }
                    string pk = list.getValue();

                    eTable etb = new eTable(name, user);
                    etb.DataBase = db;
                    foreach (string key in item.Keys())
                    {
                        etb.Fields.Add(key, item[key]);
                    }
                    if (pk.Length == 0)
                    {
                        etb.Add();
                    }
                    else
                    {
                        etb.Where.Add(etb.primaryKey, "=", pk);
                        etb.Update();
                        
                    }
                }
                eResult.Success("执行成功!");
            }
        }
        eResult.Success("执行失败!");
    }
}