using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.HJGL.TestPackageManage
{
    public partial class AItemEndCheck : PageBase
    {
        #region 定义项
        /// 
        /// 管线
        /// 
        public string ISO_ID
        {
            get
            {
                return (string)ViewState["ISO_ID"];
            }
            set
            {
                ViewState["ISO_ID"] = value;
            }
        }
        /// 
        /// A项尾工id
        /// 
        public string EIC_ID
        {
            get
            {
                return (string)ViewState["EIC_ID"];
            }
            set
            {
                ViewState["EIC_ID"] = value;
            }
        }
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtReportDate.Text = string.Format("{0:yyyy-MM}", DateTime.Now);
                this.InitTreeMenu();
            }
        }
        #endregion
        #region 加载树装置-单位-工作区
        /// 
        /// 加载树
        /// 
        private void InitTreeMenu()
        {
            if (!string.IsNullOrEmpty(this.txtReportDate.Text.Trim()))
            {
                DateTime? startTime = Funs.GetNewDateTime(this.txtReportDate.Text.Trim());
                DateTime? endTime = startTime.HasValue ? startTime.Value.AddMonths(1) : System.DateTime.Now;
                this.tvControlItem.Nodes.Clear();
                TreeNode rootNode = new TreeNode();
                rootNode.Text = "单位-装置-月份";
                rootNode.NodeID = "0";
                rootNode.Expanded = true;
                this.tvControlItem.Nodes.Add(rootNode);
                List units = null;
                var unit = BLL.UnitService.GetUnitByUnitId(this.CurrUser.UnitId);
                if (unit == null || unit.UnitTypeId == BLL.Const.ProjectUnitType_1 || unit.UnitTypeId == BLL.Const.ProjectUnitType_3)
                {
                    if (BLL.WorkAreaService.IsSupervisor(this.CurrUser.UnitId, this.CurrUser.LoginProjectId))
                    {
                        units = (from x in Funs.DB.Base_Unit
                                 join y in Funs.DB.ProjectData_WorkArea on x.UnitId equals y.UnitId
                                 where (x.UnitId == this.CurrUser.UnitId || y.SupervisorUnitId == this.CurrUser.UnitId) && y.ProjectId == this.CurrUser.LoginProjectId
                                 select x).Distinct().ToList();
                    }
                    else
                    {
                        units = BLL.UnitService.GetUnitByProjectIdUnitTypeList(this.CurrUser.LoginProjectId, "2");
                    }
                }
                else
                {
                    units = (from x in Funs.DB.Base_Unit where x.UnitId == this.CurrUser.UnitId select x).ToList();
                }
                List testPackageLists = new List(); ///试压包
                if (!this.txtReportDate.Hidden)
                {
                    testPackageLists = (from x in Funs.DB.TP_TestPackage
                                        where x.ProjectId == this.CurrUser.LoginProjectId && x.PTP_TableDate >= startTime && x.PTP_TableDate < endTime
                                        select x).ToList();
                }
                if (units != null)
                {
                    foreach (var item in units)
                    {
                        TreeNode rootUnitNode = new TreeNode();//定义根节点
                        rootUnitNode.Text = item.UnitName;
                        rootUnitNode.NodeID = item.UnitId;
                        rootUnitNode.Expanded = true;
                        rootUnitNode.ToolTip = "施工单位";
                        rootNode.Nodes.Add(rootUnitNode);
                        var lists = testPackageLists.Where(x => x.BSU_ID == item.UnitId).ToList();
                        this.BindNodes(rootUnitNode, lists);
                    }
                }
                else
                {
                    Alert.ShowInTop("请先增加施工单位!", MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                Alert.ShowInTop("请选择试压月份!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 绑定树节点
        /// 
        ///  绑定树节点
        /// 
        /// 
        private void BindNodes(TreeNode node, List testPackageLists)
        {
            if (node.ToolTip == "施工单位")
            {
                var installId = (from x in testPackageLists select x.InstallationId).Distinct();
                if (installId.Count() > 0)
                {
                    var install = from x in Funs.DB.Project_Installation where installId.Contains(x.InstallationId) orderby x.InstallationCode select x;
                    foreach (var q in install)
                    {
                        TreeNode newNode = new TreeNode();
                        newNode.Text = q.InstallationCode + q.InstallationName;
                        newNode.NodeID = q.InstallationId + "|" + node.NodeID; ;
                        newNode.ToolTip = "装置";
                        newNode.Expanded = true;
                        node.Nodes.Add(newNode);
                        this.BindNodes(newNode, testPackageLists);
                    }
                }
            }
            else if (node.ToolTip == "装置")
            {
                string installationId = Funs.GetStrListByStr(node.NodeID, '|')[0];
                var listMonth = (from x in testPackageLists
                                 where x.InstallationId == installationId && x.BSU_ID == node.ParentNode.NodeID
                                 select string.Format("{0:yyyy-MM}", x.PTP_TableDate)).Distinct();
                foreach (var item in listMonth)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item;
                    newNode.NodeID = item + "|" + node.NodeID; ;
                    newNode.ToolTip = "月份";
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, testPackageLists);
                }
            }
            else if (node.ToolTip == "月份")
            {
                string installationId = Funs.GetStrListByStr(node.ParentNode.NodeID, '|')[0];
                var days = (from x in testPackageLists
                            where x.InstallationId == installationId && x.BSU_ID == node.ParentNode.ParentNode.NodeID
                            orderby x.PTP_TableDate descending
                            select x.PTP_TableDate).Distinct();
                foreach (var item in days)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = string.Format("{0:yyyy-MM-dd}", item);
                    newNode.NodeID = item.ToString() + "|" + node.NodeID; ;
                    newNode.ToolTip = "日期";
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, testPackageLists);
                }
            }
            else if (node.ToolTip == "日期")
            {
                string installationId = Funs.GetStrListByStr(node.ParentNode.ParentNode.NodeID, '|')[0];
                var dReports = from x in testPackageLists
                               where x.InstallationId == installationId && x.BSU_ID == node.ParentNode.ParentNode.ParentNode.NodeID
                               && x.PTP_TableDate == Funs.GetNewDateTime(node.Text)
                               orderby x.PTP_TestPackageNo descending
                               select x;
                foreach (var item in dReports)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item.PTP_TestPackageNo;
                    newNode.NodeID = item.PTP_ID;
                    newNode.ToolTip = "试压包";
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, testPackageLists);
                }
            }
            else if (node.ToolTip == "试压包")
            {
                var isoInfov = from x in Funs.DB.TP_IsoList
                               join y in Funs.DB.TP_TestPackage on x.PTP_ID equals y.PTP_ID
                               join z in Funs.DB.PW_IsoInfo on x.ISO_ID equals z.ISO_ID
                               where x.PTP_ID == node.NodeID
                               && z.ProjectId == this.CurrUser.LoginProjectId
                               orderby z.ISO_IsoNo
                               select z;
                foreach (var item in isoInfov)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item.ISO_IsoNo;
                    newNode.NodeID = item.ISO_ID;
                    newNode.EnableClickEvent = true;
                    node.Nodes.Add(newNode);
                }
            }
        }
        #endregion
        #region 查询Tree
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        #endregion
        #region 点击树节点
        /// 
        /// 点击树节点
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            this.TextIsEmpty();
            this.ISO_ID = this.tvControlItem.SelectedNodeID;
            if (!string.IsNullOrEmpty(ISO_ID))
            {
                BindGrid();
            }
        }
        #endregion
        #region 绑定数据
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            string strSql = @"SELECT aItem.EIC_ID, 
                                    aItem.ISO_ID, 
                                    aItem.EIC_CheckMan, 
                                    aItem.EIC_CheckDate, 
                                    aItem.EIC_DealMan, 
                                    aItem.EIC_DealDate, 
                                    aItem.EIC_Remark"
                         + @" FROM TP_AItemEndCheck AS aItem WHERE aItem.ISO_ID=@isoId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@isoId", this.ISO_ID));
            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 文本清空
        /// 
        ///  文本清空
        /// 
        private void TextIsEmpty()
        {
            this.EIC_ID = null;
            this.txtEIC_CheckMan.Text = string.Empty;
            this.txtEIC_CheckDate.Text = string.Empty;
            this.txtEIC_DealMan.Text = string.Empty;
            this.txtEIC_DealDate.Text = string.Empty;
            this.txtEIC_Remark.Text = string.Empty;
        }
        #endregion
        #region 增加
        /// 
        /// 增加按钮
        /// 
        /// 
        /// 
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnAdd))
            {
                TextIsEmpty();
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 保存
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnSave))
            {
                if (!String.IsNullOrEmpty(this.ISO_ID))
                {
                    Model.TP_AItemEndCheck newAItemEndCheck = new Model.TP_AItemEndCheck();
                    newAItemEndCheck.ISO_ID = this.ISO_ID;
                    newAItemEndCheck.EIC_CheckMan = this.txtEIC_CheckMan.Text.Trim();
                    newAItemEndCheck.EIC_CheckDate = Funs.GetNewDateTime(this.txtEIC_CheckDate.Text.Trim());
                    newAItemEndCheck.EIC_DealMan = this.txtEIC_DealMan.Text.Trim();
                    newAItemEndCheck.EIC_DealDate = Funs.GetNewDateTime(this.txtEIC_DealDate.Text.Trim());
                    newAItemEndCheck.EIC_Remark = this.txtEIC_Remark.Text.Trim();
                    if (!string.IsNullOrEmpty(this.EIC_ID))
                    {
                        newAItemEndCheck.EIC_ID = this.EIC_ID;
                        BLL.AItemEndCheckService.UpdateTP_AItemEndCheck(newAItemEndCheck);
                        //BLL.LogService.AddLog(this.CurrUser.UserId, "修改A项尾工检查信息");
                    }
                    else
                    {
                        BLL.AItemEndCheckService.AddTP_AItemEndCheck(newAItemEndCheck);
                        //BLL.LogService.AddLog(this.CurrUser.UserId, "添加A项尾工检查信息");
                    }
                    ShowNotify("保存成功!", MessageBoxIcon.Success);
                    BindGrid();
                }
                else
                {
                    Alert.ShowInTop("请选择管线!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnDelete))
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop("请选择一条记录!", MessageBoxIcon.Warning);
                    return;
                }
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    BLL.AItemEndCheckService.DeleteTP_AItemEndCheckByID(rowID);
                }
                BindGrid();
                TextIsEmpty();
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region Grid行点击事件
        /// 
        /// Grid行点击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowClick(object sender, GridRowClickEventArgs e)
        {
            var item = BLL.AItemEndCheckService.GetTP_AItemEndCheckByID(Grid1.SelectedRowID);
            if (item != null)
            {
                this.EIC_ID = item.EIC_ID;
                this.ISO_ID = item.ISO_ID;
                this.txtEIC_CheckMan.Text = item.EIC_CheckMan;
                this.txtEIC_CheckDate.Text = item.EIC_CheckDate.HasValue ? string.Format("{0:yyyy-MM-dd}", item.EIC_CheckDate) : "";
                this.txtEIC_DealMan.Text = item.EIC_DealMan;
                this.txtEIC_DealDate.Text = item.EIC_DealDate.HasValue ? string.Format("{0:yyyy-MM-dd}", item.EIC_DealDate) : "";
                this.txtEIC_Remark.Text = item.EIC_Remark;
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private bool GetButtonPower(string button)
        {
            return BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HJGL_AItemEndCheckMenuId, button);
        }
        #endregion
    }
}