using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using BLL;
namespace FineUIPro.Web.WeldingProcess.TrustManage
{
    public partial class SelectExpandPoint : 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.PointBatchId = Request.Params["PointBatchId"];
                var pointBatch = Batch_PointBatchService.GetPointBatchById(PointBatchId);
                if (pointBatch != null)
                {
                    this.lbTitle.Text = "当前批号:" + pointBatch.PointBatchCode;
                    var pointBatchItemRepairs = (from x in Funs.DB.View_Batch_PointBatchItem
                                                 where x.PointBatchId == this.PointBatchId && !x.CutDate.HasValue
                                                  && !x.RepairDate.HasValue && x.PointState == null
                                                 select x).ToList();
                    var pointBatchItem = (from x in Funs.DB.View_Batch_PointBatchItem
                                          where x.PointBatchId == this.PointBatchId && !x.CutDate.HasValue
                                           && !x.RepairDate.HasValue && x.PointState != null
                                          select x).ToList();
                    foreach (var ext in pointBatchItem)
                    {
                        var trustItem = from x in Funs.DB.Batch_BatchTrustItem
                                        where x.PointBatchItemId == ext.PointBatchItemId
                                        select x;
                        if (trustItem.Count() == 1) // 如大于1,则表示这个口之前已进过委托单,不能再选了
                        {
                            var firstBatchTrustItem = trustItem.FirstOrDefault();
                            if (firstBatchTrustItem != null)
                            {
                                var checkItems = from x in Funs.DB.Batch_NDEItem
                                                 where x.NDEItemID == firstBatchTrustItem.TrustBatchItemId
                                                 select x;
                                if (checkItems.Count() == 0) // 还未进检测单
                                {
                                    pointBatchItemRepairs.Add(ext);
                                }
                                else
                                {
                                    var checkItem = checkItems.FirstOrDefault(x => !x.SubmitDate.HasValue);
                                    if (checkItem != null)
                                    {
                                        pointBatchItemRepairs.Add(ext);
                                    }
                                }
                            }
                        }
                        if (trustItem.Count() == 0) // 还未进委托单
                        {
                            pointBatchItemRepairs.Add(ext);
                        }
                    }
                    if (pointBatchItemRepairs.Count() > 0)
                    {
                        BindGrid(pointBatchItemRepairs);
                    }
                }
            }
        }
        #endregion        
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        private void BindGrid(List pointBatchItemRepairs)
        {
            Grid1.DataSource = pointBatchItemRepairs.OrderBy(x=>x.PipelineCode).OrderBy(x=>x.WeldJointCode);
            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 == "2")
                    {
                        ids += pointItem.PointBatchItemId + ",";
                    }
                    else if (pointItem.PointState == "1")
                    {
                        this.Grid1.Rows[i].RowSelectable = false;
                    }
                }               
            }
            if (!string.IsNullOrEmpty(ids))
            {
                ids = ids.Substring(0, ids.Length - 1);
                this.Grid1.SelectedRowIDArray = ids.Split(',');
            }
        }
        #endregion
        
        #region 确定按钮
        /// 
        /// 确定按钮
        /// 
        /// 
        /// 
        protected void btnAccept_Click(object sender, EventArgs e)
        {
            Model.HJGLDB db = Funs.DB;
            string[] selectRowId = Grid1.SelectedRowIDArray;
            string weldJointId = string.Empty;
            // 找最近一个返修口
            var pointItem = db.Batch_PointBatchItem.Where(x => x.PointBatchId == this.PointBatchId && x.PointState != null && x.IsCheckRepair.HasValue);
            foreach (var p in pointItem)
            {
                var j = BLL.Pipeline_WeldJointService.GetWeldJointByWeldJointId(p.WeldJointId);
                if (j.WeldJointCode.Contains("K"))
                {
                    weldJointId = p.WeldJointId;
                    break;
                }
            }
            for (int i = 0; i < this.Grid1.Rows.Count; i++)
            {
                string pointBatchItemId = this.Grid1.Rows[i].DataKeys[0].ToString();
                var pointBatchItem = Funs.DB.Batch_PointBatchItem.FirstOrDefault(x => x.PointBatchItemId == pointBatchItemId);
                if (pointBatchItem != null)
                {
                    if (selectRowId.Contains(pointBatchItemId))
                    {                       
                        if (pointItem.Count() > 0 &&  pointBatchItem.PointState == null)
                        {
                            pointBatchItem.PointDate = DateTime.Now;
                            pointBatchItem.PointState = "2";
                            db.SubmitChanges(); ////更新批明细 返修日期 状态
                            int k_num = 0;
                            string jot = "K1";
                            Model.Pipeline_WeldJoint jointInfo = null;
                            if (!String.IsNullOrEmpty(weldJointId))
                            {
                                jointInfo = db.Pipeline_WeldJoint.FirstOrDefault(x => x.WeldJointId == weldJointId);
                            }
                            else
                            {
                                var first = pointItem.FirstOrDefault();
                                if (first != null)
                                {
                                    jointInfo = db.Pipeline_WeldJoint.FirstOrDefault(x => x.WeldJointId == first.WeldJointId);
                                }
                            }
                            int indexK = jointInfo.WeldJointCode.LastIndexOf("K");
                            if (indexK > 0)
                            {
                                try
                                {
                                    k_num = Convert.ToInt32(jointInfo.WeldJointCode.Substring(indexK + 1, 1)) + 1;
                                    jot = "K" + k_num.ToString();
                                }
                                catch { }
                            }
                            BLL.Batch_PointBatchService.UpdateNewKuoOrCutJointNo(pointBatchItem.PointBatchItemId, jot);
                        }
                    }
                    else
                    {
                        // 找到已扩透的明细ID; 找到委托单里的明细.
                        if (pointBatchItem.PointState == "2")
                        {
                            var trust = db.Batch_BatchTrustItem.FirstOrDefault(p => p.PointBatchItemId == pointBatchItem.PointBatchItemId);
                            if (trust != null)
                            {
                                string trustBatchId = trust.TrustBatchId;
                                var checkItem = db.Batch_NDEItem.FirstOrDefault(x => x.NDEItemID == trust.TrustBatchItemId);
                                if (checkItem != null)
                                {
                                    string checkId = checkItem.NDEID;
                                    if (checkItem.SubmitDate == null)
                                    {
                                        // 删除检测单里明细
                                        Batch_NDEItemService.DeleteNDEItemByNDEItemID(checkItem.NDEItemID);
                                        var c = BLL.Batch_NDEItemService.GetNDEItemByNDEID(checkId);
                                        if (c.Count() == 0)
                                        {
                                            // 当没有明细时删除对应主表
                                            BLL.Batch_NDEService.DeleteNDEById(checkId);
                                        }
                                    }
                                }
                                if (checkItem == null || (checkItem != null && checkItem.SubmitDate == null))
                                {
                                    // 删除委托单里明细
                                    Batch_BatchTrustItemService.DeleteTrustItemByTrustBatchItemId(trust.TrustBatchItemId);
                                    var t = BLL.Batch_BatchTrustItemService.GetBatchTrustItemByTrustBatchId(trustBatchId);
                                    if (t.Count() == 0)
                                    {
                                        // 当没有明细时删除对应主表
                                        BLL.Batch_BatchTrustService.DeleteBatchTrustById(trustBatchId);
                                    }
                                }
                            }
                            pointBatchItem.PointDate = null;
                            pointBatchItem.PointState = null;
                            pointBatchItem.IsBuildTrust = null;
                            db.SubmitChanges(); //更新批明细 返修日期 状态
                            // 更新焊口号
                            Batch_PointBatchService.CancellationJointNo(pointBatchItem.WeldJointId);
                        }
                    }
                }
            }
            // 更新批 是否委托:否
            var updatePointBatch = BLL.Batch_PointBatchService.GetPointBatchById(this.PointBatchId);
            if (updatePointBatch != null)
            {
                updatePointBatch.IsTrust = false;
                BLL.Batch_PointBatchService.UpdatePointBatch(updatePointBatch);
            }
            BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnSelectResetExpand, this.PointBatchId);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
    }
}