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_selectTable : 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") || jd.Contains("conds")))
            {
                string action = jd.Contains("action") ? jd["action"].ToString() : "wirte";
                eDataBase db = eBase.DataBase;
                if (datasource.Length > 0) db = new eDataBase(datasource);
                if (action == "count")
                {
                    string conds = jd.Contains("conds") ? jd["conds"].ToString() : "";
                    string group = jd.Contains("group") ? jd["group"].ToString() : "";

                    eList list = new eList(name, db);
                    list.Fields.Add("isnull(sum(1),0) as allcount");
                    if (group.Length > 0)
                    {
                        list.Fields.Add("COUNT(DISTINCT " + group + ") as [groupcount]");
                        list.Fields.Add("isnull(max(" + group + "),'0') as [groupid]");
                    }
                    else
                    {
                        list.Fields.Add("COUNT(1) as [groupcount]");
                        list.Fields.Add("'0' as [groupid]");
                    }
                   
                    if (conds.Length > 0)
                    {
                        string[] arr = conds.Split(",".ToCharArray());
                        foreach (string item in arr)
                        {
                            string[] arr2 = item.Split(":".ToCharArray());
                            if (arr2.Length == 2)
                            {
                                
                                list.Where.Add(arr2[0], "=", arr2[1]);
                            }
                        }
                    }
                    DataTable tb = list.getDataTable();
                    if (tb.Rows.Count == 1)
                    {
                        //eBase.AppendLog("count:" + list.SQL);
                        JsonData jd2 = tb.Rows[0].toJSONData();
                        jd2["success"] = true;
                        jd2["errcode"] = "0";
                        jd2["message"] = "执行成功";

                        eResult.WriteJson(jd2);
                    }
                    else
                    {
                        JsonData jd2 = new JsonData();
                        jd2["allcount"] = 0;
                        jd2["groupcount"] = 0;
                        jd2["groupid"] = "";
                        jd2["success"] = true;
                        jd2["errcode"] = "-1";
                        jd2["message"] = "执行失败";

                        
                        eResult.WriteJson(jd2);
                    }
                }
                else
                {
                    JsonData fields = JsonMapper.ToObject("[]");
                    if (jd["fields"].IsObject) fields.Add(jd["fields"]);
                    if (jd["fields"].IsArray) fields = jd["fields"];
                    if (action == "write")
                    {
                        #region 写入
                        foreach (JsonData item in fields)
                        {
                            string selected = item["selected"].ToString().ToLower();

                            eList list = new eList(name, db);
                            list.Fields.Add(list.primaryKey);
                            foreach (string key in item.Keys())
                            {
                                if (key == "selected") continue;
                                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())
                            {
                                if (key == "selected") continue;
                                etb.Fields.Add(key, item[key]);
                            }
                            if (selected == "true")
                            {
                                if (pk.Length == 0)
                                {
                                    etb.Add();
                                }
                                else
                                {
                                    etb.Where.Add(etb.primaryKey, "=", pk);
                                    etb.Update();
                                }
                            }
                            else
                            {
                                if (pk.Length > 0)
                                {
                                    etb.Where.Add(etb.primaryKey, "=", pk);
                                    etb.DeleteTrue();
                                }
                            }
                        }
                        #endregion
                    }
                    else if (action == "read")
                    {
                        foreach (JsonData item in fields)
                        {
                            eList list = new eList(name, db);
                            list.Fields.Add(list.primaryKey);
                            foreach (string key in item.Keys())
                            {
                                if (key == "selected") continue;
                                list.Where.Add(key, "=", item[key]);
                            }
                            string pk = list.getValue();

                            if (pk.Length > 0)
                            {
                                item["selected"] = true;
                            }
                        }
                        eResult.WriteJson(fields);
                    }
                }
                eResult.Success("执行成功!");
            }
        }
        eResult.Success("执行失败!");
    }
}