using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.UI.WebControls;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web.CQMS.ProcessControl
{
    public partial class ShowUnitWork : PageBase
    {
        /// 
        /// 被选择项列表
        /// 
        public List SelectedList
        {
            get
            {
                return (List)ViewState["SelectedList"];
            }
            set
            {
                ViewState["SelectedList"] = value;
            }
        }
        /// 
        /// 未被选择项列表
        /// 
        public List NoSelectedList
        {
            get
            {
                return (List)ViewState["NoSelectedList"];
            }
            set
            {
                ViewState["NoSelectedList"] = value;
            }
        }
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.SelectedList = new List();
                this.NoSelectedList = new List();
                string cnProfessionalId = Request.Params["CNPrefessionalId"];
                InitTreeMenu();
            }
        }
        /// 
        /// 加载树
        /// 
        /// 
        private void InitTreeMenu()
        {
            this.trWBS.Nodes.Clear();
            this.trWBS.ShowBorder = false;
            this.trWBS.ShowHeader = false;
            this.trWBS.EnableIcons = true;
            this.trWBS.AutoScroll = true;
            this.trWBS.EnableSingleClickExpand = true;
            var unitWorks = from x in Funs.DB.WBS_UnitWork where x.ProjectId == this.CurrUser.LoginProjectId orderby x.UnitWorkCode select x;
            foreach (var q in unitWorks)
            {
                TreeNode newNode = new TreeNode();
                newNode.Text = q.UnitWorkName;
                newNode.NodeID = q.UnitWorkId;
                newNode.CommandName = "UnitWork";
                newNode.EnableExpandEvent = true;
                newNode.EnableClickEvent = true;
                this.trWBS.Nodes.Add(newNode);
                TreeNode emptyNode = new TreeNode();
                emptyNode.Text = "";
                emptyNode.NodeID = "";
                newNode.Nodes.Add(emptyNode);
            }
        }
        #endregion
        #region  展开树
        /// 
        /// 展开树
        /// 
        /// 
        /// 
        protected void trWBS_NodeExpand(object sender, TreeNodeEventArgs e)
        {
            e.Node.Nodes.Clear();
            Model.SGGLDB db = Funs.DB;
            if (e.Node.CommandName == "UnitWork")   //展开工程类型
            {
                string cnProfessionalId = Request.Params["CNPrefessionalId"];
                var divisions = (from x in db.WBS_DivisionProject
                                 where x.CNProfessionalId == cnProfessionalId && x.ProjectId == this.CurrUser.LoginProjectId && x.SuperDivisionId == null && x.UnitWorkId == e.NodeID && x.IsSelected == true
                                 orderby x.SortIndex
                                 select x).ToList();
                Model.Base_CNProfessional cNProfessional = new Model.Base_CNProfessional();
                if (divisions.Count() == 0 && cnProfessionalId == BLL.Const.CNProfessionalCVId)
                {
                    cNProfessional = (from x in db.Base_CNProfessional where x.CNProfessionalId == BLL.Const.CNProfessionalConstructId orderby x.SortIndex select x).FirstOrDefault();
                }
                else
                {
                    cNProfessional = (from x in db.Base_CNProfessional where x.CNProfessionalId == cnProfessionalId orderby x.SortIndex select x).FirstOrDefault();
                }
                if (cNProfessional != null)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = cNProfessional.ProfessionalName;
                    newNode.NodeID = cNProfessional.CNProfessionalId + "|" + e.NodeID;
                    newNode.CommandName = "CNProfessional";
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    newNode.EnableExpandEvent = true;
                    e.Node.Nodes.Add(newNode);
                    TreeNode tempNode = new TreeNode();
                    tempNode.NodeID = "";
                    tempNode.Text = "";
                    newNode.Nodes.Add(tempNode);
                }
            }
            else if (e.Node.CommandName == "CNProfessional")   //展开专业
            {
                string unitWorkId = e.Node.ParentNode.NodeID;
                string cNProfessionalId = Request.Params["CNPrefessionalId"];
                var divisions = (from x in db.WBS_DivisionProject
                                 where x.CNProfessionalId == cNProfessionalId && x.ProjectId == this.CurrUser.LoginProjectId && x.SuperDivisionId == null && x.UnitWorkId == unitWorkId && x.IsSelected == true
                                 orderby x.SortIndex
                                 select x).ToList();
                foreach (var q in divisions)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = q.DivisionName;
                    newNode.NodeID = q.DivisionProjectId;
                    newNode.CommandName = "DivisionProject";
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    newNode.EnableExpandEvent = true;
                    e.Node.Nodes.Add(newNode);
                    var list = (from x in Funs.DB.WBS_DivisionProject
                                where x.SuperDivisionId == q.DivisionProjectId && x.ProjectId == this.CurrUser.LoginProjectId
                                 && x.IsSelected == true
                                orderby x.SortIndex
                                select x).ToList();
                    if (list.Count > 0)
                    {
                        TreeNode tempNode = new TreeNode();
                        tempNode.NodeID = "";
                        tempNode.Text = "";
                        newNode.Nodes.Add(tempNode);
                    }
                }
            }
            else if (e.Node.CommandName == "DivisionProject")   //展开分部节点
            {
                string parentId = e.NodeID;
                var childDivisions = (from x in db.WBS_DivisionProject
                                      where x.SuperDivisionId == parentId && x.ProjectId == this.CurrUser.LoginProjectId
                                      && x.IsSelected == true
                                      orderby x.SortIndex
                                      select x).ToList();
                foreach (var q in childDivisions)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = q.DivisionName;
                    newNode.NodeID = q.DivisionProjectId;
                    newNode.CommandName = "DivisionProject";
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    newNode.EnableExpandEvent = true;
                    e.Node.Nodes.Add(newNode);
                    var list = (from x in Funs.DB.WBS_DivisionProject
                                where x.SuperDivisionId == q.DivisionProjectId && x.ProjectId == this.CurrUser.LoginProjectId
                                 && x.IsSelected == true
                                orderby x.SortIndex
                                select x).ToList();
                    if (list.Count > 0)
                    {
                        TreeNode tempNode = new TreeNode();
                        tempNode.NodeID = "";
                        tempNode.Text = "";
                        newNode.Nodes.Add(tempNode);
                    }
                }
            }
        }
        #endregion
        #region 遍历节点
        /// 
        /// 遍历节点
        /// 
        /// 
        /// 
        /// 
        /// 
        private void GetNodes(TreeNodeCollection nodes, string parentId, TreeNode node, string unitWorkId,Model.SGGLDB db)
        {
            if (!string.IsNullOrEmpty(unitWorkId))
            {
                var divisions = (from x in db.WBS_DivisionProject
                                 where x.CNProfessionalId == parentId && x.ProjectId == this.CurrUser.LoginProjectId && x.SuperDivisionId == null && x.UnitWorkId == unitWorkId && x.IsSelected == true
                                 orderby x.SortIndex
                                 select x).ToList();
                foreach (var q in divisions)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = q.DivisionName;
                    newNode.NodeID = q.DivisionProjectId;
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    newNode.Expanded = true;
                    node.Nodes.Add(newNode);
                }
            }
            else
            {
                var childDivisions = (from x in db.WBS_DivisionProject
                                      where x.SuperDivisionId == parentId && x.ProjectId == this.CurrUser.LoginProjectId
                                      && x.IsSelected == true
                                      orderby x.SortIndex
                                      select x).ToList();
                foreach (var q in childDivisions)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = q.DivisionName;
                    newNode.NodeID = q.DivisionProjectId;
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    newNode.Expanded = true;
                    nodes.Add(newNode);
                }
            }
            for (int i = 0; i < nodes.Count; i++)
            {
                GetNodes(nodes[i].Nodes, nodes[i].NodeID, nodes[i], string.Empty,db);
            }
        }
        #endregion
        #region 点击树节点
        /// 
        /// 点击树节点
        /// 
        /// 
        /// 
        protected void trWBS_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            this.hdDivisionProjectId.Text = this.trWBS.SelectedNode.NodeID;
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                int i = mergedRow.Value("index");
                AspNet.CheckBox ckb = (AspNet.CheckBox)(this.Grid1.Rows[i].FindControl("cbSelect"));
                if (ckb.Checked)
                {
                    SelectedList.Add(this.Grid1.Rows[i].RowID);
                }
                else
                {
                    NoSelectedList.Add(this.Grid1.Rows[i].RowID);
                }
            }
            BindGrid();
        }
        #endregion
        #region 数据绑定
        /// 
        /// 绑定数据 
        /// 
        private void BindGrid()
        {
            string strSql = @"SELECT V.BreakdownProjectId, 
                                     V.ProjectId, 
                                     V.BreakdownCode, 
                                     V.BreakdownName, 
                                     V.DivisionProjectId, 
                                     V.Basis, 
                                     V.CheckPoints, 
                                     V.RecordAndCode, 
                                     V.Class, 
                                     V.SortIndex, 
                                     V.Remark, 
                                     V.AttachUrl, 
                                     V.IsAcceptance, 
                                     V.FenBao, 
                                     V.WuHuan, 
                                     V.JianLi, 
                                     V.YeZhu, 
                                     V.IsSelected"
                            + @" FROM View_WBS_BreakdownProject AS V "
                            + @" WHERE V.ProjectId=@ProjectId AND V.DivisionProjectId=@divisionProjectId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            listStr.Add(new SqlParameter("@divisionProjectId", this.hdDivisionProjectId.Text.Trim()));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 分页
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        /// 
        /// 下拉框分页
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion
        #region 确定
        /// 
        /// 确定按钮
        /// 
        /// 
        /// 
        protected void btnSure_Click(object sender, EventArgs e)
        {
            string ids = string.Empty;
            bool res = false;
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                int i = mergedRow.Value("index");
                AspNet.CheckBox ckb = (AspNet.CheckBox)(this.Grid1.Rows[i].FindControl("cbSelect"));
                if (ckb.Checked)
                {
                    res = true;
                    break;
                }
            }
            if (SelectedList.Count == 0 && !res)
            {
                Alert.ShowInTop("没有选中任何项!", MessageBoxIcon.Warning);
                return;
            }
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                int i = mergedRow.Value("index");
                AspNet.CheckBox ckb = (AspNet.CheckBox)(this.Grid1.Rows[i].FindControl("cbSelect"));
                if (ckb.Checked)
                {
                    SelectedList.Add(this.Grid1.Rows[i].RowID);
                }
                else
                {
                    if (SelectedList.Contains(this.Grid1.Rows[i].RowID))
                    {
                        SelectedList.Remove(this.Grid1.Rows[i].RowID);
                    }
                    NoSelectedList.Add(this.Grid1.Rows[i].RowID);
                }
            }
            foreach (var item in SelectedList.Distinct())
            {
                ids += item + ",";
            }
            if (!string.IsNullOrEmpty(ids))
            {
                ids = ids.Substring(0, ids.LastIndexOf(","));
            }
            string scripts = String.Format("F.getActiveWindow().window.reloadGrid('{0}');", ids);
            PageContext.RegisterStartupScript(scripts + ActiveWindow.GetHidePostBackReference());
            //PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(ids)
            //       + ActiveWindow.GetHidePostBackReference());
        }
        #endregion
    }
}