using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using EKETEAM.UserControl;
using System.Xml;
using System.Xml.Serialization;
using LitJson;


namespace eFrameWork.Manage
{
    public partial class recordDesign : System.Web.UI.Page
    {
        public eUser user;
        string sql = "";
        public string act = eParameters.Request("act");
        public string RecordID = eParameters.QueryString("RecordID");
        public dynamic record = new eViewObject();

        private DataRow _record;
        public DataRow Record
        {
            get
            {
                if (_record == null)
                {
                   
                    DataTable dt = eBase.DataBase.getDataTable("select * from a_eke_sysDataRecords where RecordID='" + RecordID + "'");
                    if (dt.Rows.Count > 0) _record = dt.Rows[0];
                }
                return _record;
            }
        }
        private eDataBase _database;
        public eDataBase DataBase
        {
            get
            {
                if (_database == null)
                {
                    if (Record["DataSourceID"].ToString().Length > 0)
                    {
                        _database = new eDataBase(Record);
                    }
                    else
                    {
                        _database = eConfig.DefaultDataBase;
                    }
                }
                return _database;
            }
        }

        private string _tableviews;
        public string TableViews
        {
            get
            {
                if (_tableviews == null)
                {

                    string CacheName = "TableViewsJson" + Record["DataSourceID"].ToString();
                    System.Web.Caching.Cache cache = HttpRuntime.Cache;
                    _tableviews = (string)cache[CacheName];
                    if (_tableviews == null)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("[");
                        DataTable dt = DataBase.getSchemaTableViews();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (i > 0) sb.Append(",");
                            sb.Append("{");
                            sb.Append("name:\"" + dt.Rows[i]["text"].ToString() + "\",");
                            sb.Append("code:\"" + dt.Rows[i]["value"].ToString() + "\",");
                            sb.Append("type:\"" + dt.Rows[i]["type"].ToString() + "\",");
                            sb.Append("fields:[");
                            /*
                            DataTable tb = eBase.DataBase.getSchemaColumns(dt.Rows[i]["value"].ToString());
                            for (int j = 0; j < tb.Rows.Count; j++)
                            {
                                if (j > 0) sb.Append(",");
                                sb.Append("{name:\"" + tb.Rows[j]["COLUMN_NAME"].ToString() + "\",type:\"" + tb.Rows[j]["DATA_TYPE"].ToString() + "\"}");
                            }
                            */

                            sb.Append("]");
                            sb.Append("}");
                        }
                        sb.Append("]");
                        _tableviews = sb.ToString();
                        cache.Insert(CacheName, _tableviews); 
                    }
                }
                return _tableviews;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser("Manage");
            string resultSql = "";
            if (act == "updatesql")
            {
                JsonData jd = JsonMapper.ToObject("{\"success\":1,\"errcode\":\"0\",\"message\":\"保存成功!\"}");
                string sql = eParameters.Form("sql");
                eBase.DataBase.Execute("update a_eke_sysDataRecords set resultSql='" + sql.Replace("'", "''") + "' where RecordID='" + RecordID + "'");
                record = eBase.DataBase.getValues("select * from a_eke_sysDataRecords where RecordID='" + RecordID + "'");
                jd["tempSql"] = record.tempSql;
                jd["resultSql"] = record.resultSql;
                resultSql = record.resultSql.Length > 0 ? record.resultSql : record.tempSql;
                if (resultSql.Length > 0)
                {
                    if (!resultSql.ToLower().Contains(" top ")) resultSql = Regex.Replace(resultSql, "select ", "select top 10 ", RegexOptions.IgnoreCase);
                    DataTable dt = DataBase.getDataTable(resultSql);
                    jd["resultTable"] = eBase.getTableHTML(dt);                   
                }
                eResult.WriteJson(jd);
            }
            if (act == "update")
            {
                string json = eParameters.Form("json");
                json = eBase.decode(json);
                string tempsql = eBase.getRecordDesignSql(json,DataBase.StartNameSplitChar,DataBase.EndNameSplitChar);
               // eBase.AppendLog(tempsql);
                eBase.DataBase.Execute("update a_eke_sysDataRecords set relationJson='" + json.Replace("'", "''") + "',tempSql='" + tempsql.Replace("'", "''") + "' where RecordID='" + RecordID + "'");
                //eResult.Success("成功!");

                JsonData jd = JsonMapper.ToObject("{\"success\":1,\"errcode\":\"0\",\"message\":\"保存成功!\"}");
                jd["tempSql"] = tempsql;
                record = eBase.DataBase.getValues("select * from a_eke_sysDataRecords where RecordID='" + RecordID + "'");
                resultSql = record.resultSql.Length > 0 ? record.resultSql : record.tempSql;
                if (resultSql.Length > 0)
                {
                    if (!resultSql.ToLower().Contains(" top ")) resultSql = Regex.Replace(resultSql, "select ", "select top 10 ", RegexOptions.IgnoreCase);
                    DataTable dt = DataBase.getDataTable(resultSql);
                    jd["resultTable"] = eBase.getTableHTML(dt);
                }
                eResult.WriteJson(jd);
            }
            if (act == "getdata")
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("[");
                string code = eParameters.QueryString("code");
                DataTable tb = DataBase.getSchemaColumns(code);
                if (tb.Rows.Count > 0)
                {
                    for (int j = 0; j < tb.Rows.Count; j++)
                    {
                        if (j > 0) sb.Append(",");
                        //sb.Append("{\"name\":\"" + tb.Rows[j]["COLUMN_NAME"].ToString() + "\",\"code\":\"" + tb.Rows[j]["COLUMN_NAME"].ToString() + "\",\"type\":\"" + tb.Rows[j]["DATA_TYPE"].ToString() + "\",\"show\":false,\"asname\":\"\",\"cond\":\"\",\"order\":\"\"}");
                        sb.Append("{\"name\":\"" + tb.Rows[j]["COLUMN_NAME"].ToString() + "\",\"code\":\"" + tb.Rows[j]["COLUMN_NAME"].ToString() + "\"");
                        sb.Append(",\"type\":\"" + tb.Rows[j]["DATA_TYPE"].ToString() + "\",\"show\":false,\"asname\":\"\",\"cond\":\"\",\"order\":\"\",\"group\":false,\"grouptype\":\"\"");
                        sb.Append(",\"showindex\":999,\"condindex\":999,\"orderindex\":999}");
                    }
                }
                sb.Append("]");

                eBase.WriteJson(sb.ToString());
            }
            record = eBase.DataBase.getValues("select * from a_eke_sysDataRecords where RecordID='" + RecordID + "'");
            if (record.relationJson.Length < 10) record.relationJson = "{}";
            resultSql = record.resultSql.Length > 0 ? record.resultSql : record.tempSql;
            if (resultSql.Length > 0)
            {
                if (!resultSql.ToLower().Contains(" top ")) resultSql = Regex.Replace(resultSql, "select ", "select top 10 ", RegexOptions.IgnoreCase);
                DataTable dt = DataBase.getDataTable(resultSql);             
                record.resultTable = eBase.getTableHTML(dt);
            }
        }

 
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Master == null) return;
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = "数据集管理 - " + eConfig.manageName(); 
            }
        }
    }
}