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 EKETEAM.FrameWork;
using EKETEAM.Data;

namespace eFrameWork.Manage
{
    public partial class ModelItems_Data : System.Web.UI.Page
    {
        private DataTable _alltables;//所有表
        public DataTable AllTables
        {
            get
            {
                if (_alltables == null)
                {
                    string sql = "SELECT id,name FROM sysobjects where (xtype='U' or xtype='V') "; //name!='dtproperties' and 
                    sql += " and (charindex('a_eke_sys',lower(name))=0 or lower(name)='a_eke_sysusers' or lower(name)='a_eke_sysroles' or lower(name)='a_eke_sysmodels')";
                    sql += " and (name not in (" + eBase.getSystemTables() + ") or  lower(name)='a_eke_sysmodels' or lower(name)='a_eke_sysroles')";

                    //sql += " and (name not in (" + eBase.getSystemTables() + ") or  lower(name)='a_eke_sysmodels' or lower(name)='a_eke_sysusers')";
                    sql += " order by name";//crdate";
                   // _alltables = DataBase.getDataTable(sql);
                    _alltables = DataBase.getSchemaTableViews();
                    //eBase.PrintDataTable(_alltables);
                    //eBase.End();

                }
                return _alltables;
            }
        }

        private eDataBase _database;
        private eDataBase DataBase
        {
            get
            {
                if (_database == null)
                {
                    if (modelrow["DataSourceID"].ToString().Length > 0)
                    {
                        _database = new eDataBase(modelrow);
                    }
                    else
                    {
                        return eOleDB.DataBase;
                    }
                }
                return _database;
            }
        }
        public string modelid = eParameters.QueryString("modelid");
        public string getJsonText(string jsonstr,string name)
        {
            StringBuilder sb = new StringBuilder();
            if (jsonstr.Length > 0)
            {
                eJson json = new eJson(jsonstr);
                foreach (eJson m in json.GetCollection())
                {
                    sb.Append("<span style=\"display:inline-block;margin-right:6px;border:1px solid #ccc;padding:3px 12px 3px 12px;\">" + HttpUtility.HtmlDecode(m.GetValue(name)) + "</span>");
                }
            }
            return sb.ToString();
        }
        DataRow modelrow;

        private DataTable _modelitems;
        public DataTable ModelItems
        {
            get
            {
                if (_modelitems == null)
                {
                    _modelitems = eOleDB.getDataTable("select * from a_eke_sysModelItems where delTag=0 and ModelID='" + modelid + "' order by px");
                }
                return _modelitems;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (eConfig.showHelp())
            {
                Response.Write("<div class=\"tips\" style=\"margin-bottom:8px;\">");
                Response.Write("<b>数据</b><br>");
                Response.Write("设置列(单选框、复选框、下拉框)的选项数据来源。<br>");
                Response.Write("</div> ");
            }
            modelrow = eOleDB.getDataTable("select * from a_eke_sysModels where ModelID='" + modelid + "'").Select()[0];

            eList datalist = new eList("a_eke_sysModelItems");
            datalist.Where.Add("ModelID='" + modelid + "' and delTag=0");
            //datalist.Where.Add("(Sys=0 or Code like '%User') and (showAdd=1 or showList=1) and (Code like '%User' or (Custom=1 or ControlType='searchselect' or ControlType='radio' or ControlType='checkbox' or ControlType='select' or ControlType='autoselect'))");//自定义列也要可以取值 Custom=0 and 
            datalist.Where.Add("(showAdd=1 or showList=1 or showExport=1)");
            datalist.OrderBy.Add("px");
            //Rep.ItemDataBound += new RepeaterItemEventHandler(Rep_ItemDataBound);
            //datalist.Bind(Rep);

            Rep.ItemDataBound += new RepeaterItemEventHandler(Rep_ItemDataBound);
            Rep.DataSource = ModelItems.Select("", "showAdd=1 or showList=1 or showExport=1", "px");
            Rep.DataBind();

            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            Rep.RenderControl(htw);
            Rep.Visible = false;//不输出，要在获取后设，不然取不到内容。
            Response.Write(sw.ToString());
            Response.End();
        }
        protected void Rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string sql = "";
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
               
                Control ctrl = e.Item.Controls[0];
                Literal lit = (Literal)ctrl.FindControl("LitObjects");
                if (lit != null)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < AllTables.Rows.Count; i++)
                    {
                        sb.Append("<option value=\"" + AllTables.Rows[i]["value"].ToString() + "\"" + (DataBinder.Eval(e.Item.DataItem, "BindObject").ToString().ToLower() == AllTables.Rows[i]["value"].ToString().ToLower() ? " selected=\"true\"" : "") + " title=\"" + AllTables.Rows[i]["text"].ToString() + "\">" + AllTables.Rows[i]["text"].ToString() + "</option>\r\n");
                    }
                    lit.Text = sb.ToString();

                    if (DataBinder.Eval(e.Item.DataItem, "BindObject").ToString().Length > 0)
                    {
                        lit = (Literal)ctrl.FindControl("LitValue");
                        if (lit != null)
                        {
                            //绑定表-列
                            DataTable cols = DataBase.getSchemaColumns(DataBinder.Eval(e.Item.DataItem, "BindObject").ToString());

                            sql = "select b.name from sysobjects a inner join  syscolumns b on a.id=b.id where a.name='" + DataBinder.Eval(e.Item.DataItem, "BindObject").ToString() + "' order by b.colid";//b.colid";
                            //lit.Text = DataBase.getOptions(sql, "name", "name", DataBinder.Eval(e.Item.DataItem, "BindValue").ToString());
                            lit.Text = cols.toOptions("COLUMN_NAME", "COLUMN_NAME", DataBinder.Eval(e.Item.DataItem, "BindValue").ToString());

                            lit = (Literal)ctrl.FindControl("LitText");
                            if (lit != null)
                            {
                                //lit.Text = DataBase.getOptions(sql, "name", "name", DataBinder.Eval(e.Item.DataItem, "BindText").ToString());
                                lit.Text = cols.toOptions("COLUMN_NAME", "COLUMN_NAME", DataBinder.Eval(e.Item.DataItem, "BindText").ToString());
                            }

                            #region 外键
                            lit = (Literal)ctrl.FindControl("LitBindForeignKey");
                            if (lit != null)
                            {
                                string bindfk = DataBinder.Eval(e.Item.DataItem, "BindForeignKey").ToString();
                                if (bindfk.Length == 0) bindfk = "ParentID";
                                sql = "select b.name from sysobjects a inner join  syscolumns b on a.id=b.id ";
                                sql += " inner join systypes c on b.xtype=c.xusertype ";
                                sql+=" where a.name='" + DataBinder.Eval(e.Item.DataItem, "BindObject").ToString() + "'";
                                sql += " and b.name not in ('addtime','adduser','edittime','edituser','deltime','deluser','deltag','" + DataBinder.Eval(e.Item.DataItem, "BindValue").ToString() + "')";
                                sql += " and (charindex('int',c.name)>0 or charindex('varchar',c.name)>0 or charindex('uniqueidentifier',c.name)>0) ";
                                sql +=" order by b.colid";
                                //lit.Text = DataBase.getOptions(sql, "name", "name", bindfk);
                                //eBase.PrintDataTable(DataBase.getDataTable(sql));
                                //eBase.PrintDataTable(cols);
                                lit.Text += cols.Select("", "DATA_TYPE in ('int','uniqueidentifier','char','nchar','varchar','nvarchar') and COLUMN_NAME not in ('addtime','adduser','edittime','edituser','deltime','deluser','deltag','" + DataBinder.Eval(e.Item.DataItem, "BindValue").ToString() + "')", "ORDINAL_POSITION").toOptions("COLUMN_NAME", "COLUMN_NAME", bindfk);
                            }
                            #endregion
                        }
                    }
                }
                lit = (Literal)ctrl.FindControl("Litcolumns");
                if (lit != null)
                {
                    sql = "SELECT ModelItemID,MC FROM a_eke_sysModelItems ";
                    sql += " where ModelID='" + DataBinder.Eval(e.Item.DataItem, "ModelID").ToString() + "' and len(BindObject)>0 ";
                    sql += " and ModelItemID<>'" + DataBinder.Eval(e.Item.DataItem, "ModelItemID").ToString() + "' ";
                    sql += " and ControlType in ('select','radio','checkbox') ";
                    //lit.Text = eOleDB.getOptions(sql, "mc", "ModelItemID", DataBinder.Eval(e.Item.DataItem, "FillItem").ToString());
                    lit.Text = ModelItems.Select("", "len(Convert(BindObject, 'System.String'))>0 and Convert(ModelItemID, 'System.String')<>'" + DataBinder.Eval(e.Item.DataItem, "ModelItemID").ToString() + "' and ControlType in ('select','radio','checkbox')", "").toOptions("ModelItemID", "MC", DataBinder.Eval(e.Item.DataItem, "FillItem").ToString());
                }

            }
        }
    }
}