using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
namespace FineUIPro.Web.WeldingProcess.CheckManage
{
    public partial class RepairAndExpand : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtRepairMonth.Text = string.Format("{0:yyyy-MM}", DateTime.Now);
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                this.InitTreeMenu();//加载树
            }
        }
        private void PageInit()
        {
            string repairRecordId = tvControlItem.SelectedNodeID;
            var repairRecord = BLL.RepairRecordService.GetRepairRecordById(repairRecordId);
            var jot = BLL.Pipeline_WeldJointService.GetViewWeldJointById(repairRecord.WeldJointId);
            var ndeItem = Batch_NDEItemService.GetNDEItemById(repairRecord.NDEItemID);
            //var pipe = BLL.Pipeline_PipelineService.GetPipelineByPipelineId(jot.PipelineId);
            if (!string.IsNullOrEmpty(repairRecordId))
            {
                this.txtPipeCode.Text = jot.PipelineCode;
                txtWeldJointCode.Text = jot.WeldJointCode;
                txtWelder.Text = jot.BackingWelderCode;
                txtRepairLocation.Text = repairRecord.RepairLocation;
                txtJudgeGrade.Text = ndeItem.JudgeGrade;
                txtCheckDefects.Text = repairRecord.CheckDefects;
                if (repairRecord.RepairDate.HasValue)
                {
                    txtRepairDate.Text = repairRecord.RepairDate.ToString();
                }
                else
                {
                    txtRepairDate.Text = DateTime.Now.Date.ToString();
                }
                if (repairRecord.IsCut == true)
                {
                    ckbIsCut.Checked = true;
                }
                else
                {
                    ckbIsCut.Checked = false;
                }
                if (!string.IsNullOrEmpty(repairRecord.RepairWelder))
                {
                    drpRepairWelder.SelectedValue = repairRecord.RepairWelder;
                }
                else
                {
                    drpRepairWelder.SelectedValue = repairRecord.WelderId;
                }
                if (repairRecord.AuditDate.HasValue)
                {
                    lbIsAudit.Text = "已审核";
                }
                else
                {
                    lbIsAudit.Text = "未审核";
                }
            }
        }
        #region 加载树
        /// 
        /// 加载树
        /// 
        private void InitTreeMenu()
        {
            if (!string.IsNullOrEmpty(this.txtRepairMonth.Text.Trim()))
            {
                DateTime startTime = Convert.ToDateTime(this.txtRepairMonth.Text.Trim() + "-01");
                DateTime endTime = startTime.AddMonths(1);
                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
                {
                    units.Add(BLL.Base_UnitService.GetUnit(this.CurrUser.UnitId));
                }
                if (units != null)
                {
                    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);
                        this.BindNodes(newNode, startTime, endTime);
                    }
                }
                else
                {
                    Alert.ShowInTop(Resources.Lan.PleaseAddUnitFirst, MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop(Resources.Lan.PleaseSelectTrustMonth, MessageBoxIcon.Warning);
            }
        }
        /// 
        ///  绑定树节点
        /// 
        /// 
        private void BindNodes(TreeNode node, DateTime startTime, DateTime endTime)
        {
            if (node.ToolTip == "Unit")
            {
                ///装置
                var install = (from x in Funs.DB.Project_Installation
                               join y in Funs.DB.Repair_RepairRecord on x.InstallationId equals y.InstallationId
                               where y.UnitId == node.NodeID && x.ProjectId == this.CurrUser.LoginProjectId
                               orderby x.InstallationCode
                               select x).Distinct();
                foreach (var q in install)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = q.InstallationName;
                    newNode.NodeID = q.InstallationId.ToString();
                    newNode.Expanded = true;
                    newNode.ToolTip = "Installation";
                    node.Nodes.Add(newNode);
                    BindNodes(newNode, startTime, endTime);
                }
            }
            else if (node.ToolTip == "Installation")
            {
                //单号
                string ndtTypeId = node.NodeID.Split('|')[0];
                var repairs = (from x in Funs.DB.View_RepairRecord
                               where x.NoticeDate < Convert.ToDateTime(this.txtRepairMonth.Text.Trim() + "-01").AddMonths(1)
                               && x.NoticeDate >= Convert.ToDateTime(this.txtRepairMonth.Text.Trim() + "-01").AddMonths(-1)
                               && x.ProjectId == this.CurrUser.LoginProjectId && x.RepairRecordCode.Contains(this.txtSearchCode.Text.Trim())
                               && x.InstallationId.ToString() == node.NodeID
                               && x.UnitId == node.ParentNode.NodeID
                               orderby x.RepairRecordCode descending
                               select x).ToList();
                if (this.drpTrust.SelectedValue == "0")
                {
                    repairs = repairs.Where(x => x.TrustBatchItemId == null).ToList();
                }
                else
                {
                    repairs = repairs.Where(x => x.TrustBatchItemId != null).ToList();
                }
                foreach (var r in repairs)
                {
                    TreeNode newNode = new TreeNode();
                    if (!r.AuditDate.HasValue)
                    {
                        newNode.Text = "" + r.RepairRecordCode + "";
                    }
                    else
                    {
                        newNode.Text = r.RepairRecordCode;
                    }
                    newNode.NodeID = r.RepairRecordId;
                    newNode.ToolTip = "返修单";
                    newNode.EnableClickEvent = true;
                    node.Nodes.Add(newNode);
                }
            }
        }
        #endregion
        private void BindGrid()
        {
            if (!string.IsNullOrEmpty(tvControlItem.SelectedNodeID))
            {
                string repairRecordId = tvControlItem.SelectedNodeID;
                var repairRecord = BLL.RepairRecordService.GetRepairRecordById(repairRecordId);
                var ndt = BLL.Base_DetectionTypeService.GetDetectionTypeByDetectionTypeId(repairRecord.DetectionTypeId);
                var ndtItem = BLL.Batch_NDEItemService.GetNDEItemById(repairRecord.NDEItemID);
                var jot = BLL.Pipeline_WeldJointService.GetViewWeldJointById(repairRecord.WeldJointId);
                var day = BLL.Pipeline_WeldingDailyService.GetPipeline_WeldingDailyByWeldingDailyId(jot.WeldingDailyId);
                string strSql = string.Empty;
                Model.Batch_PointBatchItem r = Funs.DB.Batch_PointBatchItem.FirstOrDefault(x => x.RepairRecordId == repairRecordId);
                string code2 = string.Empty;
                string code4 = string.Empty;
                if (repairRecord != null && !string.IsNullOrEmpty(repairRecord.RepairRecordCode))
                {
                    // 取返修单后4位
                    code4 = repairRecord.RepairRecordCode.Substring(repairRecord.RepairRecordCode.Length - 4);
                    // 取返修单后2位
                    code2 = repairRecord.RepairRecordCode.Substring(repairRecord.RepairRecordCode.Length - 2);
                }
                if (jot.Dia >= 500)
                {
                    if (r == null)
                    {
                        strSql = @"SELECT PointBatchItemId,PointBatchId,PointBatchCode,WeldJointId,PointState,PointDate,WeldJointCode,
                                         JointArea,Size,WeldingDate,PipelineCode,PipingClassName
                                    FROM dbo.View_Batch_PointBatchItem 
                                   WHERE ProjectId=@ProjectId 
                                         AND (Dia>=500 AND PState ='1' AND WeldJointId=@WeldJointId)";
                    }
                    else
                    {
                        strSql = @"SELECT PointBatchItemId, PointBatchId, PointBatchCode, WeldJointId, PointState, PointDate, WeldJointCode,
                                         JointArea, Size, WeldingDate, PipelineCode, PipingClassName
                                    FROM dbo.View_Batch_PointBatchItem
                                   WHERE ProjectId = @ProjectId AND RepairRecordId=@RepairRecordId";
                    }
                }
                else
                {
                    strSql = @"SELECT PointBatchItemId,PointBatchId,PointBatchCode,WeldJointId,PointState,PointDate,WeldJointCode,
                                         JointArea,Size,WeldingDate,PipelineCode,PipingClassName
                                    FROM dbo.View_Batch_PointBatchItem 
                                   WHERE ProjectId=@ProjectId AND DetectionTypeId=@DetectionTypeId
                                         AND (PointDate IS NULL OR (PointDate IS NOT NULL AND RepairRecordId=@RepairRecordId))";
                }
              
                List listStr = new List();
                listStr.Add(new SqlParameter("@DetectionTypeId", repairRecord.DetectionTypeId));
                // 如果是第二次返修不加载扩透口 
                if (!code4.Contains("K1") && code2 == "R2")
                {
                    listStr.Add(new SqlParameter("@ProjectId", "0"));
                }
                else
                {
                    var rate = from x in Funs.DB.Pipeline_WeldJoint
                               join y in Funs.DB.Pipeline_Pipeline on x.PipelineId equals y.PipelineId
                               join z in Funs.DB.Base_DetectionRate on y.DetectionRateId equals z.DetectionRateId
                               where x.WeldJointId == repairRecord.WeldJointId
                               select z.DetectionRateValue;
                    // 如果返修的焊口为100%的检测比例,则不进行扩透
                    if (rate.Count() > 0 && rate.First().Value == 100)
                    {
                        listStr.Add(new SqlParameter("@ProjectId", "0"));
                    }
                    else
                    {
                        if (ndtItem.JudgeGrade == "修磨" || ndtItem.JudgeGrade == "异物")
                        {
                            listStr.Add(new SqlParameter("@ProjectId", "0"));
                        }
                        else
                        {
                            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
                        }
                    }
                }
                //if (ndt.SysType == "射线检测")
                //{
                //    strSql += " AND Flag = @Flag";
                //    listStr.Add(new SqlParameter("@Flag", "1"));
                //}
                //else
                //{
                //    strSql += " AND Flag <> @Flag";
                //    listStr.Add(new SqlParameter("@Flag", "1"));
                //}
                listStr.Add(new SqlParameter("@RepairRecordId", repairRecordId));
                if (r == null && jot.Dia >= 500)
                {
                    listStr.Add(new SqlParameter("@WeldJointId", repairRecord.WeldJointId));
                }
                if (ckbWelder.Checked)
                {
                    strSql += " AND WelderId =@WelderId";
                    listStr.Add(new SqlParameter("@WelderId", jot.BackingWelderId));
                }
                if (ckbPipe.Checked)
                {
                    strSql += " AND PipelineId =@PipelineId";
                    listStr.Add(new SqlParameter("@PipelineId", jot.PipelineId));
                }
                if (ckbRepairBefore.Checked)
                {
                    strSql += " AND WeldingDate <=@WeldingDate";
                    listStr.Add(new SqlParameter("@WeldingDate", day.WeldingDate));
                }
                if (ckbMat.Checked)
                {
                    strSql += " AND Mat =@Mat";
                    listStr.Add(new SqlParameter("@Mat", jot.Material1Id));
                }
                if (ckbSpec.Checked)
                {
                    strSql += " AND Specification =@Specification";
                    listStr.Add(new SqlParameter("@Specification", jot.Specification));
                }
                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();
                
                string ids = string.Empty;
                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.PointState != null)
                        {
                            ids += pointItem.PointBatchItemId + ",";
                            this.Grid1.Rows[i].CellCssClasses[3] = "colorredBlue";
                            this.Grid1.Rows[i].CellCssClasses[6] = "colorredBlue";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(ids))
                {
                    ids = ids.Substring(0, ids.Length - 1);
                    this.Grid1.SelectedRowIDArray = ids.Split(',');
                }
            }
        }
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            string repairRecordId = tvControlItem.SelectedNodeID;
            var repairRecord = BLL.RepairRecordService.GetRepairRecordById(repairRecordId);
            BLL.WelderService.InitProjectWelderDropDownList(this.drpRepairWelder, true, this.CurrUser.LoginProjectId, repairRecord.UnitId, Resources.Lan.PleaseSelect);
            PageInit();
            BindGrid();
            if (BLL.RepairRecordService.GetExportNum(repairRecordId) == 0)
            {
                RandomExport(repairRecordId);
            }
        }
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            InitTreeMenu();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_RepairAndExpandMenuId, Const.BtnSave))
            {
                Model.HJGLDB db = Funs.DB;
                string repairRecordId = tvControlItem.SelectedNodeID;
                var t = from x in Funs.DB.Batch_BatchTrustItem where x.RepairRecordId == repairRecordId select x;
                if (t.Count() == 0)
                {
                    // 更新返修记录
                    var repair = db.Repair_RepairRecord.FirstOrDefault(x => x.RepairRecordId == repairRecordId);
                    if (repair != null)
                    {
                        repair.RepairWelder = drpRepairWelder.SelectedValue;
                        repair.RepairDate = Convert.ToDateTime(this.txtRepairDate.Text);
                        repair.AuditDate = DateTime.Now;
                        if (ckbIsCut.Checked)
                        {
                            repair.IsCut = true;
                            repair.RepairRecordCode = repair.RepairRecordCode.Substring(0, repair.RepairRecordCode.Length - 1) + "C";
                        }
                    }
                    // 更新返修口
                    var batchItem = db.Batch_PointBatchItem.FirstOrDefault(x => x.WeldJointId == repair.WeldJointId && x.RepairDate == null);
                    if (batchItem != null)
                    {
                        batchItem.RepairDate = Convert.ToDateTime(this.txtRepairDate.Text);
                        batchItem.RepairRecordId = repairRecordId;
                        if (ckbIsCut.Checked)
                        {
                            batchItem.CutDate = DateTime.Now.Date;
                        } 
                        db.SubmitChanges();
                    }
                    else
                    {
                        var updatebatchItem = db.Batch_PointBatchItem.FirstOrDefault(x => x.WeldJointId == repair.WeldJointId && x.RepairRecordId== repairRecordId);
                        if (updatebatchItem != null)
                        {
                            updatebatchItem.RepairDate = Convert.ToDateTime(this.txtRepairDate.Text);
                            db.SubmitChanges();
                        }
                    }
                   
                    var exp = BLL.RepairRecordService.GetExportItem(repairRecordId);
                    if (exp != null)
                    {
                        foreach (Model.Batch_PointBatchItem item in exp)
                        {
                            // 扩透口非自身
                            if (repair.WeldJointId != item.WeldJointId)
                            {
                                Model.Batch_PointBatchItem newPointBatchItem = db.Batch_PointBatchItem.FirstOrDefault(x => x.PointBatchItemId == item.PointBatchItemId);
                                newPointBatchItem.PointState = null;
                                newPointBatchItem.PointDate = null;
                                newPointBatchItem.RepairRecordId = null;
                                db.SubmitChanges();
                            }
                        }
                    }
                    // 更新扩透口
                    string[] checkedRow = Grid1.SelectedRowIDArray;
                    if (checkedRow.Count() > 0)
                    {
                        foreach (string item in checkedRow)
                        {
                            Model.Batch_PointBatchItem newPointBatchItem = db.Batch_PointBatchItem.FirstOrDefault(x => x.PointBatchItemId == item);
                            if (newPointBatchItem != null)
                            {
                                // 扩透口非自身
                                if (repair.WeldJointId != newPointBatchItem.WeldJointId)
                                {
                                    newPointBatchItem.PointState = "2";
                                    newPointBatchItem.PointDate = DateTime.Now;
                                    newPointBatchItem.RepairRecordId = repairRecordId;
                                    db.SubmitChanges();
                                }
                                // 大于500的焊口扩透口是自身,这时要增加批明细
                                else
                                {
                                    Model.Batch_PointBatchItem pointItem = db.Batch_PointBatchItem.FirstOrDefault(x => x.RepairRecordId == repairRecordId && x.PointState=="2");
                                    // 大于500的焊口扩透口是自身,保存后不能再次增加
                                    if (pointItem == null)
                                    {
                                        Model.Batch_PointBatchItem addPointBatchItem = new Model.Batch_PointBatchItem();
                                        string itemId = SQLHelper.GetNewID(typeof(Model.Batch_PointBatchItem));
                                        addPointBatchItem.PointBatchItemId = itemId;
                                        addPointBatchItem.PointBatchId = newPointBatchItem.PointBatchId;
                                        addPointBatchItem.WeldJointId = repair.WeldJointId;
                                        addPointBatchItem.WeldingDate = newPointBatchItem.WeldingDate;
                                        addPointBatchItem.AcceptLevel = newPointBatchItem.AcceptLevel;
                                        addPointBatchItem.PointState = "2";
                                        addPointBatchItem.PointDate = DateTime.Now;
                                        addPointBatchItem.RepairRecordId = repairRecordId;
                                        addPointBatchItem.IsCheckRepair = false;
                                        BLL.Batch_PointBatchItemService.AddPointBatchItem(addPointBatchItem);
                                    }
                                }
                            }
                        }
                    }
                    BindGrid();
                    Alert.ShowInTop("保存成功!", MessageBoxIcon.Success);
                }
                else
                {
                    Alert.ShowInTop("已生成委托单了,未能保存!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        protected void btnPointAudit_Click(object sender, EventArgs e)
        {
            Model.HJGLDB db = Funs.DB;
            string repairRecordId = tvControlItem.SelectedNodeID;
            // 更新返修记录
            var repair = db.Repair_RepairRecord.FirstOrDefault(x => x.RepairRecordId == repairRecordId);
            if (!repair.AuditDate.HasValue)
            {
                repair.AuditDate = DateTime.Now;
                db.SubmitChanges();
                string[] selectRowId = Grid1.SelectedRowIDArray;
                if (selectRowId.Count() > 0)
                {
                    foreach (var item in selectRowId)
                    {
                        BLL.Batch_PointBatchItemService.PointAudit(item, true);
                    }
                    this.BindGrid();
                    Alert.ShowInTop("已审核!");
                }
                else
                {
                    Alert.ShowInTop("请勾选要审核的焊口!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("已审核!");
            }
        }
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_RepairAndExpandMenuId, Const.BtnGenerate))
            {
                Model.HJGLDB db = Funs.DB;
                string repairRecordId = tvControlItem.SelectedNodeID;
                Model.Repair_RepairRecord repairRecord = BLL.RepairRecordService.GetRepairRecordById(repairRecordId);
                var pipe = BLL.Pipeline_WeldJointService.GetViewWeldJointById(repairRecord.WeldJointId);
                string pipelineId = string.Empty;
                if (pipe != null)
                {
                    pipelineId = pipe.PipelineId;
                }
                var t = from x in Funs.DB.Batch_BatchTrustItem where x.RepairRecordId == repairRecordId select x;
                if (t.Count() == 0)
                {
                    if (!string.IsNullOrEmpty(repairRecordId) && repairRecord.AuditDate.HasValue)
                    {
                        // 返修委托(切除不用返修委托)
                        if (!ckbIsCut.Checked)
                        {
                            Model.Batch_BatchTrust newRepairTrust = new Model.Batch_BatchTrust();
                            string trustBatchId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrust));
                            newRepairTrust.TrustBatchId = trustBatchId;
                            newRepairTrust.TrustBatchCode = repairRecord.RepairRecordCode;
                            newRepairTrust.TrustDate = DateTime.Now;
                            newRepairTrust.ProjectId = repairRecord.ProjectId;
                            newRepairTrust.UnitId = repairRecord.UnitId;
                            newRepairTrust.InstallationId = repairRecord.InstallationId;
                            newRepairTrust.WorkAreaId = repairRecord.WorkAreaId;
                            newRepairTrust.DetectionTypeId = repairRecord.DetectionTypeId;
                            newRepairTrust.PipelineId = pipelineId;
                            BLL.Batch_BatchTrustService.AddBatchTrust(newRepairTrust);  // 新增返修委托单
                            Model.Batch_BatchTrustItem newRepairTrustItem = new Model.Batch_BatchTrustItem();
                            newRepairTrustItem.TrustBatchItemId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrustItem));
                            newRepairTrustItem.TrustBatchId = trustBatchId;
                            newRepairTrustItem.RepairRecordId = repairRecordId;
                            newRepairTrustItem.WeldJointId = repairRecord.WeldJointId;
                            newRepairTrustItem.CreateDate = DateTime.Now;
                            Batch_BatchTrustItemService.AddBatchTrustItem(newRepairTrustItem);
                        }
                        // 扩透委托
                        var exp = BLL.RepairRecordService.GetExportItem(repairRecordId);
                        if (exp != null)
                        {
                            string exportTrustCode = string.Empty;
                            if (repairRecord.RepairRecordCode.Substring(repairRecord.RepairRecordCode.Length - 4) == "K1R2")
                            {
                                exportTrustCode = repairRecord.RepairRecordCode.Substring(0, repairRecord.RepairRecordCode.Length - 4) + "K2R2";
                            }
                            else
                            {
                                if (repairRecord.RepairRecordCode.Substring(repairRecord.RepairRecordCode.Length - 4) == "K1R1")
                                {
                                    exportTrustCode = repairRecord.RepairRecordCode.Substring(0, repairRecord.RepairRecordCode.Length - 4) + "K2";
                                }
                                else
                                {
                                    exportTrustCode = repairRecord.RepairRecordCode.Substring(0, repairRecord.RepairRecordCode.Length - 2) + "K1";
                                }
                            }
                            
                            Model.Batch_BatchTrust newExportTrust = new Model.Batch_BatchTrust();
                            string exporttrustBatchId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrust));
                            newExportTrust.TrustBatchId = exporttrustBatchId;
                            newExportTrust.TrustBatchCode = exportTrustCode;
                            newExportTrust.TrustDate = DateTime.Now;
                            newExportTrust.ProjectId = repairRecord.ProjectId;
                            newExportTrust.UnitId = repairRecord.UnitId;
                            newExportTrust.InstallationId = repairRecord.InstallationId;
                            newExportTrust.WorkAreaId = repairRecord.WorkAreaId;
                            newExportTrust.DetectionTypeId = repairRecord.DetectionTypeId;
                            newExportTrust.PipelineId = pipelineId;
                            BLL.Batch_BatchTrustService.AddBatchTrust(newExportTrust);  // 新增扩透委托单
                            foreach (var q in exp)
                            {
                                Model.Batch_BatchTrustItem newExportTrustItem = new Model.Batch_BatchTrustItem();
                                newExportTrustItem.TrustBatchItemId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrustItem));
                                newExportTrustItem.TrustBatchId = exporttrustBatchId;
                                newExportTrustItem.PointBatchItemId = q.PointBatchItemId;
                                newExportTrustItem.WeldJointId = q.WeldJointId;
                                newExportTrustItem.CreateDate = DateTime.Now;
                                Batch_BatchTrustItemService.AddBatchTrustItem(newExportTrustItem);
                                Model.Batch_PointBatchItem pointBatchItem = db.Batch_PointBatchItem.FirstOrDefault(x => x.PointBatchItemId == q.PointBatchItemId);
                                pointBatchItem.IsBuildTrust = true;
                                db.SubmitChanges();
                            }
                        }
                        Alert.ShowInTop("成功生成委托单!", MessageBoxIcon.Success);
                    }
                    else
                    {
                        Alert.ShowInTop("选中的返修单需要先保存再生成委托单!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    Alert.ShowInTop("已生成委托单,不能再次生成!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        protected void btnSee_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tvControlItem.SelectedNodeID))
            {
                string window = String.Format("SeeFilm.aspx?repairRecordId={0}", tvControlItem.SelectedNodeID, "查看底片 - ");
                PageContext.RegisterStartupScript(Window1.GetShowReference(window));
            }
        }
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        #region 排序
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid();
        }
        #endregion
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }
        protected void ckbWelder_CheckedChanged(object sender, CheckedEventArgs e)
        {
            BindGrid();
            string repairRecordId = tvControlItem.SelectedNodeID;
            if (BLL.RepairRecordService.GetExportNum(repairRecordId) == 0)
            {
                RandomExport(repairRecordId);
            }
        }
        protected void ckbPipe_CheckedChanged(object sender, CheckedEventArgs e)
        {
            BindGrid();
            string repairRecordId = tvControlItem.SelectedNodeID;
            if (BLL.RepairRecordService.GetExportNum(repairRecordId) == 0)
            {
                RandomExport(repairRecordId);
            }
        }
        protected void ckbRepairBefore_CheckedChanged(object sender, CheckedEventArgs e)
        {
            BindGrid();
            string repairRecordId = tvControlItem.SelectedNodeID;
            if (BLL.RepairRecordService.GetExportNum(repairRecordId) == 0)
            {
                RandomExport(repairRecordId);
            }
        }
        protected void ckbMat_CheckedChanged(object sender, CheckedEventArgs e)
        {
            BindGrid();
            string repairRecordId = tvControlItem.SelectedNodeID;
            if (BLL.RepairRecordService.GetExportNum(repairRecordId) == 0)
            {
                RandomExport(repairRecordId);
            }
        }
        protected void ckbSpec_CheckedChanged(object sender, CheckedEventArgs e)
        {
            BindGrid();
            string repairRecordId = tvControlItem.SelectedNodeID;
            if (BLL.RepairRecordService.GetExportNum(repairRecordId) == 0)
            {
                RandomExport(repairRecordId);
            }
        }
        private void RandomExport(string repairRecordId)
        {
            var code = BLL.RepairRecordService.GetRepairRecordById(repairRecordId);
            if (code != null && !string.IsNullOrEmpty(code.RepairRecordCode))
            {
                // 取返修单后4位
                string code4 = code.RepairRecordCode.Substring(code.RepairRecordCode.Length - 4);
                // 取返修单后2位
                string code2 = code.RepairRecordCode.Substring(code.RepairRecordCode.Length - 2);
                if (code2 == "R1")
                {
                    int num = Grid1.Rows.Count;
                    if (num > 0 && num <= 2)
                    {
                        if (num == 1)
                        {
                            Grid1.SelectedRowIndexArray = new int[] { 0 };
                        }
                        else
                        {
                            Grid1.SelectedRowIndexArray = new int[] { 0, 1 };
                        }
                    }
                    else
                    {
                        int[] r = Funs.GetRandomNum(2, 0, num - 1);
                        Grid1.SelectedRowIndexArray = r;
                    }
                }
                else
                {
                    if (code4.Contains("K1") && code2 == "R2")
                    {
                        Grid1.SelectAllRows();
                    }
                }
            }
        }
    }
}