using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

namespace MYAPP.Manage.Project.Design.MProject
{
    public partial class AD_MProject : MyApp.Web.UI.UserPage
    {
        public string _Tour_ID = "";
        public string _LocalName = "";
        public string _XPath = "";
        public int _ROW = 0;
        int item = 0;
        DataTable dt;
        DataTable dt_group;
        XmlDocument xmldoc, xmldocconfig;
        int count = 0;
        int _page = 0;
        DataSet myds = new DataSet();

        override protected void AppInit()//程序基本信息初始化
        {
            try
            {
                _Tour_ID = Request.QueryString["Tour_ID"].Trim();
                _ROW = Convert.ToInt32(Request.QueryString["ROW"].Trim());
                _LocalName = Request.QueryString["LocalName"];
            }
            catch (Exception ex)
            {
                ButPost.Enabled = false;
                ClientScript.RegisterStartupScript(this.GetType(), "refresh", "<script language=javascript>alert('错误!!!');history.back()</script>");
                return;
            }
            try
            {
                _page = Convert.ToInt32(Request.QueryString["Page"]);
            }
            catch
            {
                _page = 0;
            }

            if ((Request.QueryString["XPath"] != null) && (Request.QueryString["XPath"].Trim() != ""))
            {
                _XPath = Request.QueryString["XPath"];
            }
            if (_XPath.Trim() == "")
            {
                _XPath = _LocalName;
            }
            base.AppInit();
        }


        override protected void DataInit()//数据初始化
        {

        }

        protected override void pl_register_script()
        {
            base.pl_register_script();
        }


        protected void Page_Init(object sender, EventArgs e)
        {
            #region --配置验证
            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(MyApp.Components.KRPano.Project.Project_Name_Config(_Tour_ID))))
            {

            }
            else
            {
                Response.Write("请先导入配置文件!!");
                Response.End();
            }
            #endregion

            //配置文件路径
            xmldocconfig = MyApp.Components.XML.XmlDocument.Load(MyApp.Components.KRPano.Project.Project_Name_Config(_Tour_ID));

            XmlElement xle = (XmlElement)xmldocconfig.SelectSingleNode(_XPath);

            #region --获取分页信息

            int pageitems = 18;
            try
            {
               pageitems = Convert.ToInt32(xle.GetAttribute("pageitems"));
            }
            catch
            {
                pageitems = 16;
            }


            if (_page > 1)
                _ROW = (_page - 1) * pageitems + _ROW;

            if (_ROW > 0)
            {
                item = _ROW - 1;
            }
            #endregion 

            dt = new DataTable("item");

            #region --填充item 列
            dt.Columns.Add("row", System.Type.GetType("System.Int32"));
            dt.Columns.Add("name", System.Type.GetType("System.String"));
            dt.Columns.Add("viewname", System.Type.GetType("System.String"));
            dt.Columns.Add("type", System.Type.GetType("System.String"));
            dt.Columns.Add("identity", System.Type.GetType("System.String"));
            dt.Columns.Add("key", System.Type.GetType("System.String"));
            dt.Columns.Add("pkey", System.Type.GetType("System.String"));
            dt.Columns.Add("pkeyxpath", System.Type.GetType("System.String"));
            dt.Columns.Add("PkeyText", System.Type.GetType("System.String"));
            dt.Columns.Add("PkeyValue", System.Type.GetType("System.String"));
            dt.Columns.Add("width", System.Type.GetType("System.String"));
            dt.Columns.Add("height", System.Type.GetType("System.String"));
            dt.Columns.Add("value", System.Type.GetType("System.String"));
            dt.Columns.Add("Isnull", System.Type.GetType("System.String"));
            dt.Columns.Add("recursion", System.Type.GetType("System.String"));
            dt.Columns.Add("validateenable", System.Type.GetType("System.String"));
            dt.Columns.Add("validateview", System.Type.GetType("System.String"));
            dt.Columns.Add("validatetext", System.Type.GetType("System.String"));
            dt.Columns.Add("datatype", System.Type.GetType("System.String"));
            dt.Columns.Add("datalength", System.Type.GetType("System.String"));
            dt.Columns.Add("dateintro", System.Type.GetType("System.String"));
            dt.Columns.Add("AutoPostBack", System.Type.GetType("System.String"));
            dt.Columns.Add("groupid", System.Type.GetType("System.String"));
            #endregion 

            dt_group = new DataTable("group");
            #region --补充group 列
            dt_group.Columns.Add("id", System.Type.GetType("System.String"));
            dt_group.Columns.Add("name", System.Type.GetType("System.String"));
            dt_group.Columns.Add("enable", System.Type.GetType("System.String"));
            dt_group.Columns.Add("sort", System.Type.GetType("System.String"));
            dt_group.Columns.Add("memo", System.Type.GetType("System.String"));
            #endregion 

            xmldoc = MyApp.Components.XML.XmlDocument.Load(MyApp.Components.KRPano.Project.Get_Project_Name(_Tour_ID));

            XmlNodeList xmlnodelist = xmldocconfig.SelectNodes("/Project/Group/item[@xpath='"+ @_XPath+"']");

            #region --填充group表
            DataRow dr_group = null;

            int cmums = xmlnodelist.Count;
            if (xmlnodelist.Count == 0)
            {
                dr_group = dt_group.NewRow();
                dr_group["id"] = "0";
                dr_group["name"] = "基本信息";
                dr_group["enable"] = "true";
                dr_group["sort"] = "0";
                dr_group["memo"] = "基本信息";
                dt_group.Rows.Add(dr_group);
            }
            else
            {
                foreach (XmlNode xnode in xmlnodelist)
                {
                    XmlElement xle_config = (XmlElement)xnode;
                    dr_group = dt_group.NewRow();
                    dr_group["id"] = xle_config.GetAttribute("id");
                    dr_group["name"] = xle_config.GetAttribute("name");
                    dr_group["enable"] = xle_config.GetAttribute("enab");
                    dr_group["sort"] = xle_config.GetAttribute("sort");
                    dr_group["memo"] = xle_config.GetAttribute("memo");
                    dt_group.Rows.Add(dr_group);
                }
            }
            #endregion 
           
            myds.Tables.Add(dt_group);

            XmlElement elem_item = (XmlElement)xmldoc.SelectNodes(_XPath)[item];

            #region --填充item表
            DataRow dr;
            for (int i = 0; i < xle.ChildNodes.Count; i++)
            {
                if (xle.ChildNodes[i].LocalName == "Attribute")
                {
                    XmlElement xle_cf = (XmlElement)xle.ChildNodes[i];
                    dr = dt.NewRow();

                    dr["row"] = i;
                    dr["name"] = xle_cf.GetAttribute("name");
                    if (xle_cf.GetAttribute("viewname").ToString().Trim() != "")
                    {
                        dr["viewname"] = xle_cf.GetAttribute("viewname");
                    }
                    else
                    {
                        dr["viewname"] = dr["name"];
                    }
                    dr["type"] = xle_cf.GetAttribute("type");
                    dr["identity"] = xle_cf.GetAttribute("identity");
                    dr["key"] = xle_cf.GetAttribute("key");
                    dr["pkey"] = xle_cf.GetAttribute("pkey");
                    dr["pkeyxpath"] = xle_cf.GetAttribute("pkeyxpath");
                    dr["PkeyText"] = xle_cf.GetAttribute("PkeyText");
                    dr["PkeyValue"] = xle_cf.GetAttribute("PkeyValue");
                    dr["width"] = xle_cf.GetAttribute("width");
                    dr["height"] = xle_cf.GetAttribute("height");
                    dr["value"] = xle_cf.GetAttribute("value");
                    dr["Isnull"] = xle_cf.GetAttribute("Isnull");
                    dr["recursion"] = xle_cf.GetAttribute("recursion");
                    dr["validateenable"] = xle_cf.GetAttribute("validateenable");
                    dr["validateview"] = xle_cf.GetAttribute("validateview");
                    dr["validatetext"] = xle_cf.GetAttribute("validatetext");
                    dr["datatype"] = xle_cf.GetAttribute("datatype");
                    dr["datalength"] = xle_cf.GetAttribute("datalength");
                    dr["dateintro"] = xle_cf.GetAttribute("dateintro");
                    dr["AutoPostBack"] = xle_cf.GetAttribute("AutoPostBack");

                    if (cmums == 0)
                    {
                        dr["groupid"] = "0";
                    }
                    else
                    {
                        if (xle_cf.GetAttribute("groupid").Trim() != "")
                        {
                            dr["groupid"] = xle_cf.GetAttribute("groupid");
                        }
                        else
                        {
                            dr["groupid"] = "1";
                        }
                    }

                    if (action == "edit")
                    {
                        try
                        {
                            dr["value"] = elem_item.GetAttribute(xle_cf.GetAttribute("name")); //elem_item.Attributes[i].Value;
                        }
                        catch
                        { }
                    }
                    else if (action == "add")
                    {
                        if (Convert.ToString(dr["key"]) == "true")
                        {
                            int key = 0;
                            if ((Request.QueryString["key"] != null) && (Request.QueryString["key"].Trim() != ""))
                            {
                                key = Convert.ToInt32(Request.QueryString["key"]);
                            }
                            if (key > 0)
                            {
                                key++;
                                dr["value"] = key.ToString();
                            }
                        }
                    }
                    dt.Rows.Add(dr);
                }
            }
            myds.Tables.Add(dt);

            myds.Relations.Add("myReation", myds.Tables["group"].Columns["id"], myds.Tables["item"].Columns["groupid"]);

            #endregion 

            this.rp_group.DataSource = dt_group;
            this.rp_group2.DataSource = dt_group;

           
            XmlNodeList xmlnodeitemlist = xmldocconfig.SelectNodes(_XPath);

            try
            {
                Page.DataBind();
            }
            catch
            { }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        override protected void pl_del()
        {
            XmlDocument xmldoc;
            xmldoc = MyApp.Components.XML.XmlDocument.Load(MyApp.Components.KRPano.Project.Get_Project_Name(_Tour_ID));

            XmlNode xmlnode = xmldoc.SelectSingleNode(_XPath);

            XmlNodeList xmlnodelist = xmldoc.SelectNodes(_XPath);
            try
            {
                if (_ROW == -1)
                {
                    foreach (XmlElement elem_item in xmlnodelist)
                    {
                        xmlnode.RemoveChild(elem_item);
                    }
                }
                else
                {
                    if (xmlnodelist.Count >= _ROW)
                    {
                        xmlnodelist[_ROW - 1].ParentNode.RemoveChild(xmlnodelist[_ROW - 1]);
                    }
                }
                MyApp.Components.XML.XmlDocument.WriteAllText(Server.MapPath(MyApp.Components.KRPano.Project.Get_Project_Name(_Tour_ID)), xmldoc.OuterXml);
                Response.Redirect(MyApp.Components.NavUrl.GetUrl(2));
            }
            catch (Exception)
            {
                ButPost.Enabled = false;
                ClientScript.RegisterStartupScript(this.GetType(), "refresh", "<script language=javascript>alert('错误!!!');history.back()</script>");
                return;
            }
        }

        /// <summary>
        /// 生成控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HiddenField hd_item_id = (HiddenField)e.Item.FindControl("item_id");

            int item = Convert.ToInt32(hd_item_id.Value);
            DataRow dr = dt.Rows[item];

            RequiredFieldValidator refv = null;
            CompareValidator cpv = null;

            Panel pan = (Panel)e.Item.FindControl("panel1");
            Control cl = new Control();

            #region --自定义生成控件
            switch (dr["type"].ToString().Trim())
            {
                case "TextBox":
                    TextBox tb = new TextBox();
                    cl = tb;

                    tb.Text = dr["value"].ToString();

                    if (dr["datalength"].ToString().Trim() != "")
                    {
                        tb.MaxLength = Convert.ToInt32(dr["datalength"]);
                    }

                    if (dr["width"].ToString().Trim() != "")
                    {
                        tb.Width = Convert.ToInt32(dr["width"].ToString().Trim());
                    }
                    if (dr["height"].ToString().Trim() != "")
                    {
                        tb.Height = Convert.ToInt32(dr["height"].ToString().Trim());
                    }
                    break;
                case "DropDownList":
                    DropDownList dl = new DropDownList();

                    if ((dr["pkeyxpath"].ToString().Trim() != "") && (dr["pkey"].ToString().Trim() == "true"))
                    {
                        XmlNodeList xmllist = xmldoc.SelectNodes(dr["pkeyxpath"].ToString());

                        try
                        {
                            dl.Items.Clear();
                        }
                        catch { }

                        for (int i = 0; i < xmllist.Count; i++)
                        {
                            XmlElement xle = (XmlElement)xmllist[i];

                            string _name = "";
                            string _id = "";
                            string _text = "";
                            string _value = "";

                            #region --DropDownList 参数赋值

                            if (xle.GetAttribute("Name").Trim() != "")
                            {
                                _name = xle.GetAttribute("Name");
                                _text = "Name";
                            }
                            else if (xle.GetAttribute("name").Trim() != "")
                            {
                                _name = xle.GetAttribute("name");
                                _text = "name";
                            }
                            if (xle.GetAttribute("ID").Trim() != "")
                            {
                                _id = xle.GetAttribute("ID");
                                _value = "ID";
                            }
                            else if (xle.GetAttribute("id").Trim() != "")
                            {
                                _id = xle.GetAttribute("id");
                                _value = "id";
                            }
                            if (dr["PkeyText"].ToString().Trim() != "")
                            {
                                _name = xle.GetAttribute(dr["PkeyText"].ToString().Trim());
                                _text = dr["PkeyText"].ToString().Trim();
                            }
                            if (dr["PkeyValue"].ToString().Trim() != "")
                            {
                                _id = xle.GetAttribute(dr["PkeyValue"].ToString().Trim());
                                _value = dr["PkeyValue"].ToString().Trim();
                            }
                            #endregion 

                            dl.Items.Add(new ListItem(_name, _id));

                            if (Convert.ToString(dr["recursion"]) == "true")
                            {
                                DropDownListBind(dl, "　", xle, _text, _value);
                            }
                        }
                    }

                    if (dr["value"].ToString().Trim() != "")
                    {
                        try
                        {
                            dl.SelectedValue = dr["value"].ToString().Trim();
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.ToString());
                        }
                    }
                    if (dr["width"].ToString().Trim() != "")
                    {
                        dl.Width = Convert.ToInt32(dr["width"].ToString().Trim());
                    }
                    if (dr["height"].ToString().Trim() != "")
                    {
                        dl.Height = Convert.ToInt32(dr["height"].ToString().Trim());
                    }
                    cl = dl;
                    break;
                case "CheckBox":
                    CheckBox cb = new CheckBox();
                    cb.Text = dr["value"].ToString().Trim();

                    cl = cb;
                    break;
                default:
                    TextBox tb1 = new TextBox();
                    tb1.Text = dr["value"].ToString().Trim();
                    cl = tb1;
                    break;
            }
            cl.ID = "cl_" + dr["name"].ToString();
            if (dr["identity"].ToString().Trim() == "1")
            {

            }

            #region --主键or非空字段
            if (dr["key"].ToString().Trim() == "true")
            {
                refv = new RequiredFieldValidator();
                refv.ID = "refv_" + count.ToString();
                refv.ErrorMessage = "主键不能为空";

                refv.Text = "*";
                refv.ForeColor = System.Drawing.Color.Red;
                refv.ControlToValidate = cl.ID;

                if (action == "edit")
                {
                    if (cl.GetType().Name == "TextBox")
                    {
                        TextBox tb = (TextBox)cl;
                        tb.ReadOnly = true;
                    }
                }
            }
            else if (dr["Isnull"].ToString().Trim() == "false")
            {
                refv = new RequiredFieldValidator();
                refv.ID = "refv_" + count.ToString();
                refv.ErrorMessage = dr["name"].ToString() + "不能为空";
                refv.Text = "*";
                refv.ForeColor = System.Drawing.Color.Red;
                refv.ControlToValidate = cl.ID;
            }
            #endregion 

            #region --字段类型验证
            if (dr["validateenable"].ToString().Trim() == "true")
            {
                cpv = new CompareValidator();
                cpv.ID = "cpv_" + count.ToString();
                cpv.Text = dr["validateview"].ToString().Trim();
                cpv.ErrorMessage = dr["validatetext"].ToString().Trim();
                cpv.Operator = ValidationCompareOperator.DataTypeCheck;

                switch (dr["datatype"].ToString().Trim())
                {
                    case "int":
                        cpv.Type = ValidationDataType.Integer;
                        break;
                    case "smalldatetime":
                        cpv.Type = ValidationDataType.Date;
                        break;
                    case "tinyint":
                        cpv.Type = ValidationDataType.Integer;
                        break;
                    case "nvarchar":
                        cpv.Type = ValidationDataType.String;
                        break;
                }
                cpv.ControlToValidate = cl.ID;
            }
            #endregion 

            pan.Controls.Add(cl);
            if (refv != null)
            {
                pan.Controls.Add(refv);
            }
            if (cpv != null)
            {
                pan.Controls.Add(cpv);
            }
            count++;
            #endregion 
        }

        /// <summary>
        /// 递归绑定
        /// </summary>
        /// <param name="dl"></param>
        /// <param name="ne"></param>
        /// <param name="xlle"></param>
        protected void DropDownListBind(DropDownList dl, string ne, XmlElement xlle)
        {
            XmlNodeList xmlnodelist = xlle.ChildNodes;
            string dr_head = "";
            for (int i = 0; i < xmlnodelist.Count; i++)
            {
                XmlElement xle = (XmlElement)xmlnodelist[i];

                if (i == xmlnodelist.Count - 1)
                {
                    dr_head = ne + "└";
                }
                else
                {
                    dr_head = ne + "├";
                }

                string _name = "";
                string _id = "";

                #region --DropDownList 参数赋值

                if (xle.GetAttribute("Name").Trim() != "")
                {
                    _name = xle.GetAttribute("Name");
                }
                else if (xle.GetAttribute("name").Trim()!="")
                {
                    _name = xle.GetAttribute("name");
                }
                if (xle.GetAttribute("ID").Trim() != "")
                {
                    _id = xle.GetAttribute("ID");
                }
                else if (xle.GetAttribute("id").Trim() != "")
                {
                    _id = xle.GetAttribute("id");
                }
                #endregion 

                dl.Items.Add(new ListItem(dr_head + _name, _id));

                #region --逐层递归
                if (xle.ChildNodes.Count > 0)
                {
                    if (i == xmlnodelist.Count - 1)
                    {
                        DropDownListBind(dl, ne + "　", xle);
                    }
                    else
                    {
                        DropDownListBind(dl, ne + "│", xle);
                    }
                }
                #endregion 
            }
        }


        /// <summary>
        /// 递归绑定
        /// </summary>
        /// <param name="dl"></param>
        /// <param name="ne"></param>
        /// <param name="xlle"></param>
        protected void DropDownListBind(DropDownList dl, string ne, XmlElement xlle,string _text,string _value)
        {
            XmlNodeList xmlnodelist = xlle.ChildNodes;
            string dr_head = "";
            for (int i = 0; i < xmlnodelist.Count; i++)
            {
                XmlElement xle = (XmlElement)xmlnodelist[i];

                if (i == xmlnodelist.Count - 1)
                {
                    dr_head = ne + "└";
                }
                else
                {
                    dr_head = ne + "├";
                }

                string _name = "";
                string _bindvalue = "";

                _name = xle.GetAttribute(_text);
                _bindvalue = xle.GetAttribute(_value);

                dl.Items.Add(new ListItem(dr_head + _name, _bindvalue));

                #region --逐层递归
                if (xle.ChildNodes.Count > 0)
                {
                    if (i == xmlnodelist.Count - 1)
                    {
                        DropDownListBind(dl, ne + "　", xle,_name,_value);
                    }
                    else
                    {
                        DropDownListBind(dl, ne + "│", xle,_name,_value);
                    }
                }
                #endregion
            }
        }


        protected void ButPost_Click(object sender, EventArgs e)
        {
            if (Page.Visible)
            {
                XmlDocument xmldoc;
                xmldoc = MyApp.Components.XML.XmlDocument.Load(MyApp.Components.KRPano.Project.Get_Project_Name(_Tour_ID));

                XmlElement xle = (XmlElement)xmldoc.SelectNodes(_XPath)[item];
                XmlElement elem_item = null;

                if (action == "edit")
                {
                    elem_item = xle;//xle (XmlElement)xmldoc.SelectNodes(_XPath)[item];
                }
                if (action == "add")
                {
                    string _itemname = _XPath.Split('/')[_XPath.Split('/').Length-1];
                    elem_item = (XmlElement)xmldoc.CreateElement(_itemname);
                }

                for (int i = 0; i < this.rp_group2.Controls.Count; i++)
                {
                    if (this.rp_group2.Controls[i].Controls.Count > 0)
                    {
                        Control cl = this.rp_group2.Controls[i];
                        if((cl.ID!=null)&& (cl.ID.IndexOf("cl_") == 0))
                        {
                            #region --赋值
                            TextBox tb = new TextBox();
                            if (cl.GetType().Name == "TextBox")
                            {
                                tb = (TextBox)cl;
                                elem_item.SetAttribute(tb.ID.Replace("cl_", ""), tb.Text);
                            }
                            else if (cl.GetType().Name == "DropDownList")
                            {
                                DropDownList dl = (DropDownList)cl;
                                elem_item.SetAttribute(dl.ID.Replace("cl_", ""), dl.SelectedValue);
                            }
                            else if (cl.GetType().Name == "CheckBox")
                            {
                                CheckBox cb = (CheckBox)cl;
                                elem_item.SetAttribute(cb.ID.Replace("cl_", ""), cb.Checked.ToString());
                            }
                            else if (cl.GetType().Name == "CheckBoxList")
                            {
                            }
                            #endregion 
                        }
                        FindControl(cl, ref elem_item);
                    }
                }

                if (action == "add")
                {                  
                    xle.ParentNode.AppendChild(elem_item);
                    xmldoc.Save(Server.MapPath(MyApp.Components.KRPano.Project.Get_Project_Name(_Tour_ID)));
                }
                else if (action == "edit")
                {
                    MyApp.Components.XML.XmlDocument.WriteAllText(Server.MapPath(MyApp.Components.KRPano.Project.Get_Project_Name(_Tour_ID)), xmldoc.OuterXml);
                }

                if (Request.QueryString["ViewType"] != null)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "refresh", "<script language=javascript>alert('数据提交成功!');</script>");
                }
                else
                {
                    Response.Redirect(MyApp.Components.NavUrl.GetUrl(2));
                }
            }
        }

        private void FindControl(Control cll, ref XmlElement elem_item)
        {
            for (int i = 0; i < cll.Controls.Count; i++)
            {
                Control cl = cll.Controls[i];
                if ((cl.ID != null) && (cl.ID.IndexOf("cl_") == 0))
                {
                    #region --赋值
                    TextBox tb = new TextBox();

                    if (cl.GetType().Name == "TextBox")
                    {
                        tb = (TextBox)cl;
                        elem_item.SetAttribute(tb.ID.Replace("cl_", ""), tb.Text);
                    }
                    else if (cl.GetType().Name == "DropDownList")
                    {
                        DropDownList dl = (DropDownList)cl;
                        elem_item.SetAttribute(dl.ID.Replace("cl_", ""), dl.SelectedValue);
                    }
                    else if (cl.GetType().Name == "CheckBox")
                    {
                        CheckBox cb = (CheckBox)cl;
                        elem_item.SetAttribute(cb.ID.Replace("cl_", ""), cb.Checked.ToString());
                    }
                    else if (cl.GetType().Name == "CheckBoxList")
                    {
                        //tb = (TextBox)cl;
                    }
                    #endregion
                }
                FindControl(cl, ref elem_item);
            }
        }

    }
}