using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Newtonsoft.Json.Linq;

namespace FineUIPro.Web.ProjectData
{
    public partial class Installation : PageBase
    {
        #region  页面加载
        /// <summary>
        /// 页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                InitTreeMenu();
            }
        }
        #endregion

        #region 获取按钮权限
        /// <summary>
        /// 获取按钮权限
        /// </summary>
        /// <param name="button"></param>
        /// <returns></returns>
        private void GetButtonPower()
        {
            if (Request.Params["value"] == "0")
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ProjectInstallationMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnMenuAdd.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDelete.Hidden = false;
                }
            }
        }
        #endregion

        #region  加载树
        /// <summary>
        /// 加载树
        /// </summary>
        private void InitTreeMenu()
        {
            this.trProjects.Nodes.Clear();
            this.trProjects.ShowBorder = false;
            this.trProjects.ShowHeader = false;
            this.trProjects.EnableIcons = true;
            this.trProjects.AutoScroll = true;
            this.trProjects.EnableSingleClickExpand = true;
            Model.Base_Project project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            if (project != null)
            {
                TreeNode node = new TreeNode();
                node.Text = project.ProjectName;
                node.NodeID = project.ProjectId;
                node.CommandName = "project";
                node.EnableClickEvent = true;
                node.EnableExpandEvent = true;
                this.trProjects.Nodes.Add(node);
                TreeNode emptyNode = new TreeNode();
                emptyNode.Text = "";
                emptyNode.NodeID = "";
                node.Nodes.Add(emptyNode);
            }
        }
        #endregion

        #region  展开树
        /// <summary>
        /// 展开树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void trProjects_NodeExpand(object sender, TreeNodeEventArgs e)
        {
            e.Node.Nodes.Clear();
            if (e.Node.CommandName == "project")  //展开项目节点
            {
                var installations = from x in Funs.DB.Project_Installation
                                    where x.ProjectId == e.Node.NodeID && x.SuperInstallationId == "0"
                                    orderby x.InstallationCode
                                    select x;
                foreach (var installation in installations)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = installation.InstallationName;
                    newNode.NodeID = installation.InstallationId;
                    newNode.CommandName = "installation";
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    e.Node.Nodes.Add(newNode);
                    var installation2s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == installation.InstallationId orderby x.InstallationCode select x;
                    if (installation2s.Count() > 0)
                    {
                        TreeNode emptyNode = new TreeNode();
                        emptyNode.Text = "";
                        emptyNode.NodeID = "";
                        newNode.Nodes.Add(emptyNode);
                    }
                }
            }
            else if (e.Node.CommandName == "installation")  //展开装置/单元节点
            {
                var installations = from x in Funs.DB.Project_Installation
                                    where x.SuperInstallationId == e.Node.NodeID
                                    orderby x.InstallationCode
                                    select x;
                foreach (var installation in installations)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = installation.InstallationName;
                    newNode.NodeID = installation.InstallationId;
                    newNode.CommandName = "installation";
                    newNode.EnableExpandEvent = true;
                    newNode.EnableClickEvent = true;
                    e.Node.Nodes.Add(newNode);
                    var installation3s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == installation.InstallationId orderby x.InstallationCode select x;
                    if (installation3s.Count() > 0)
                    {
                        TreeNode emptyNode = new TreeNode();
                        emptyNode.Text = "";
                        emptyNode.NodeID = "";
                        newNode.Nodes.Add(emptyNode);
                    }
                }
            }
        }
        #endregion

        #region  Tree点击事件
        /// <summary>
        /// Tree点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void trProjects_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            if (this.Grid1.Rows.Count > 0)
            {
                SaveData();
            }
            BindGrid();
        }
        #endregion

        #region  保存方法
        /// <summary>
        /// 保存方法
        /// </summary>
        private void SaveData()
        {
            //string rowId = this.Grid1.Rows[0].RowID;
            //string type = this.Grid1.Rows[0].Values[4].ToString();

            //if (type == "unitProject")
            //{
            //    Model.Wbs_UnitProjectInit unitProject = BLL.UnitProjectInitService.GetUnitProjectInitByUnitProjectCode(rowId);
            //    if (unitProject != null)
            //    {
            //        BLL.UnitProjectInitService.UpdateUnitProjectInit(unitProject);
            //    }
            //}
            //else if (type == "wbsSet")
            //{
            //    Model.WBS_WbsSetInit wbsSet = BLL.WbsSetInitService.GetWbsSetInitByWbsSetCode(rowId);
            //    if (wbsSet != null)
            //    {
            //        var childWbsSets = BLL.WbsSetInitService.GetWbsSetInitsBySuperWbsSetCode(this.trProjects.SelectedNodeID);
            //        //wbsSet.StartDate = Convert.ToDateTime(this.Grid1.Rows[0].Values[2].ToString());
            //        //wbsSet.EndDate = Convert.ToDateTime(this.Grid1.Rows[0].Values[3].ToString());
            //        BLL.WbsSetInitService.UpdateWbsSetInit(wbsSet);
            //    }
            //}
        }
        #endregion

        #region  修改关闭窗口
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            ShowNotify("修改成功!", MessageBoxIcon.Success);

            getWBSSet();
        }
        #endregion

        #region  拷贝关闭窗口
        /// <summary>
        /// 拷贝关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            ShowNotify("增加成功!", MessageBoxIcon.Success);

            getWBSSet();
        }
        #endregion

        #region 右键增加、修改、删除方法
        /// <summary>
        /// 右键修改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            if (this.trProjects.SelectedNode != null && this.trProjects.SelectedNode.CommandName != "project")
            {
                if (BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ProjectInstallationMenuId, BLL.Const.BtnModify))
                {
                    if (this.trProjects.SelectedNode.Text != "总图")   //非专业节点可以修改
                    {
                        this.hdSelectId.Text = this.trProjects.SelectedNode.NodeID;
                        PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("InstallationSave.aspx?operating=modify&Id={0}", this.trProjects.SelectedNode.NodeID, "编辑 - ")));
                    }
                    else
                    {
                        ShowNotify("总图节点无法修改!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("项目节点无法修改!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuAdd_Click(object sender, EventArgs e)
        {
            if (this.trProjects.SelectedNode != null)
            {
                if (BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ProjectInstallationMenuId, BLL.Const.BtnAdd))
                {
                    if (BLL.Project_InstallationService.IsCanAddInstallation(this.trProjects.SelectedNode.NodeID) && this.trProjects.SelectedNode.Text != "总图")   //可增加子级
                    {
                        string openUrl = String.Format("InstallationSave.aspx?operating=add&SuperId={0}", this.trProjects.SelectedNode.NodeID, "增加 - ");

                        PageContext.RegisterStartupScript(Window2.GetSaveStateReference(hdSelectId.ClientID)
                                + Window2.GetShowReference(openUrl));
                        //PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("WBSSetCopy.aspx?Id={0}&Type={1}", this.trProjects.SelectedNode.NodeID, this.trProjects.SelectedNode.CommandName, "拷贝 - ")));
                    }
                    else
                    {
                        ShowNotify("总图和主项节点无法增加子级!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请选择树节点!", MessageBoxIcon.Warning);
            }
        }



        /// <summary>
        /// 右键删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (this.trProjects.SelectedNode != null)
            {
                if (BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ProjectInstallationMenuId, BLL.Const.BtnDelete))
                {
                    if (this.trProjects.SelectedNode.CommandName != "project")   //非专业节点可以删除
                    {
                        string id = this.trProjects.SelectedNode.NodeID;
                        Model.Project_Installation installation = BLL.Project_InstallationService.GetInstallationByInstallationId(id);
                        if (installation.SuperInstallationId == "0")  //删除一级装置
                        {
                            if (installation.InstallationName == "总图")
                            {
                                DeleteZTData(installation.InstallationId);
                            }
                            else
                            {
                                BLL.Project_InstallationService.DeleteInstallation(id);
                                var installation2s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == id select x;
                                foreach (var installation2 in installation2s)
                                {
                                    BLL.Project_InstallationService.DeleteInstallation(installation2.InstallationId);
                                    var installation3s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == installation2.InstallationId select x;
                                    foreach (var installation3 in installation3s)
                                    {
                                        DeleteData(installation3.InstallationId);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Model.Project_Installation installation2 = BLL.Project_InstallationService.GetInstallationByInstallationId(id);
                            Model.Project_Installation installation1 = BLL.Project_InstallationService.GetInstallationByInstallationId(installation2.SuperInstallationId);
                            if (installation1.SuperInstallationId == "0")  //删除二级装置
                            {
                                BLL.Project_InstallationService.DeleteInstallation(id);
                                var installation3s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == id select x;
                                foreach (var installation3 in installation3s)
                                {
                                    DeleteData(installation3.InstallationId);
                                }
                            }
                            else    //删除二级装置
                            {
                                DeleteData(id);
                            }
                        }
                        ShowNotify("删除成功!", MessageBoxIcon.Success);
                        InitTreeMenu();
                    }
                    else
                    {
                        ShowNotify("项目节点无法删除!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请选择树节点!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        private void DeleteData(string installationId)
        {
            var wbsSets = (from x in Funs.DB.Wbs_WbsSet join y in Funs.DB.WBS_CnProfession on x.CnProfessionId equals y.CnProfessionId where y.InstallationId == installationId && x.CnProfessionId != null select x).ToList();
            foreach (var wbsSet in wbsSets)
            {
                BLL.WbsDetailHistoryService.DeleteWbsDetailHistoryByToWbs(wbsSet.WbsSetId);    //删除进度历史版本记录
                BLL.WbsDetailService.DeleteWbsDetailByToWbs(wbsSet.WbsSetId);                  //删除进度记录
                BLL.WbsSetService.DeleteWbsSet(wbsSet.WbsSetId);
            }

            //删除单位工程及子单位工程
            var unitProjects = from x in Funs.DB.Wbs_UnitProject join y in Funs.DB.WBS_CnProfession on x.CnProfessionId equals y.CnProfessionId where y.InstallationId == installationId && x.CnProfessionId != null select x;
            foreach (var unitProject in unitProjects)
            {
                BLL.WbsDetailService.DeleteWbsDetailByToWbs(unitProject.UnitProjectId);                  //删除进度记录
                BLL.UnitProjectService.DeleteUnitProject(unitProject.UnitProjectId);
            }

            //删除专业
            var cnProfessions = from x in Funs.DB.WBS_CnProfession where x.InstallationId == installationId select x;
            foreach (var cnProfession in cnProfessions)
            {
                BLL.WbsDetailService.DeleteWbsDetailByToWbs(cnProfession.CnProfessionId);                  //删除进度记录
                BLL.CnProfessionService.DeleteCnProfession(cnProfession.CnProfessionId);
            }

            BLL.WbsDetailService.DeleteWbsDetailByToWbs(installationId);                  //删除进度记录
            BLL.Project_InstallationService.DeleteInstallation(installationId);
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        private void DeleteZTData(string installationId)
        {
            var wbsSets = (from x in Funs.DB.Wbs_WbsSet where x.InstallationId == installationId && x.CnProfessionId == null select x).ToList();
            foreach (var wbsSet in wbsSets)
            {
                BLL.WbsDetailHistoryService.DeleteWbsDetailHistoryByToWbs(wbsSet.WbsSetId);    //删除进度历史版本记录
                BLL.WbsDetailService.DeleteWbsDetailByToWbs(wbsSet.WbsSetId);                  //删除进度记录
                BLL.WbsSetService.DeleteWbsSet(wbsSet.WbsSetId);
            }

            //删除单位工程及子单位工程
            var unitProjects = from x in Funs.DB.Wbs_UnitProject where x.InstallationId == installationId && x.CnProfessionId == null select x;
            foreach (var unitProject in unitProjects)
            {
                BLL.WbsDetailService.DeleteWbsDetailByToWbs(unitProject.UnitProjectId);                  //删除进度记录
                BLL.UnitProjectService.DeleteUnitProject(unitProject.UnitProjectId);
            }

            //删除专业
            //var cnProfessions = from x in Funs.DB.WBS_CnProfession where x.InstallationId == installationId select x;
            //foreach (var cnProfession in cnProfessions)
            //{
            //    BLL.WbsDetailService.DeleteWbsDetailByToWbs(cnProfession.CnProfessionId);                  //删除进度记录
            //    BLL.CnProfessionService.DeleteCnProfession(cnProfession.CnProfessionId);
            //}

            BLL.WbsDetailService.DeleteWbsDetailByToWbs(installationId);                  //删除进度记录
            BLL.Project_InstallationService.DeleteInstallation(installationId);
        }
        #endregion

        #region  保存事件
        /// <summary>
        /// 保存事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.ProjectInstallationMenuId, BLL.Const.BtnSave))
            {
                if (this.Grid1.Rows.Count > 0)
                {
                    SaveData();
                    Alert.ShowInTop("保存成功!", MessageBoxIcon.Success);
                }
                else
                {
                    Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region  绑定数据
        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_FilterChange(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        /// <summary>
        /// Grid1排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }

        /// <summary>
        /// 分页下拉选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }

        /// <summary>
        /// 加载Grid
        /// </summary>
        private void BindGrid()
        {
            List<Model.WBSSetInitItem> items = new List<Model.WBSSetInitItem>();
            if (this.trProjects.SelectedNode != null)
            {
                if (this.trProjects.SelectedNode.CommandName == "installation")
                {
                    Model.Project_Installation installation = BLL.Project_InstallationService.GetInstallationByInstallationId(this.trProjects.SelectedNode.NodeID);
                    Model.WBSSetInitItem item = new Model.WBSSetInitItem();
                    if (installation != null)
                    {
                        item.Code = installation.InstallationCode;
                        item.Name = installation.InstallationName;
                        item.StartDate = installation.StartDate;
                        item.EndDate = installation.EndDate;
                        item.Type = "installation";
                        items.Add(item);
                    }
                }
                this.Grid1.DataSource = items;
                this.Grid1.DataBind();
            }
        }
        #endregion

        #region 根据所给Id定位到对应装置
        /// <summary>
        /// 根据所给Id定位到对应装置
        /// </summary>
        private void getWBSSet()
        {
            string installationId = string.Empty;
            string pInstallationId = string.Empty;
            string ppInstallationId = string.Empty;
            string projectId = this.CurrUser.LoginProjectId;
            string id = this.hdSelectId.Text;
            Model.Project_Installation installation = BLL.Project_InstallationService.GetInstallationByInstallationId(id);
            if (installation.SuperInstallationId == "0")  //一级装置
            {
                ppInstallationId = id;
            }
            else
            {
                if (BLL.Project_InstallationService.IsCanAddInstallation(id))   //二级装置
                {
                    pInstallationId = id;
                    ppInstallationId = installation.SuperInstallationId;
                }
                else   //三级装置
                {
                    installationId = id;
                    pInstallationId = installation.SuperInstallationId;
                    Model.Project_Installation pInstallation = BLL.Project_InstallationService.GetInstallationByInstallationId(installation.SuperInstallationId);
                    if (pInstallation != null)
                    {
                        ppInstallationId = pInstallation.SuperInstallationId;
                    }
                }
            }
            //projectId = installation.ProjectId;
            this.trProjects.Nodes.Clear();
            this.trProjects.ShowBorder = false;
            this.trProjects.ShowHeader = false;
            this.trProjects.EnableIcons = true;
            this.trProjects.AutoScroll = true;
            this.trProjects.EnableSingleClickExpand = true;
            Model.Base_Project project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            if (project != null)
            {
                TreeNode node = new TreeNode();
                node.Text = project.ProjectName;
                node.NodeID = project.ProjectId;
                node.EnableClickEvent = true;
                this.trProjects.Nodes.Add(node);
                node.Expanded = true;
                var installation1s = from x in Funs.DB.Project_Installation
                                     where x.ProjectId == projectId && x.SuperInstallationId == "0"
                                     orderby x.InstallationCode
                                     select x;
                foreach (var installation1 in installation1s)
                {
                    TreeNode newNode1 = new TreeNode();
                    newNode1.Text = installation1.InstallationName;
                    newNode1.NodeID = installation1.InstallationId;
                    newNode1.CommandName = "installation";
                    newNode1.EnableExpandEvent = true;
                    newNode1.EnableClickEvent = true;
                    node.Nodes.Add(newNode1);
                    if (installation1.InstallationId == ppInstallationId)
                    {
                        newNode1.Expanded = true;
                        var installation2s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == installation1.InstallationId orderby x.InstallationCode select x;
                        foreach (var installation2 in installation2s)
                        {
                            TreeNode newNode2 = new TreeNode();
                            newNode2.Text = installation2.InstallationName;
                            newNode2.NodeID = installation2.InstallationId;
                            newNode2.CommandName = "installation";
                            newNode2.EnableExpandEvent = true;
                            newNode2.EnableClickEvent = true;
                            newNode1.Nodes.Add(newNode2);
                            if (installation2.InstallationId == pInstallationId)
                            {
                                newNode2.Expanded = true;
                                var installation3s = from x in Funs.DB.Project_Installation where x.SuperInstallationId == installation2.InstallationId orderby x.InstallationCode select x;
                                foreach (var installation3 in installation3s)
                                {
                                    TreeNode newNode3 = new TreeNode();
                                    newNode3.Text = installation3.InstallationName;
                                    newNode3.NodeID = installation3.InstallationId;
                                    newNode3.CommandName = "installation";
                                    newNode3.EnableExpandEvent = true;
                                    newNode3.EnableClickEvent = true;
                                    newNode2.Nodes.Add(newNode3);
                                }
                            }
                            else
                            {
                                if (BLL.Project_InstallationService.IsExitsInstallationsBySuperInstallationId(installation2.InstallationId))
                                {
                                    TreeNode emptyNode = new TreeNode();
                                    emptyNode.Text = "";
                                    emptyNode.NodeID = "";
                                    newNode2.Nodes.Add(emptyNode);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (BLL.Project_InstallationService.IsExitsInstallationsBySuperInstallationId(installation1.InstallationId))
                        {
                            TreeNode emptyNode = new TreeNode();
                            emptyNode.Text = "";
                            emptyNode.NodeID = "";
                            newNode1.Nodes.Add(emptyNode);
                        }
                    }
                }
            }
            this.trProjects.SelectedNodeID = this.hdSelectId.Text;
            BindGrid();
        }
        #endregion
    }
}