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

namespace eFrameWork.Manage
{
    public partial class ModelItems_Columns : System.Web.UI.Page
    {
        public string act = eParameters.QueryString("act");
        #region 属性
        private string sql = "";
        private string modelid = eParameters.QueryString("modelid");
        public string ModelID
        {
            get
            {
                return modelid;
            }
        }
        private DataRow _modelinfo;
        public DataRow ModelInfo
        {
            get
            {
                if (_modelinfo == null)
                {
                    DataTable dt = DataBase.getDataTable("select * from a_eke_sysModels where ModelID='" + ModelID + "'");
                    if (dt.Rows.Count > 0) _modelinfo = dt.Rows[0];
                }
                return _modelinfo;
            }
        }
        /// <summary>
        /// 主库
        /// </summary>
        private eDataBase _database;
        private eDataBase DataBase
        {
            get
            {
                if (_database == null) _database = eOleDB.DataBase;
                return _database;
            }
        }
        /// <summary>
        /// 主库或扩展库
        /// </summary>
        private eDataBase _exdatabase;
        private eDataBase ExDataBase
        {
            get
            {
                if (_exdatabase == null)
                {
                    if (ModelInfo["DataSourceID"].ToString().Length > 0)
                    {
                        _exdatabase = new eDataBase(ModelInfo);
                    }
                    else
                    {
                        return DataBase;
                    }
                }
                return _exdatabase;
            }
        }

        private string _tablename = "";
        public string TableName
        {
            get
            {
                if (_tablename.Length == 0)
                {
                    _tablename = eOleDB.getValue("select code from a_eke_sysModels where ModelID='" + ModelID + "'");
                }
                return _tablename;
            }
        }


        private DataTable _columns;//所有列
        public DataTable Columns
        {
            get
            {
                if (_columns == null)
                {
                    _columns = ExDataBase.getSchemaColumns(TableName);

                }
                return _columns;
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
           // string pk = eOleDB.getPrimaryKey("mesData_OEEDaily");
            //eBase.Writeln(pk);
            if (eConfig.showHelp())
            {
                Response.Write("<div class=\"tips\">");
                Response.Write("<b>数据结构</b><br>项目开发期间管理数据库物理结构。<br>");
                Response.Write("<b>注</b>：项目正式运行后请谨慎使用。<br>");
                Response.Write("</div> ");
            }


            List();
            if (ModelInfo["Code"].ToString().Length > 0)
            {
                Response.Write("<div style=\"margin:6px 0px 8px 0px;\">");


                Response.Write("<input type=\"checkbox\" id=\"editdatatable\" onclick=\"editdatatable(this);\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? " checked" : "") + " /><label for=\"editdatatable\">我了解风险,启用编辑。</label><br>");

                Response.Write("&nbsp;表名：<input" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " id=\"tablename\" type=\"text\" value=\"" + ModelInfo["Code"].ToString() + "\" oldvalue=\"" + ModelInfo["Code"].ToString() + "\"  class=\"edit\" style=\"width:180px;\" onBlur=\"setModel(this,'code');\" />");
                if (eConfig.showHelp()) Response.Write(" <img src=\"images/help.gif\" align=\"absmiddle\" border=\"0\" onclick=\"showHelp(56);\" title=\"查看帮助\" alt=\"查看帮助\" style=\"cursor:pointer;margin-bottom:4px;\">");
                Response.Write("</div> ");
            }
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            LitBody.RenderControl(htw);
            LitBody.Visible = false;//不输出，要在获取后设，不然取不到内容。
            Response.Write(sw.ToString());
            sw.Close();
            Response.End();

        }
        private void List()
        {
            bool submodel = Boolean.Parse(ModelInfo["submodel"].ToString());
            string modeltype = ModelInfo["type"].ToString();
           
            StringBuilder sb = new StringBuilder();
            string ct = "";
            if (Columns.Rows.Count > 0)
            {
                ct = "0";// eOleDB.getValue("select count(*) from a_eke_sysModelItems where Custom=0 and ModelID='" + ModelID + "'");
                sb.Append("<table id=\"eDataTable_Columns\" class=\"eDataTable\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" wi3dth=\"99%\" style=\"margin-top:0px;\">\r\n");
                
                sb.Append("<colgroup>\r\n");
                sb.Append("<col width=\"75\" />\r\n");  //添加删除
                sb.Append("<col width=\"75\" />\r\n");  //选择
                sb.Append("<col width=\"170\" />\r\n"); //编码
                sb.Append("<col width=\"170\" />\r\n"); //说明
                sb.Append("<col width=\"160\" />\r\n"); //数据类型
                sb.Append("<col width=\"100\" />\r\n");  //长度
                sb.Append("<col width=\"100\" />\r\n");  //小数位
                sb.Append("<col width=\"170\" />\r\n"); //默认值
                sb.Append("<col width=\"75\" />\r\n");  //主键

                if (submodel && modeltype != "3") sb.Append("<col width=\"75\" />\r\n");  //外键
                sb.Append("<col width=\"75\" />\r\n"); //顺序

                sb.Append("</colgroup>\r\n");
                sb.Append("<thead>\r\n");
                sb.Append("<tr>\r\n");
                sb.Append("<td align=\"center\"><a title=\"添加列\" href=\"javascript:;\" style=\"margin:0px;" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : "display:none;") + "\" onclick=\"addColumnN();\"><img width=\"16\" height=\"16\" src=\"images/add.png\" border=\"0\"></a></td>\r\n");
                
                sb.Append("<td align=\"center\"><input type=\"checkbox\" onclick=\"selColumnAll(this);\" name=\"selall\" id=\"selall\" style=\"margin-right:8px;\" value=\"0\"" + (ct == "0" ? "" : " checked") + " />");
                if (eConfig.showHelp()) sb.Append("<img src=\"images/help.gif\" align=\"absmiddle\" border=\"0\" onclick=\"showHelp(57);\" title=\"查看帮助\" alt=\"查看帮助\" style=\"cursor:pointer;\">");
                sb.Append("</td>\r\n");
                sb.Append("<td>编码");
                if (eConfig.showHelp()) sb.Append(" <img src=\"images/help.gif\" align=\"absmiddle\" border=\"0\" onclick=\"showHelp(58);\" title=\"查看帮助\" alt=\"查看帮助\" style=\"cursor:pointer;margin-bottom:4px;\">");
                sb.Append("</td>\r\n");
                sb.Append("<td>说明");
                if (eConfig.showHelp()) sb.Append(" <img src=\"images/help.gif\" align=\"absmiddle\" border=\"0\" onclick=\"showHelp(59);\" title=\"查看帮助\" alt=\"查看帮助\" style=\"cursor:pointer;margin-bottom:4px;\">");
                sb.Append("</td>\r\n");
                sb.Append("<td>数据类型</td>\r\n");
                sb.Append("<td>长度</td>\r\n");
                sb.Append("<td>小数位</td>\r\n");
                sb.Append("<td>默认值");
                if (eConfig.showHelp()) sb.Append(" <img src=\"images/help.gif\" align=\"absmiddle\" border=\"0\" onclick=\"showHelp(60);\" title=\"查看帮助\" alt=\"查看帮助\" style=\"cursor:pointer;margin-bottom:4px;\">");
                sb.Append("</td>\r\n");
                sb.Append("<td>主键</td>\r\n");
                if (submodel && modeltype!="3") sb.Append("<td width=\"60\">外键</td>\r\n");
                //sb.Append("<td width=\"60\" align=\"center\">顺序</td>\r\n");
                sb.Append("<td>顺序</td>\r\n");
                sb.Append("</tr>\r\n");
                sb.Append("</thead>\r\n");
                sb.Append("<tbody eSize=\"false\" eMove=\"true\">\r\n");

                string zj = ExDataBase.getPrimaryKey(TableName);

                string syscolumns = eConfig.getAllSysColumns() + zj.ToLower() + ",";

                string foreignkey = ModelInfo["foreignkey"].ToString();
                if (foreignkey.Length == 0)
                {
                    foreignkey = DataBase.getValue("SELECT Code FROM a_eke_sysModelItems where ModelID='" + ModelInfo["ParentID"].ToString() + "' and primaryKey='1'");
                   // eBase.Writeln(foreignkey);
                }

                string codes = ",";
                #region 数据库列
                for (int i = 0; i < Columns.Rows.Count; i++)
                {

                    codes += Columns.Rows[i]["COLUMN_NAME"].ToString() + ",";
                    sb.Append("<tr" + ((i + 1) % 2 == 0 ? " class=\"alternating\" eclass=\"alternating\"" : " eclass=\"\"") + ">\r\n");
                    sb.Append("<td height=\"32\" align=\"center\">");
                    if (syscolumns.IndexOf("," + Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower() + ",") > -1)
                    {
                        sb.Append("&nbsp;");
                    }
                    else
                    {
                        //sb.Append("<a title=\"删除列\" style=\"margin:0px;" + ("sys" == "True" ? "display:none;" : "") + "\" href=\"javascript:;\" onclick=\"delColumn(this,'" + Columns.Rows[i]["code"].ToString() + "');\"><img width=\"16\" height=\"16\" src=\"images/del.png\" border=\"0\"></a>");
                        sb.Append("<a title=\"删除列\" style=\"margin:0px;" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : "display:none;") + "\" href=\"javascript:;\" onclick=\"delColumn(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "');\"><img width=\"16\" height=\"16\" src=\"images/del.png\" border=\"0\"></a>");
                    }
                    sb.Append("</td>\r\n");
                    sb.Append("<td align=\"center\">\r\n");
                    ct = DataBase.getValue("select count(*) from a_eke_sysModelItems where ModelID='" + ModelID + "' and Code='" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "' and delTag=0");

                    sb.Append("<input type=\"checkbox\" onclick=\"selColumn(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "');\" name=\"selItem\" value=\"" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "\"" + (ct == "0" ? "" : " checked") + " />\r\n");
                    sb.Append("</td>\r\n");
                    sb.Append("<td><input style=\"width:150px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " reload=\"true\" type=\"text\" oldvalue=\"" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "\" value=\"" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "\" class=\"edit\" onBlur=\"ReNameColumn(this);\" /></td>\r\n");
                    sb.Append("<td><input style=\"width:150px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " type=\"text\" oldvalue=\"" + Columns.Rows[i]["DESCRIPTION"].ToString() + "\" value=\"" + Columns.Rows[i]["DESCRIPTION"].ToString() + "\"  class=\"edit\" onBlur=\"ColumnName(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "',this.value);\" /></td>\r\n");
                    sb.Append("<td>");



                    sb.Append("<select style=\"width:150px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " reload=\"true\" oldvalue=\"" + Columns.Rows[i]["DATA_TYPE"].ToString() + "\" onChange=\"ColumnType(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "',this.value);\">\r\n");


                    if(ExDataBase.DataBaseType==eDataBaseType.SQLServer)   sb.Append("<option value=\"uniqueidentifier\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "uniqueidentifier" ? " selected=\"true\"" : "") + ">GUID(uniqueidentifier)</option>\r\n");
                    
                    
                    if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"nchar\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "char" || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "nchar" ? " selected=\"true\"" : "") + ">字符(char)</option>\r\n");
                    if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"nvarchar\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("varchar") > -1 ? " selected=\"true\"" : "") + ">文本(varchar)</option>\r\n");
                    sb.Append("<option value=\"int\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "int" ? " selected=\"true\"" : "") + ">数字(int)</option>\r\n");
                    //if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"float\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "float" ? " selected=\"true\"" : "") + ">小数(float)</option>\r\n");
                    if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"decimal\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "decimal" ? " selected=\"true\"" : "") + ">小数(decimal)</option>\r\n");
                    if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"datetime\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("date") > -1 || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "timestamp" ? " selected=\"true\"" : "") + ">时间(datetime)</option>\r\n");
                    if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"bit\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "bit" ? " selected=\"true\"" : "") + ">是/否(bit)</option>\r\n");
                    if (zj.ToLower() != Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower()) sb.Append("<option value=\"ntext\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("text") > -1 ? " selected=\"true\"" : "") + ">备注(text)</option>\r\n");
                   
                    
                    sb.Append("<select>\r\n");




                    sb.Append("</td>\r\n");
                    sb.Append("<td>");

                    if (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("char") > -1 || (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "decimal" && Columns.Rows[i]["NUMERIC_SCALE"].ToString().Length > 0))
                    {
                        if (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "decimal")
                        {
                            sb.Append("<input style=\"width:90px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " type=\"text\" oldvalue=\"" + Columns.Rows[i]["NUMERIC_PRECISION"].ToString() + "\" value=\"" + Columns.Rows[i]["NUMERIC_PRECISION"].ToString() + "\" class=\"edit\" onBlur=\"ColumnLength(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "',this.value);\" />");
                            
                        }
                        else
                        {
                            sb.Append("<input style=\"width:90px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " type=\"text\" oldvalue=\"" + Columns.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString() + "\" value=\"" + (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "nvarchar" || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "nchar" ? (Convert.ToInt32(Columns.Rows[i]["CHARACTER_MAXIMUM_LENGTH"]) / 2).ToString() : Columns.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString()) + "\" class=\"edit\" onBlur=\"ColumnLength(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "',this.value);\" />"); 
                        }
                    }
                    else
                    {
                        sb.Append(Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "nvarchar" || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "nchar" ? (Convert.ToInt32(Columns.Rows[i]["CHARACTER_MAXIMUM_LENGTH"]) / 2).ToString() : Columns.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString());
                    }
                    sb.Append("</td>\r\n");
                    sb.Append("<td>");
                    //小数位
                    if (Columns.Rows[i]["DATA_TYPE"].ToString().ToLower() == "decimal" && Columns.Rows[i]["NUMERIC_SCALE"].ToString().Length > 0)
                    {
                        sb.Append("<input style=\"width:90px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " type=\"text\" oldvalue=\"" + Columns.Rows[i]["NUMERIC_SCALE"].ToString() + "\" value=\"" + Columns.Rows[i]["NUMERIC_SCALE"].ToString() + "\" class=\"edit\" onBlur=\"ColumnScale(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "',this.value);\" />");
                    }
                    else
                    {
                        sb.Append("&nbsp;");
                    }
                    sb.Append("</td>\r\n");

                    string _default = Columns.Rows[i]["COLUMN_DEFAULT"].ToString();
                    if (_default.Length > 0)
                    {
                        if (_default.IndexOf("((") > -1)
                        {
                            //_default = _default.Substring(2, _default.Length - 4);
                        }
                        else
                        {
                            //_default = _default.Substring(1, _default.Length - 2);
                        }
                    }
                    sb.Append("<td><input style=\"width:150px;\"" + (Session["dbeditstate_" + modelid.Replace("-", "")] != null && Session["dbeditstate_" + modelid.Replace("-", "")].ToString() == "1" ? "" : " disabled=\"true\"") + " type=\"text\" oldvalue=\"" + _default + "\" value=\"" + _default + "\" class=\"edit\" onBlur=\"ColumnDefault(this,'" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "',this.value);\" /></td>\r\n");
                    sb.Append("<td align=\"center\">" + (zj.ToLower() == Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower() ? "是" : "&nbsp;") + "</td>\r\n");

                    if (submodel && modeltype != "3")
                    {
                     

                        sb.Append("<td align=\"center\">");
                        if (
                            syscolumns.IndexOf("," + Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower() + ",") > -1 
                            || ct == "0"
                            || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("bit") > -1
                            || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("text") > -1
                            || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("numeric") > -1
                            || Columns.Rows[i]["DATA_TYPE"].ToString().ToLower().IndexOf("date") > -1
                            )
                        {
                            sb.Append("&nbsp;");
                        }
                        else
                        {
                            sb.Append("<input type=\"radio\" onclick=\"setModel(this,'foreignkey');\" name=\"foreignkey\" value=\"" + Columns.Rows[i]["COLUMN_NAME"].ToString() + "\"" + (foreignkey.ToLower() == Columns.Rows[i]["COLUMN_NAME"].ToString().ToLower() ? " checked" : "") + " />\r\n");
                        }
                        sb.Append("</td>\r\n"); 
                    }
                   


                    sb.Append("<td align=\"center\" style=\"cursor:move;\" titl3e=\"鼠标按下拖动改变列位置!\">" + (i + 1).ToString() + "</td>\r\n");
                    sb.Append("</tr>\r\n");
                }
                #endregion
                #region 删除的
                sql = "select * from a_eke_sysModelItems where ModelID='" + ModelID + "' and delTag=0 and Custom=0 and '" + codes + "' not like  '%,' + Code + ',%'";
                //eBase.Writeln(sql);
                DataTable tb = DataBase.getDataTable(sql);
               // eBase.PrintDataTable(tb);
                foreach (DataRow dr in tb.Rows)
                {
                    sb.Append("<tr>\r\n");
                    sb.Append("<td height=\"32\" align=\"center\">&nbsp;</td>\r\n");

                    sb.Append("<td align=\"center\"><input type=\"checkbox\" onclick=\"selColumn(this,'" + dr["code"].ToString() + "');\" value=\"" + dr["code"].ToString() + "\" checked=\"true\" /></td>\r\n");
                    sb.Append("<td style=\"color:#ccc;\">" + dr["code"].ToString() + "</td>\r\n");
                    sb.Append("<td style=\"color:#ccc;\">" + dr["mc"].ToString() + "</td>\r\n");
                    sb.Append("<td style=\"color:#ccc;\">" + dr["type"].ToString() + "</td>\r\n");
                    sb.Append("<td>" + (dr["type"].ToString().ToLower() == "nvarchar" ? (Convert.ToInt32(dr["length"]) / 2).ToString() : dr["length"].ToString()) + "</td>\r\n");

                    sb.Append("<td>&nbsp;</td>\r\n"); //默认值
                    sb.Append("<td>&nbsp;</td>\r\n");//主键
                    if (submodel && modeltype != "3")
                    {
                        sb.Append("<td>&nbsp;</td>\r\n"); //外键
                    }
                    sb.Append("<td>&nbsp;</td>\r\n"); //顺序
                    
                    //sb.Append("<td align=\"center\" style=\"cursor:move;\" titl3e=\"鼠标按下拖动改变列位置!\">&nbsp;</td>\r\n");
                    sb.Append("</tr>\r\n");
                }
                #endregion
                sb.Append("</tbody>\r\n");
                sb.Append("</table>");
 
            }

            LitBody.Text = sb.ToString();
        }
    }
}