using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.WeldingProcess.TrustManage
{
    public partial class PointManage : PageBase
    {
        #region 定义变量
        /// 
        /// 批次主键
        /// 
        public string PointBatchId
        {
            get
            {
                return (string)ViewState["PointBatchId"];
            }
            set
            {
                ViewState["PointBatchId"] = value;
            }
        }
        #endregion
        #region 加载
        /// 
        /// 加载
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                this.txtJotDate.Text = DateTime.Now.Date.ToShortDateString();
                BLL.Base_DetectionTypeService.InitDetectionTypeDropDownList(drpNde, "", false, "");
                drpNde.SelectedValue = "32617d42-24cb-4390-b115-d53c9c9e2c81";  // 默认RT
                this.InitTreeMenu();//加载树
            }
        }
        #endregion
        #region 加载并展开树
        /// 
        /// 加载树
        /// 
        private void InitTreeMenu()
        {
            if (string.IsNullOrEmpty(this.txtJotDate.Text))
            {
                Alert.ShowInTop("请选择月份!", MessageBoxIcon.Warning);
            }
            this.tvControlItem.Nodes.Clear();
            List units = new List();
            Model.Project_Unit pUnit = BLL.Project_UnitService.GetProject_UnitByProjectIdUnitId(this.CurrUser.LoginProjectId, this.CurrUser.UnitId);
            if (pUnit == null || pUnit.UnitType == BLL.Const.UnitType_1 || pUnit.UnitType == BLL.Const.UnitType_2
               || pUnit.UnitType == BLL.Const.UnitType_3 || pUnit.UnitType == BLL.Const.UnitType_4
               || pUnit.UnitType == BLL.Const.UnitType_6)
            {
                units = (from x in Funs.DB.Base_Unit
                         join y in Funs.DB.Project_Unit on x.UnitId equals y.UnitId
                         where y.ProjectId == this.CurrUser.LoginProjectId && y.UnitType.Contains(BLL.Const.UnitType_5)
                         select x).ToList();
            }
            else
            {
                Model.Base_Unit unit = BLL.Base_UnitService.GetUnit(this.CurrUser.UnitId);
                if (unit != null)
                {
                    units.Add(unit);
                }
            }
            foreach (var unit in units)
            {
                TreeNode newNode = new TreeNode();//定义根节点
                newNode.Text = unit.UnitName;
                newNode.NodeID = unit.UnitId;
                newNode.Expanded = true;
                newNode.ToolTip = "Unit";
                this.tvControlItem.Nodes.Add(newNode);
                var install = (from x in Funs.DB.Project_Installation
                               join y in Funs.DB.Batch_PointBatch on x.InstallationId equals y.InstallationId
                               where y.UnitId == unit.UnitId && x.ProjectId == this.CurrUser.LoginProjectId
                               orderby x.InstallationCode
                               select x).Distinct();
                foreach (var q in install)
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = q.InstallationName;
                    tn.NodeID = q.InstallationId.ToString() + "|" + unit.UnitId;
                    tn.ToolTip = "Installation";
                    // 按管线查询能展开
                    if (!string.IsNullOrEmpty(this.txtPipeCode.Text))
                    {
                        tn.Expanded = true;
                        newNode.Nodes.Add(tn);
                        var pointManages = (from x in Funs.DB.View_Batch_PointBatch
                                           where x.ProjectId == this.CurrUser.LoginProjectId
                                           && x.InstallationId == q.InstallationId
                                           && x.UnitId == tn.ParentNode.NodeID
                                           && x.DetectionTypeId == drpNde.SelectedValue
                                           && x.PipelineCode.Contains(this.txtPipeCode.Text.Trim())
                                           select x).ToList();
                        if (this.drpTrust.SelectedValue == "1")
                        {
                            pointManages = pointManages.Where(p => p.IsCompletedPoint == 1).ToList();
                        }
                        else if (this.drpTrust.SelectedValue == "2")
                        {
                            pointManages = pointManages.Where(p => p.IsCompletedPoint == 0).ToList();
                        }
                        if (pointManages.Count() > 0)
                        {
                            var ndeRate = (from x in pointManages select new { x.DetectionRateId, x.DetectionRateCode, x.InstallationId }).Distinct(); 
                            foreach (var item in ndeRate)
                            {
                                TreeNode tn1 = new TreeNode();
                                tn1.Text = item.DetectionRateCode;
                                tn1.NodeID = item.DetectionRateId + "|" + q.InstallationId;
                                tn1.Expanded = true;
                                tn.Nodes.Add(tn1);
                                var pointList = (pointManages.Where(x => x.DetectionRateId == item.DetectionRateId)).ToList();
                                if (pointList.Count() > 0)
                                {
                                    DateTime start = Convert.ToDateTime(this.txtJotDate.Text.Trim());
                                    string startDate = start.Year + "-" + start.Month + "-" + "01";
                                    DateTime sar = Convert.ToDateTime(startDate).AddMonths(-1);
                                    DateTime end = Convert.ToDateTime(startDate).AddMonths(1);
                                    foreach (var p in pointList)
                                    {
                                        if (!string.IsNullOrEmpty(this.txtJotDate.Text))
                                        {
                                            var pitem = from x in Funs.DB.Batch_PointBatchItem
                                                        where x.PointBatchId == p.PointBatchId && x.WeldingDate >= sar && x.WeldingDate < end
                                                        select x;
                                            if (pitem.Count() > 0)
                                            {
                                                TreeNode tn2 = new TreeNode
                                                {
                                                    NodeID = p.PointBatchId,
                                                    ToolTip = "批",
                                                    EnableClickEvent = true,
                                                };
                                                // 当天批
                                                if (string.Format("{0:yyyy-MM-dd}", p.StartDate) == string.Format("{0:yyyy-MM-dd}", System.DateTime.Now)
                                                     || string.Format("{0:yyyy-MM-dd}", p.EndDate) == string.Format("{0:yyyy-MM-dd}", System.DateTime.Now))
                                                {
                                                    tn2.Text = "" + p.PointBatchCode + "";
                                                    tn2.ToolTip = "当天批";
                                                }
                                                else
                                                {
                                                    tn2.Text = p.PointBatchCode;
                                                }
                                                tn1.Nodes.Add(tn2);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        tn.EnableExpandEvent = true;
                        newNode.Nodes.Add(tn);
                        TreeNode tn1 = new TreeNode();
                        tn1.NodeID = "temp";
                        tn1.Text = "正在加载...";
                        tn.Nodes.Add(tn1);
                    }
                }
            }
        }
        /// 
        /// 展开树
        /// 
        /// 
        /// 
        protected void tvControlItem_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
        {
            e.Node.Nodes.Clear();
            e.Node.Expanded = true;
            if (e.Node.ToolTip == "Installation")
            {
                var detectionRates = from x in Funs.DB.Base_DetectionRate
                                     orderby x.DetectionRateCode
                                     select new { x.DetectionRateId, x.DetectionRateCode };
                foreach (var item in detectionRates)
                {
                    var pointManages = from x in Funs.DB.View_Batch_PointBatch
                                       where x.ProjectId == this.CurrUser.LoginProjectId
                                       && x.InstallationId == e.NodeID.Split('|')[0]
                                       && x.UnitId == e.Node.ParentNode.NodeID
                                       && x.DetectionTypeId == drpNde.SelectedValue
                                       && x.DetectionRateId == item.DetectionRateId
                                       select x;
                    TreeNode newNode = new TreeNode();
                    if (pointManages.Count() > 0)
                    {
                        newNode.Text = item.DetectionRateCode;
                        newNode.NodeID = item.DetectionRateId + "|" + e.Node.NodeID;
                        newNode.EnableExpandEvent = true;
                        newNode.ToolTip = "检测比例";
                        e.Node.Nodes.Add(newNode);
                    }
                    TreeNode tn1 = new TreeNode
                    {
                        Text = "检测批",
                        NodeID = "检测批",
                    };
                    newNode.Nodes.Add(tn1);
                }
                #region 这一层级不要了
                //var detectionTypes = from x in Funs.DB.Base_DetectionType
                //                     orderby x.DetectionTypeCode
                //                     select new { x.DetectionTypeId, x.DetectionTypeName };
                //foreach (var item in detectionTypes)
                //{
                //    var pointManages = from x in Funs.DB.View_Batch_PointBatch
                //                       where x.ProjectId == this.CurrUser.LoginProjectId
                //                       && x.InstallationId == e.Node.NodeID.Split('|')[0]
                //                       && x.UnitId == e.Node.ParentNode.NodeID
                //                       && x.DetectionTypeId == item.DetectionTypeId
                //                       select x;
                //    TreeNode newNode = new TreeNode();
                //    if (pointManages.Count() > 0)
                //    {
                //        newNode.Text = item.DetectionTypeName;
                //        newNode.NodeID = item.DetectionTypeId + "|" + e.Node.NodeID;
                //        newNode.EnableExpandEvent = true;
                //        newNode.ToolTip = "探伤类型";
                //        e.Node.Nodes.Add(newNode);
                //    }
                //    TreeNode tn1 = new TreeNode
                //    {
                //        Text = "检测比例",
                //        NodeID = "检测比例",
                //    };
                //    newNode.Nodes.Add(tn1);
                //}
                #endregion
            }
            //if (e.Node.ToolTip == "探伤类型")
            //{
            //}
            if (e.Node.ToolTip == "检测比例")
            {
                var pointManages = from x in Funs.DB.View_Batch_PointBatch
                                   where x.ProjectId == this.CurrUser.LoginProjectId
                                   && x.DetectionRateId == e.NodeID.Split('|')[0]
                                   && x.DetectionTypeId == drpNde.SelectedValue
                                   && x.InstallationId == e.Node.ParentNode.NodeID.Split('|')[0]
                                   && x.UnitId == e.Node.ParentNode.ParentNode.NodeID
                                   select x;
                //if (!string.IsNullOrEmpty(this.txtWelderCode.Text))
                //{
                //    pointManages = pointManages.Where(x => x.WelderCode.Contains(this.txtWelderCode.Text.Trim()));
                //}
                if (!string.IsNullOrEmpty(this.txtPipeCode.Text))
                {
                    pointManages = pointManages.Where(x => x.PipelineCode.Contains(this.txtPipeCode.Text.Trim()));
                }
                //if (this.drpState.SelectedValue == "2")
                //{
                //    pointManages = pointManages.Where(p => p.EndDate == null);
                //}
                //else if (this.drpState.SelectedValue == "3")
                //{
                //    pointManages = pointManages.Where(p => p.EndDate != null);
                //}
                //if (this.drpTrust.SelectedValue == "1")
                //{
                //    pointManages = pointManages.Where(p => p.IsTrust == false || p.IsTrust == null);
                //}
                //else if (this.drpTrust.SelectedValue == "2")
                //{
                //    pointManages = pointManages.Where(p => p.IsTrust == true);
                //}
                if (this.drpTrust.SelectedValue == "1")
                {
                    pointManages = pointManages.Where(p => p.IsCompletedPoint == 1);
                }
                else if (this.drpTrust.SelectedValue == "2")
                {
                    pointManages = pointManages.Where(p => p.IsCompletedPoint == 0);
                }
                //else if (this.drpTrust.SelectedValue == "4")
                //{
                //    pointManages = pointManages.Where(p => p.IsCheck.HasValue && p.IsCheck.Value);
                //}
                DateTime start = Convert.ToDateTime(this.txtJotDate.Text.Trim());
                string startDate = start.Year + "-" + start.Month + "-" + "01";
                DateTime sar = Convert.ToDateTime(startDate).AddMonths(-1);
                DateTime end = Convert.ToDateTime(startDate).AddMonths(1);
                foreach (var item in pointManages)
                {
                    if (!string.IsNullOrEmpty(this.txtJotDate.Text))
                    {
                        var q = from x in Funs.DB.Batch_PointBatchItem
                                where x.PointBatchId == item.PointBatchId && x.WeldingDate >= sar && x.WeldingDate < end
                                select x;
                        if (q.Count() > 0)
                        {
                            TreeNode newNode = new TreeNode
                            {
                                NodeID = item.PointBatchId,
                                ToolTip = "批",
                                EnableClickEvent = true,
                            };
                            //if (BLL.Batch_PointBatchService.GetIsShowPointRepairByPointBatchId(item.PointBatchId)) ////存在返修 蓝色
                            //{
                            //    newNode.Text = "" + item.PointBatchCode + "";
                            //    newNode.ToolTip = "批中存在返修口";
                            //}
                            //else if (!item.EndDate.HasValue) ////批 没有关闭 粉色
                            //{
                            //    newNode.Text = "" + item.PointBatchCode + "";
                            //    newNode.ToolTip = "批尚未关闭";
                            //}
                            //else if (!item.IsTrust.HasValue || item.IsTrust == false) ////没有委托深黄色
                            //{
                            //    newNode.Text = "" + item.PointBatchCode + "";
                            //    newNode.ToolTip = "批未委托";
                            //}
                            // 当天批
                            if (string.Format("{0:yyyy-MM-dd}", item.StartDate) == string.Format("{0:yyyy-MM-dd}", System.DateTime.Now)
                                 || string.Format("{0:yyyy-MM-dd}", item.EndDate) == string.Format("{0:yyyy-MM-dd}", System.DateTime.Now))
                            {
                                newNode.Text = "" + item.PointBatchCode + "";
                                newNode.ToolTip = "当天批";
                            }
                            else
                            {
                                newNode.Text = item.PointBatchCode;
                            }
                            
                            e.Node.Nodes.Add(newNode);
                        }
                    }
                }
            }
        }
        #endregion
        #region 绑定树节点 暂不用
        /// 
        ///  绑定树节点
        /// 
        /// 
        private void BindNodes(TreeNode node, List pointManages)
        {
            if (node.ToolTip == "施工单位")
            {
                var install = (from x in pointManages where x.ProjectId==this.CurrUser.LoginProjectId
                               orderby x.InstallationCode
                               select new { x.InstallationId, x.InstallationName }).Distinct();
                foreach (var item in install)
                {
                    TreeNode newNode = new TreeNode
                    {
                        Text = item.InstallationName,
                        NodeID = item.InstallationId + "|" + node.NodeID,
                        ToolTip = "装置",
                    };
                    node.Nodes.Add(newNode);
                    var installPointManages = pointManages.Where(x => x.InstallationId == item.InstallationId);
                    if (installPointManages.Count() > 0)
                    {
                        this.BindNodes(newNode, installPointManages.ToList());
                    }
                }
            }
            else if (node.ToolTip == "装置")
            {
                var detectionTypes = (from x in pointManages
                                      orderby x.DetectionTypeCode
                                      select new { x.DetectionTypeId, x.DetectionTypeName }).Distinct();
                foreach (var item in detectionTypes)
                {
                    TreeNode newNode = new TreeNode
                    {
                        Text = item.DetectionTypeName,
                        NodeID = item.DetectionTypeId + "|" + node.NodeID,
                        ToolTip = "探伤类型",
                    };
                    node.Nodes.Add(newNode);
                    var detectionTypePointManages = pointManages.Where(x => x.DetectionTypeId == item.DetectionTypeId);
                    if (detectionTypePointManages.Count() > 0)
                    {
                        this.BindNodes(newNode, detectionTypePointManages.ToList());
                    }
                }
            }
            else if (node.ToolTip == "探伤类型")
            {
                var detectionRates = (from x in pointManages
                                      orderby x.DetectionRateCode
                                      select new { x.DetectionRateId, x.DetectionRateCode }).Distinct();
                foreach (var item in detectionRates)
                {
                    TreeNode newNode = new TreeNode
                    {
                        Text = item.DetectionRateCode,
                        NodeID = item.DetectionRateId + "|" + node.NodeID,
                        ToolTip = "检测比例",
                    };
                    node.Nodes.Add(newNode);
                    var detectionRatePointManages = pointManages.Where(x => x.DetectionRateId == item.DetectionRateId);
                    if (detectionRatePointManages.Count() > 0)
                    {
                        this.BindNodes(newNode, detectionRatePointManages.ToList());
                    }
                }
            }
            else if (node.ToolTip == "检测比例")
            {
                var pointManageItems = from x in pointManages
                                       orderby x.PointBatchCode
                                       select x;
                foreach (var item in pointManageItems)
                {
                    if (!string.IsNullOrEmpty(this.txtJotDate.Text))
                    {
                        DateTime start = Convert.ToDateTime(this.txtJotDate.Text.Trim());
                        string startDate = start.Year + "-" + start.Month + "-" + "01";
                        DateTime sar = Convert.ToDateTime(startDate);
                        DateTime end = sar.AddMonths(1);
                        var q = from x in Funs.DB.Batch_PointBatchItem
                                where x.PointBatchId == item.PointBatchId && x.WeldingDate >= sar && x.WeldingDate < end
                                select x;
                        if (q.Count() > 0)
                        {
                            TreeNode newNode = new TreeNode
                            {
                                NodeID = item.PointBatchId,
                                ToolTip = "批",
                                EnableClickEvent = true,
                            };
                            if (BLL.Batch_PointBatchService.GetIsShowPointRepairByPointBatchId(item.PointBatchId)) ////存在返修 蓝色
                            {
                                newNode.Text = "" + item.PointBatchCode + "";
                                newNode.ToolTip = "批中存在返修口";
                            }
                            else if (!item.EndDate.HasValue) ////批 没有关闭 粉色
                            {
                                newNode.Text = "" + item.PointBatchCode + "";
                                newNode.ToolTip = "批尚未关闭";
                            }
                            else if (!item.IsTrust.HasValue || item.IsTrust == false) ////没有委托深黄色
                            {
                                newNode.Text = "" + item.PointBatchCode + "";
                                newNode.ToolTip = "批未委托";
                            }  ////当天批
                            else if (string.Format("{0:yyyy-MM-dd}", item.StartDate) == string.Format("{0:yyyy-MM-dd}", System.DateTime.Now)
                                || string.Format("{0:yyyy-MM-dd}", item.EndDate) == string.Format("{0:yyyy-MM-dd}", System.DateTime.Now))
                            {
                                newNode.Text = "" + item.PointBatchCode + "";
                                newNode.ToolTip = "当天批";
                            }
                            else
                            {
                                newNode.Text = item.PointBatchCode;
                            }
                            node.Nodes.Add(newNode);
                        }
                     }
                }
            }
        }
        #endregion
        #region 点击TreeView
        /// 
        /// 点击TreeView
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            if (this.tvControlItem.SelectedNodeID != "0")
            {
                this.PointBatchId = tvControlItem.SelectedNodeID;
                var p = from x in Funs.DB.Batch_PointBatchItem where x.PointBatchId == PointBatchId && x.PointDate.HasValue && (x.IsBuildTrust == null || x.IsBuildTrust == false) select x;
                if (p.Count() == 0)
                {
                    var batch = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
                    // 批变为已委托状态
                    batch.IsTrust = true;
                    Funs.DB.SubmitChanges();
                }
                this.BindGrid();
                var pitem = (from x in Funs.DB.View_Batch_PointBatchItem
                            where x.PointBatchId == PointBatchId
                            select x.WelderCode).Distinct();
                if (pitem.Count() > 0)
                {
                    drpWelder.DataValueField = "WelderCode";
                    drpWelder.DataTextField = "WelderCode";
                    drpWelder.DataSource = pitem;
                    drpWelder.DataBind();
                    Funs.FineUIPleaseSelect(drpWelder);
                }
            }
        }
        #endregion
        #region 数据绑定
        #region 加载页面输入提交信息
        /// 
        /// 加载页面输入提交信息
        /// 
        private void PageInfoLoad()
        {
            this.txtStartDate.Text = string.Empty;
            this.txtEndDate.Text = string.Empty;
            this.txtState.Text = "未关闭";
            Model.Batch_PointBatch pointBatch = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
            if (pointBatch != null)
            {
                if (pointBatch.StartDate.HasValue)
                {
                    this.txtStartDate.Text = string.Format("{0:yyyy-MM-dd}", pointBatch.StartDate);
                }
                if (pointBatch.EndDate.HasValue)
                {
                    this.txtEndDate.Text = string.Format("{0:yyyy-MM-dd}", pointBatch.EndDate);
                    this.txtState.Text = "已关闭";
                }
            }
        }
        #endregion
        /// 
        /// 数据绑定
        /// 
        private void BindGrid()
        {
            this.PageInfoLoad();
            string strSql = @" SELECT PointBatchItemId,PointBatchId,WeldJointId,PointState,PointDate,RepairDate,CutDate,WorkAreaCode,
                                     WeldJointCode,JointArea,Size,WelderCode,WeldingDate,PipelineCode,PipingClassName,
                                     CONVERT(INT,dbo.Fun_GetParseInt(WeldJointCode)) AS ConvertJoint,
                                     (CASE WHEN IsWelderFirst=1 THEN '是' ELSE '否' END) AS IsWelderFirst, 
                                     (CASE WHEN IsCompletedPoint=1 THEN '已处理' ELSE '待处理' END) CompletedState,
                                     JLAudit,GLGSAudit,QTAudit,IsPointAudit,
                                     (CASE WHEN PointDate IS NOT NULL AND IsBuildTrust=1 THEN '已委托'
									  ELSE (CASE WHEN PointDate IS NOT NULL THEN '未委托' ELSE '' END) END) AS IsTrust
                              FROM dbo.View_Batch_PointBatchItem 
                              WHERE PointBatchId=@PointBatchId";
            List listStr = new List();
            if (!string.IsNullOrEmpty(PointBatchId))
            {
                listStr.Add(new SqlParameter("@PointBatchId", this.PointBatchId));
            }
            if (drpIsTrust.SelectedValue != "0")
            {
                if (drpIsTrust.SelectedValue == "1")
                {
                    strSql += " AND PointDate IS NOT NULL AND IsBuildTrust IS NULL";
                }
                else
                {
                    strSql += " AND PointDate IS NOT NULL AND IsBuildTrust IS NOT NULL";
                }
            }
            if (drpIsCompletedPoint.SelectedValue != "0")
            {
                if (drpIsCompletedPoint.SelectedValue == "1")
                {
                    strSql += " AND IsCompletedPoint = 0";
                }
                else
                {
                    strSql += " AND IsCompletedPoint = 1";
                }
            }
            if (drpWelder.SelectedValue != Const._Null && drpWelder.SelectedValue != null)
            {
                strSql += " AND WelderCode = @WelderCode";
                listStr.Add(new SqlParameter("@WelderCode", drpWelder.SelectedValue));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
           // tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
            for (int i = 0; i < this.Grid1.Rows.Count; i++)
            {
                var pointItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(this.Grid1.Rows[i].DataKeys[0].ToString());
                if (pointItem != null)
                {
                    if (pointItem.IsCheckRepair == true)
                    {
                        this.Grid1.Rows[i].CellCssClasses[6] = "colorredRed";
                    }
                    else if (pointItem.PointState != null)
                    {
                        this.Grid1.Rows[i].CellCssClasses[6] = "colorredBlue";
                        this.Grid1.Rows[i].CellCssClasses[9] = "colorredBlue";
                        
                    }
                    //string isTrust = Grid1.Rows[i].Values[1].ToString();//row["IsTrust"].ToString();
                    //int isPointAudit = Convert.ToInt32(Grid1.Rows[i].Values[18].ToString());
                    //if (isPointAudit != 1 || isTrust == "已委托")
                    //{
                    //    // 设置此列右键功能不能用
                    //    this.Grid1.Rows[i].RowSelectable= false;
                    //}
                }
            }
        }
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            DataRowView row = e.DataItem as DataRowView;
            CheckBoxField ckbIsPointAudit = Grid1.FindColumn("ckbSelect") as CheckBoxField;
            //ckbIsPointAudit.SetCheckedState(e.RowIndex, false);
            // 点口是否审核
            //bool isPointAudit = Convert.ToBoolean(row["IsPointAudit"]);
            string isTrust = row["IsTrust"].ToString();
            int isPointAudit = Convert.ToInt32(row["IsPointAudit"].ToString());
            // 未审核的或已委托的口禁用复选框
            if (isPointAudit!=1 || isTrust == "已委托")
            {
                //e.RowSelectable = false;
                e.CellCssClasses[ckbIsPointAudit.ColumnIndex] = "hidethis";
                
            }
            
        }
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string pointBatchItemId = e.RowID;
            if (e.CommandName == "JLAudit")
            {
                if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnJLAudit))
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("PointItemAudit.aspx?PointBatchItemId={0}&auditMan=JLAudit", pointBatchItemId, "点口审核 - ")));
                }
                else
                {
                    ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                    return;
                }
            }
            if (e.CommandName == "GLGSAudit")
            {
                if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnGLGSAudit))
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("PointItemAudit.aspx?PointBatchItemId={0}&auditMan=GLGSAudit", pointBatchItemId, "点口审核 - ")));
                }
                else
                {
                    ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                    return;
                }
            }
            if (e.CommandName == "QTAudit")
            {
                if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnQTAudit))
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("PointItemAudit.aspx?PointBatchItemId={0}&auditMan=QTAudit", pointBatchItemId, "点口审核 - ")));
                }
                else
                {
                    ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                    return;
                }
            }
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        protected void drpIsTrust_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #endregion
        #region 分页排序
        #region 页索引改变事件
        /// 
        /// 页索引改变事件
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 排序
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 分页选择下拉改变事件
        /// 
        /// 分页选择下拉改变事件
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        #endregion
        #endregion
        #region 关闭弹出窗口及刷新页面
        /// 
        /// 批关闭
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            this.BindGrid();
        }
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            this.BindGrid();
        }
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        #endregion
        #endregion
        #region 手动点口关闭、打开重新点口、手动结束批、重新选择扩口
        /// 
        /// 手动点口关闭
        /// 
        /// 
        /// 
        protected void btnPointAudit_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnJLAudit))
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("PointAudit.aspx",  "点口审核 - ")));
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 打开重新点口
        /// 
        /// 
        /// 
        protected void btnbtnOpenResetPoint_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnOpenResetPoint))
            {
                if (!string.IsNullOrEmpty(this.PointBatchId))
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("OpenResetPoint.aspx?PointBatchId={0}", this.PointBatchId, "重新点口 - ")));
                }
                else
                {
                    Alert.ShowInTop("请选择要重新点口的批!");
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 手动结束批(暂不用)
        /// 
        /// 
        /// 
        protected void btnbtnClear_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnClearBatch))
            {
                string info = "该批次已关闭!";
                var point = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
                if (point != null && !point.EndDate.HasValue)
                {
                    var q = Funs.DB.Batch_PointBatchItem.FirstOrDefault(x => x.PointBatchId == PointBatchId && x.PointState == "1");
                    if (q != null)
                    {
                        BLL.Batch_PointBatchService.UpdatePointBatch(PointBatchId, System.DateTime.Now);
                        this.txtEndDate.Text = point.EndDate.Value.ToShortDateString();
                        this.txtState.Text = "批关闭";
                        BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnClearBatch, this.PointBatchId);
                    }
                    else
                    {
                        info = "该批次未点口,请手动点口后再结束批!";
                    }
                }
                Alert.ShowInTop(info);
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 重新选择扩口
        /// 
        /// 
        /// 
        protected void btnSelectExpandPoint_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnSelectResetExpand))
            {
                var pointBatch = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
                if (pointBatch != null)
                {
                    var pointBatchItem = from x in Funs.DB.Batch_PointBatchItem
                                         join y in Funs.DB.Batch_BatchTrustItem on x.PointBatchItemId equals y.TrustBatchItemId
                                         join z in Funs.DB.Batch_NDEItem on y.TrustBatchItemId equals z.TrustBatchItemId
                                         where x.IsCheckRepair.Value && z.SubmitDate.HasValue
                                         select x;
                    if (pointBatchItem.Count() == 0)
                    {
                        Alert.ShowInTop("不存在返修口,无法选择扩透口!", MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("SelectExpandPoint.aspx?PointBatchId={0}", this.PointBatchId, "选择扩口 - ")));
                    }
                }
                else
                {
                    Alert.ShowInTop("请选择扩透所在的批次!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 生成
        /// 
        /// 生成
        /// 
        /// 
        /// 
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnGenerate))
            {
                if (!string.IsNullOrEmpty(this.PointBatchId))
                {
                    // 获取当前批次所有未委托口
                    var project = BLL.Base_ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
                    var batch = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
                    var getViewGenerateTrustLists = (from x in Funs.DB.View_GenerateTrust_FJ where x.ProjectId == this.CurrUser.LoginProjectId
                                                     && x.PointBatchId == this.PointBatchId
                                                     select x).ToList();
                    if (getViewGenerateTrustLists.Count() > 0 && project.ProjectArea == "3")
                    {
                        if (CurrUser.UserId == Const.GlyId)
                        {
                            GenerateTrust_FJ(getViewGenerateTrustLists);
                        }
                        else
                        {
                            Model.Project_Unit pUnit = BLL.Project_UnitService.GetProject_UnitByProjectIdUnitId(this.CurrUser.LoginProjectId, this.CurrUser.UnitId);
                            if (pUnit == null || pUnit.UnitType == BLL.Const.UnitType_1 || pUnit.UnitType == BLL.Const.UnitType_2
                               || pUnit.UnitType == BLL.Const.UnitType_3 || pUnit.UnitType == BLL.Const.UnitType_4)
                            {
                                GenerateTrust_FJ(getViewGenerateTrustLists);
                            }
                            else
                            {
                                var getUnitViewGenerateTrustLists = getViewGenerateTrustLists.Where(x => x.UnitId == this.CurrUser.UnitId);
                                if (getUnitViewGenerateTrustLists.Count() > 0)
                                {
                                    // 当前单位未委托批
                                    GenerateTrust_FJ(getUnitViewGenerateTrustLists.ToList());
                                }
                                else
                                {
                                    Alert.ShowInTop("当前批次所点焊口已全部生成委托单!", MessageBoxIcon.Warning);
                                }
                            }
                        }
                        // 批变为已委托状态
                        batch.IsTrust = true;
                        Funs.DB.SubmitChanges();
                        BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnGenerate, null);
                    }
                    else
                    {
                        Alert.ShowInTop("当前批次所点焊口已全部生成委托单!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    Alert.ShowInTop("请选择要生成委托单的批次!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 手动生成委托单
        /// 
        /// 
        /// 
        protected void btnHandGenerate_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnHandGenerate))
            {
                List selectRow = new List();
                CheckBoxField ckbSelect = Grid1.FindColumn("ckbSelect") as CheckBoxField;
                for (int i = 0; i < Grid1.Rows.Count; i++)
                {
                    bool check = ckbSelect.GetCheckedState(i);
                    if (check)
                    {
                        selectRow.Add(Grid1.DataKeys[i][0].ToString());
                    }
                }
                if (selectRow.Count() > 0)
                {
                    List weldMot = new List();
                    List grooveType = new List();
                    List IsFist = new List();
                    string error = string.Empty;
                    foreach (string pointItemId in selectRow)
                    {
                        var pointItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(pointItemId);
                        var jot = BLL.Pipeline_WeldJointService.GetWeldJointByWeldJointId(pointItem.WeldJointId);
                        weldMot.Add(jot.WeldingMethodId);
                        grooveType.Add(jot.GrooveTypeId);
                        IsFist.Add(pointItem.IsWelderFirst == true ? true : false);
                    }
                    if (weldMot.Distinct().Count() > 1)
                    {
                        error = "勾选的焊口焊接方法不一至,";
                    }
                    if (grooveType.Distinct().Count() > 1)
                    {
                        error = error + "勾选的焊口坡口类型不一至,";
                    }
                    if (IsFist.Distinct().Count() > 1)
                    {
                        error = error + "勾选的焊口是否首三不一至,";
                    }
                    if (error == string.Empty)
                    {
                        var point = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
                        var iso = BLL.Pipeline_PipelineService.GetPipelineByPipelineId(point.PipelineId);
                        var project = BLL.Base_ProjectService.GetProjectByProjectId(point.ProjectId);
                        var unit = BLL.Base_UnitService.GetUnit(point.UnitId);
                        var ndt = BLL.Base_DetectionTypeService.GetDetectionTypeByDetectionTypeId(point.DetectionTypeId);
                        var work = BLL.Project_WorkAreaService.GetProject_WorkAreaByWorkAreaId(iso.WorkAreaId);
                        Model.Batch_BatchTrust newBatchTrust = new Model.Batch_BatchTrust();
                        string perfix = string.Empty;
                        //perfix = unit.UnitCode + "-" + ins.InstallationCode + "-GD-" + ndt.DetectionTypeCode + "-";
                        perfix = ndt.DetectionTypeCode + "-" + unit.UnitCode + "-" + work.WorkAreaCode + "-PI" + "-";
                        newBatchTrust.TrustBatchCode = BLL.SQLHelper.RunProcNewId("SpGetNewCode", "dbo.Batch_BatchTrust", "TrustBatchCode", project.ProjectId, perfix);
                        string trustBatchId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrust));
                        newBatchTrust.TrustBatchId = trustBatchId;
                        newBatchTrust.TrustDate = DateTime.Now;
                        newBatchTrust.ProjectId = point.ProjectId;
                        newBatchTrust.UnitId = point.UnitId;
                        newBatchTrust.InstallationId = point.InstallationId;
                        newBatchTrust.WorkAreaId = iso.WorkAreaId;
                        newBatchTrust.WeldingMethodId = weldMot[0];
                        newBatchTrust.GrooveTypeId = grooveType[0];
                        newBatchTrust.IsWelderFirst = IsFist[0];
                        newBatchTrust.DetectionTypeId = point.DetectionTypeId;
                        newBatchTrust.PipelineId = point.PipelineId;
                        BLL.Batch_BatchTrustService.AddBatchTrust(newBatchTrust);  // 新增委托单
                        // 生成委托明细,并回写点口明细信息
                        string toPointBatch = string.Empty;
                        foreach (string pointItemId in selectRow)
                        {
                            var pointItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(pointItemId);
                            if (BLL.Batch_PointBatchService.GetIsGenerateTrust(pointItem.PointBatchItemId)) ////生成委托单的条件判断
                            {
                                if (!toPointBatch.Contains(pointItem.PointBatchId))
                                {
                                    toPointBatch = toPointBatch + pointItem.PointBatchId + ",";
                                }
                                Model.Batch_BatchTrustItem trustItem = new Model.Batch_BatchTrustItem
                                {
                                    TrustBatchItemId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrustItem)),
                                    TrustBatchId = trustBatchId,
                                    PointBatchItemId = pointItem.PointBatchItemId,
                                    WeldJointId = pointItem.WeldJointId,
                                    //FilmNum = fileNum,
                                    CreateDate = DateTime.Now
                                };
                                Batch_BatchTrustItemService.AddBatchTrustItem(trustItem);
                            }
                            //Model.Batch_PointBatchItem pointBatchItem = Funs.DB.Batch_PointBatchItem.FirstOrDefault(e => e.PointBatchItemId == item.PointBatchItemId);
                            pointItem.IsBuildTrust = true;
                            Funs.DB.SubmitChanges();
                        }
                        // 回写委托批对应点口信息
                        if (!string.IsNullOrEmpty(toPointBatch))
                        {
                            toPointBatch = toPointBatch.Substring(0, toPointBatch.Length - 1);
                            var updateTrut = BLL.Batch_BatchTrustService.GetBatchTrustById(trustBatchId);
                            if (updateTrut != null)
                            {
                                updateTrut.TopointBatch = toPointBatch;
                                BLL.Batch_BatchTrustService.UpdateBatchTrust(updateTrut);
                            }
                        }
                        Alert.ShowInTop("委托单已生成!", MessageBoxIcon.Success);
                    }
                    else
                    {
                        Alert.ShowInTop(error + "不能组成一个委托单!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    Alert.ShowInTop("请勾选要生成委托单的焊口!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 生成委托单
        /// 
        /// 
        private void GenerateTrust(List GenerateTrustLists)
        {
           
        }
        /// 
        /// 生成委托单-福建
        /// 
        /// 
        private void GenerateTrust_FJ(List GenerateTrustLists)
        {
            Model.HJGLDB db = Funs.DB;
            foreach (var trust in GenerateTrustLists)
            {
                Model.Batch_BatchTrust newBatchTrust = new Model.Batch_BatchTrust();
                var project = BLL.Base_ProjectService.GetProjectByProjectId(trust.ProjectId);
                var unit = BLL.Base_UnitService.GetUnit(trust.UnitId);
                var ndt = BLL.Base_DetectionTypeService.GetDetectionTypeByDetectionTypeId(trust.DetectionTypeId);
                var work = BLL.Project_WorkAreaService.GetProject_WorkAreaByWorkAreaId(trust.WorkAreaId);
                string perfix = string.Empty;
                //perfix = unit.UnitCode + "-" + ins.InstallationCode + "-GD-" + ndt.DetectionTypeCode + "-";
                perfix = ndt.DetectionTypeCode + "-" + unit.UnitCode + "-" + work.WorkAreaCode + "-PI" + "-";
                newBatchTrust.TrustBatchCode = BLL.SQLHelper.RunProcNewId("SpGetNewCode", "dbo.Batch_BatchTrust", "TrustBatchCode", project.ProjectId, perfix);
                string trustBatchId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrust));
                newBatchTrust.TrustBatchId = trustBatchId;
                newBatchTrust.TrustDate = DateTime.Now;
                newBatchTrust.ProjectId = trust.ProjectId;
                newBatchTrust.UnitId = trust.UnitId;
                newBatchTrust.InstallationId = trust.InstallationId;
                newBatchTrust.WorkAreaId = trust.WorkAreaId;
                newBatchTrust.WeldingMethodId = trust.WeldingMethodId;
                newBatchTrust.GrooveTypeId = trust.GrooveTypeId;
                newBatchTrust.IsWelderFirst = Convert.ToBoolean(trust.IsWelderFirst);
                newBatchTrust.DetectionTypeId = trust.DetectionTypeId;
                newBatchTrust.PipelineId = trust.PipelineId;
                BLL.Batch_BatchTrustService.AddBatchTrust(newBatchTrust);  // 新增委托单
                // 生成委托条件对比
                var generateTrustItem = from x in db.View_GenerateTrustItem_FJ
                                        where x.ProjectId == trust.ProjectId && x.InstallationId == trust.InstallationId
                                        && x.WorkAreaId == trust.WorkAreaId && x.UnitId == trust.UnitId
                                        && x.WeldingMethodId==trust.WeldingMethodId && x.GrooveTypeId==trust.GrooveTypeId
                                        && x.IsWelderFirst==trust.IsWelderFirst && x.DetectionTypeId == trust.DetectionTypeId
                                        && x.PipelineId == trust.PipelineId
                                        select x;
                string toPointBatch = string.Empty;
                // 生成委托明细,并回写点口明细信息
                foreach (var item in generateTrustItem)
                {
                    if (BLL.Batch_PointBatchService.GetIsGenerateTrust(item.PointBatchItemId)) ////生成委托单的条件判断
                    {
                        if (!toPointBatch.Contains(item.PointBatchId))
                        {
                            toPointBatch = toPointBatch + item.PointBatchId + ",";
                        }
                        //int? fileNum = null;
                        //if (item.Dia >= 500)
                        //{
                        //    fileNum = Batch_BatchTrustItemService.GetFilmNumByRateAndDia(item.DetectionRateValue, item.Dia);
                        //}
                        Model.Batch_BatchTrustItem trustItem = new Model.Batch_BatchTrustItem
                        {
                            TrustBatchItemId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrustItem)),
                            TrustBatchId = trustBatchId,
                            PointBatchItemId = item.PointBatchItemId,
                            WeldJointId = item.WeldJointId,
                            //FilmNum = fileNum,
                            CreateDate = DateTime.Now
                        };
                        Batch_BatchTrustItemService.AddBatchTrustItem(trustItem);
                    }
                    Model.Batch_PointBatchItem pointBatchItem = db.Batch_PointBatchItem.FirstOrDefault(e => e.PointBatchItemId == item.PointBatchItemId);
                    pointBatchItem.IsBuildTrust = true;
                    db.SubmitChanges();
                }
                // 回写委托批对应点口信息
                if (!string.IsNullOrEmpty(toPointBatch))
                {
                    toPointBatch = toPointBatch.Substring(0, toPointBatch.Length - 1);
                    var updateTrut = BLL.Batch_BatchTrustService.GetBatchTrustById(trustBatchId);
                    if (updateTrut != null)
                    {
                        updateTrut.TopointBatch = toPointBatch;
                        BLL.Batch_BatchTrustService.UpdateBatchTrust(updateTrut);
                    }
                }
            }
            Alert.ShowInTop("已成功生成委托单!", MessageBoxIcon.Success);
        }
        #endregion
        #region 切除焊口
        /// 
        ///  切除焊口
        /// 
        /// 
        /// 
        protected void btnCut_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop(Resources.Lan.SelectLeastOneRecord, MessageBoxIcon.Warning);
                return;
            }
            var pointBatchItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(Grid1.SelectedRowID);
            if (pointBatchItem != null)
            {
                if (pointBatchItem.PointState == null || pointBatchItem.IsBuildTrust == null || pointBatchItem.IsBuildTrust == false)
                {
                    //pointBatchItem.IsCheckRepair = false;
                    pointBatchItem.OldPointDate = pointBatchItem.PointDate;
                    pointBatchItem.OldPointState = pointBatchItem.PointState;
                    pointBatchItem.CutDate = System.DateTime.Now;////更新批明细 切除日期
                    Funs.DB.SubmitChanges();
                    BLL.Batch_PointBatchService.UpdateNewKuoOrCutJointNo(pointBatchItem.PointBatchItemId, "C");
                    // 更新批 是否委托:否
                    var updatePointBatch = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
                    if (updatePointBatch != null)
                    {
                        updatePointBatch.IsTrust = false;
                        BLL.Batch_PointBatchService.UpdatePointBatch(updatePointBatch);
                    }
                    this.BindGrid();
                    ShowNotify("焊口切除成功!", MessageBoxIcon.Success);
                }
                else
                {
                    Alert.ShowInTop("焊口已委托,不能切除!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("未选中要切除的焊口!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 取消点口
        /// 
        ///  取消点口
        /// 
        /// 
        /// 
        protected void btnCancelPoint_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnCancelPoint))
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop(Resources.Lan.SelectLeastOneRecord, MessageBoxIcon.Warning);
                    return;
                }
                string pointBatchItemId = Grid1.SelectedRowID;
                if (BLL.Batch_PointBatchService.GetIsShowCancellation(pointBatchItemId, "1"))
                {
                    var pointBatchItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(Grid1.SelectedRowID);
                    if (pointBatchItem != null)
                    {
                        Model.HJGLDB db = Funs.DB;
                        pointBatchItem.PointDate = null;
                        pointBatchItem.PointState = null;
                        pointBatchItem.CutDate = null;////更新批明细 切除日期
                        pointBatchItem.IsBuildTrust = null;
                        db.SubmitChanges();
                        var trust = db.Batch_BatchTrustItem.FirstOrDefault(p => p.PointBatchItemId == pointBatchItemId);
                        if (trust != null)
                        {
                            //var checkItem = db.Batch_NDEItem.FirstOrDefault(x => x.TrustBatchItemId == trust.TrustBatchItemId && !x.SubmitDate.HasValue);
                            //if (checkItem != null)
                            //{
                            //    string ndeID = checkItem.NDEID;
                            //    // 删除检测单里明细
                            //    BLL.Batch_NDEItemService.DeleteNDEItemByNDEItemID(checkItem.NDEItemID);
                            //    var c = BLL.Batch_NDEItemService.GetNDEItemByNDEID(ndeID);
                            //    if (c.Count() == 0)
                            //    {
                            //        // 当没有明细时删除对应主表
                            //        BLL.Batch_NDEService.DeleteNDEById(ndeID);
                            //    }
                            //}
                            string trustBatchId = trust.TrustBatchId;
                            // 删除委托单里明细
                            BLL.Batch_BatchTrustItemService.DeleteTrustItemByTrustBatchItemId(trust.TrustBatchItemId);
                            var t = BLL.Batch_BatchTrustItemService.GetBatchTrustItemByTrustBatchId(trustBatchId);
                            if (t.Count() == 0)
                            {
                                // 当没有明细时删除对应主表
                                BLL.Batch_BatchTrustService.DeleteBatchTrustById(trustBatchId);
                            }
                        }
                        BindGrid();
                        BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnCancelPoint, pointBatchItemId);
                        Alert.ShowInTop("该点口已成功取消!", MessageBoxIcon.Success);
                    }
                }
                else
                {
                    Alert.ShowInTop("非点口或已检测不能取消!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 取消扩透
        /// 
        ///  取消扩透
        /// 
        /// 
        /// 
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnCancelPoint))
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop(Resources.Lan.SelectLeastOneRecord, MessageBoxIcon.Warning);
                    return;
                }
                string pointBatchItemId = Grid1.SelectedRowID;
                if (BLL.Batch_PointBatchService.GetIsShowCancellation(pointBatchItemId, "2"))
                {
                    var pointBatchItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(Grid1.SelectedRowID);
                    if (pointBatchItem != null)
                    {
                        Model.HJGLDB db = Funs.DB;
                        pointBatchItem.PointDate = pointBatchItem.OldPointDate;
                        pointBatchItem.PointState = pointBatchItem.OldPointState;
                        pointBatchItem.RepairRecordId = null;
                        pointBatchItem.CutDate = null;////更新批明细 切除日期
                        Funs.DB.SubmitChanges();
                        var trust = db.Batch_BatchTrustItem.FirstOrDefault(p => p.PointBatchItemId == pointBatchItemId);
                        if (trust != null)
                        {
                            //var checkItem = db.Batch_NDEItem.FirstOrDefault(x => x.TrustBatchItemId == trust.TrustBatchItemId && !x.SubmitDate.HasValue);
                            //if (checkItem != null)
                            //{
                            //    string ndeID = checkItem.NDEID;
                            //    // 删除检测单里明细
                            //    BLL.Batch_NDEItemService.DeleteNDEItemByNDEItemID(checkItem.NDEItemID);
                            //    var c = BLL.Batch_NDEItemService.GetNDEItemByNDEID(ndeID);
                            //    if (c.Count() == 0)
                            //    {
                            //        // 当没有明细时删除对应主表
                            //        BLL.Batch_NDEService.DeleteNDEById(ndeID);
                            //    }
                            //}
                            string trustBatchId = trust.TrustBatchId;
                            // 删除委托单里明细
                            BLL.Batch_BatchTrustItemService.DeleteTrustItemByTrustBatchItemId(trust.TrustBatchItemId);
                            var t = BLL.Batch_BatchTrustItemService.GetBatchTrustItemByTrustBatchId(trustBatchId);
                            if (t.Count() == 0)
                            {
                                // 当没有明细时删除对应主表
                                BLL.Batch_BatchTrustService.DeleteBatchTrustById(trustBatchId);
                            }
                        }
                        pointBatchItem.IsBuildTrust = null;
                        db.SubmitChanges(); //更新批明细 返修日期 状态
                        BLL.Batch_PointBatchService.CancellationJointNo(pointBatchItem.WeldJointId);
                        BindGrid();
                        BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnCancelPoint, pointBatchItemId);
                        Alert.ShowInTop("该扩透口已成功取消!", MessageBoxIcon.Success);
                    }
                }
                else
                {
                    Alert.ShowInTop("非扩透口或已检测审核不能取消!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 修改首焊
        /// 
        /// 修改首焊
        /// 
        /// 
        /// 
        protected void btnModefyFristWeld_Click(object sender, EventArgs e)
        {
            if (this.CurrUser.Account == Const.Gly)
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop(Resources.Lan.SelectLeastOneRecord, MessageBoxIcon.Warning);
                    return;
                }
                string pointBatchItemId = Grid1.SelectedRowID;
                var pointBatchItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(Grid1.SelectedRowID);
                if (pointBatchItem != null)
                {
                    if (pointBatchItem.IsWelderFirst == true)
                    {
                        pointBatchItem.IsWelderFirst = null;
                    }
                    else
                    {
                        pointBatchItem.IsWelderFirst = true;
                    }
                    Funs.DB.SubmitChanges();
                    BindGrid();
                    BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnCancelPoint, pointBatchItemId);
                    Alert.ShowInTop("已修改该焊工的首焊!", MessageBoxIcon.Success);
                }
            }
            else
            {
                ShowNotify("只有管理员才能修改!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 打印
        /// 
        /// 打印
        /// 
        /// 
        /// 
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.PointBatchId))
            {
                string parm = string.Empty;
                var pointBatch = Funs.DB.View_Batch_PointBatch.FirstOrDefault(x => x.PointBatchId == this.PointBatchId);
                if (pointBatch != null)
                {
                    if (!string.IsNullOrEmpty(pointBatch.UnitCode))
                    {
                        parm = pointBatch.UnitCode;
                    }
                    else
                    {
                        parm = "NULL";
                    }
                    if (!string.IsNullOrEmpty(pointBatch.ProjectCode))
                    {
                        parm = parm + "|" + pointBatch.ProjectCode;
                    }
                    else
                    {
                        parm = parm + "|" + "NULL";
                    }
                    if (!string.IsNullOrEmpty(pointBatch.DetectionTypeCode))
                    {
                        parm = parm + "|" + "NDE Type:" + pointBatch.DetectionTypeCode;
                    }
                    else
                    {
                        parm = parm + "|" + "NDE Type:" + "NULL";
                    }
                   // PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../../Report/ReportPrint.aspx?report=1&pointBatchId={0}&parm={1}", this.PointBatchId, parm, "编辑 - ")));
                }
            }
        }
        #endregion
        private string GetNewTrust(string code)
        {
            int r_num = 0;
            string newTrustCode = string.Empty;
            if (code.Contains("R1") || code.Contains("R2") || code.Contains("R3") || code.Contains("R4"))
            {
                int indexR = code.LastIndexOf("R");
                if (indexR > 0)
                {
                    try
                    {
                        r_num = Convert.ToInt32(code.Substring(indexR + 1, 1)) + 1;
                        newTrustCode = code.Substring(0, code.Length - 1) + r_num.ToString();
                    }
                    catch { }
                }
            }
            else
            {
                newTrustCode = code + "R1";
            }
           
            return newTrustCode;
        }
    }
}