using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using BLL;
namespace FineUIPro.Web.WeldingProcess.TrustManage
{
    public partial class PointAudit : PageBase
    {
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindGrid();
            }
        }
        #endregion
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        private void BindGrid()
        {
            string strSql = @"SELECT PointBatchItem.PointBatchItemId,PointBatch.PointBatchCode, jot.WeldJointCode,
                                     ins.InstallationCode, WorkArea.WorkAreaCode,unit.UnitCode, Pipeline.PipelineCode,
                                    (CASE PointBatchItem.IsAudit WHEN 1 THEN '是' ELSE '否' END) AS PointIsAudit,
                                     jot.JointArea,WeldingDaily.WeldingDate,PipingClass.PipingClassName,
                                     trustItem.TrustBatchItemId,
									 (CASE WHEN jot.BackingWelderId!=jot.CoverWelderId THEN backingWelder.WelderCode+'/'+coverWelder.WelderCode ELSE backingWelder.WelderCode END) AS WelderCode--焊工号
                               FROM Batch_PointBatchItem AS PointBatchItem
                               LEFT JOIN Batch_PointBatch AS PointBatch ON PointBatch.PointBatchId=PointBatchItem.PointBatchId
                               LEFT JOIN Pipeline_WeldJoint AS jot ON jot.WeldJointId=PointBatchItem.WeldJointId
                               LEFT JOIN Pipeline_Pipeline AS Pipeline ON Pipeline.PipelineId=jot.PipelineId
                                LEFT JOIN dbo.Welder_Welder backingWelder ON backingWelder.WelderId = jot.BackingWelderId
                               LEFT JOIN dbo.Welder_Welder coverWelder ON coverWelder.WelderId = jot.CoverWelderId
							   LEFT JOIN Project_WorkArea AS WorkArea ON WorkArea.WorkAreaId=Pipeline.WorkAreaId
                               LEFT JOIN Pipeline_WeldingDaily AS WeldingDaily ON WeldingDaily.WeldingDailyId=jot.WeldingDailyId
                               LEFT JOIN Base_PipingClass AS PipingClass ON PipingClass.PipingClassId=Pipeline.PipingClassId
                               LEFT JOIN dbo.Project_Installation ins ON ins.InstallationId = PointBatch.InstallationId
                               LEFT JOIN dbo.Base_Unit unit ON unit.UnitId = PointBatch.UnitId
                               LEFT JOIN dbo.Batch_BatchTrustItem trustItem ON trustItem.PointBatchItemId = PointBatchItem.PointBatchItemId
                               WHERE PointBatchItem.PointState IS NOT NULL AND trustItem.TrustBatchItemId IS NULL
                                     AND PointBatch.ProjectId=@ProjectId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            if (!string.IsNullOrEmpty(this.txtPipelineCode.Text.Trim()))
            {
                strSql += " AND Pipeline.PipelineCode LIKE @PipelineCode";
                listStr.Add(new SqlParameter("@PipelineCode", "%" + this.txtPipelineCode.Text.Trim() + "%"));
            }
            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();
        }
        #endregion
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #region 排序
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            this.BindGrid();
        }
        #endregion
        #region 确定按钮
        /// 
        /// 确定按钮
        /// 
        /// 
        /// 
        protected void btnAccept_Click(object sender, EventArgs e)
        {
            string[] selectRowId = Grid1.SelectedRowIDArray;
            if (selectRowId.Count() > 0)
            {
                foreach (var item in selectRowId)
                {
                    BLL.Batch_PointBatchItemService.PointAudit(item, true);
                    BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnJLAudit, item);
                }
                this.BindGrid();
                Alert.ShowInTop("勾选的焊口已审核!");
            }
            else
            {
                Alert.ShowInTop("请勾选要审核的焊口!", MessageBoxIcon.Warning);
            }
        }
        protected void btnCancelAccept_Click(object sender, EventArgs e)
        {
            string[] selectRowId = Grid1.SelectedRowIDArray;
            if (selectRowId.Count() > 0)
            {
                foreach (var item in selectRowId)
                {
                    BLL.Batch_PointBatchItemService.PointAudit(item, false);
                    BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnJLAudit, item);
                }
                this.BindGrid();
                Alert.ShowInTop("勾选的焊口已取消审核!");
            }
            else
            {
                Alert.ShowInTop("请勾选要取消审核的焊口!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 生成委托单
        /// 
        /// 生成委托单
        /// 
        /// 
        /// 
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnGenerate))
            {
                var project = BLL.Base_ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
                if (project.ProjectArea == "1" || project.ProjectArea == "2")
                {
                    var getViewGenerateTrustLists = (from x in Funs.DB.View_GenerateTrust where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
                    if (getViewGenerateTrustLists.Count() > 0)
                    {
                        var getUnit = BLL.Base_UnitService.GetUnit(this.CurrUser.UnitId);
                        if (getUnit == null || getUnit.UnitTypeId == "1" || getUnit.UnitTypeId == "2" || getUnit.UnitTypeId == "3")
                        {
                            GenerateTrust(getViewGenerateTrustLists);
                        }
                        else
                        {
                            var getUnitViewGenerateTrustLists = getViewGenerateTrustLists.Where(x => x.UnitId == this.CurrUser.UnitId);
                            if (getUnitViewGenerateTrustLists.Count() > 0)
                            {
                                // 当前单位未委托批
                                GenerateTrust(getUnitViewGenerateTrustLists.ToList());
                            }
                            else
                            {
                                Alert.ShowInTop("所属单位审核的点口已全部生成委托单!", MessageBoxIcon.Warning);
                            }
                        }
                        BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnGenerate, null);
                        this.BindGrid();
                    }
                    else
                    {
                        Alert.ShowInTop("已全部生成委托单!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    var getViewGenerateTrustLists = (from x in Funs.DB.View_GenerateTrust_FJ where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
                    if (getViewGenerateTrustLists.Count() > 0)
                    {
                        var getUnit = BLL.Base_UnitService.GetUnit(this.CurrUser.UnitId);
                        if (getUnit == null || getUnit.UnitTypeId == "1" || getUnit.UnitTypeId == "2" || getUnit.UnitTypeId == "3")
                        {
                            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);
                            }
                        }
                        BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_PointManageMenuId, Const.BtnGenerate, null);
                        this.BindGrid();
                    }
                    else
                    {
                        Alert.ShowInTop("已全部生成委托单!", MessageBoxIcon.Warning);
                    }
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 生成委托单-宁波
        /// 
        /// 
        private void GenerateTrust(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 area = BLL.Project_WorkAreaService.GetProject_WorkAreaByWorkAreaId(trust.WorkAreaId);
                string perfix = string.Empty;
                perfix = project.ProjectCode + "-" + unit.UnitCode + "-" + ndt.DetectionTypeCode + "-" + area.WorkAreaCode + "-";
                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.DetectionTypeId = trust.DetectionTypeId;
                BLL.Batch_BatchTrustService.AddBatchTrust(newBatchTrust);  // 新增委托单
                // 生成委托条件对比
                var generateTrustItem = from x in db.View_GenerateTrustItem
                                        where x.ProjectId == trust.ProjectId && x.InstallationId == trust.InstallationId
                                        && x.WorkAreaId == trust.WorkAreaId && x.UnitId == trust.UnitId
                                        && x.DetectionTypeId == trust.DetectionTypeId
                                        select x;
                string toPointBatch = string.Empty;
                // 生成委托明细,并回写点口明细信息
                foreach (var item in generateTrustItem)
                {
                    if (BLL.Batch_PointBatchService.GetIsGenerateTrust(item.PointBatchItemId)) ////生成委托单的条件判断
                    {
                        toPointBatch = toPointBatch + item.PointBatchId + ",";
                        Model.Batch_BatchTrustItem trustItem = new Model.Batch_BatchTrustItem
                        {
                            TrustBatchItemId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrustItem)),
                            TrustBatchId = trustBatchId,
                            PointBatchItemId = item.PointBatchItemId,
                            WeldJointId = item.WeldJointId,
                            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))
                {
                    List pointBatchList = Funs.GetStrListByStr(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);
        }
        /// 
        /// 生成委托单-福建
        /// 
        /// 
        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 ins = BLL.Project_InstallationService.GetProject_InstallationByInstallationId(trust.InstallationId);
                string perfix = string.Empty;
                perfix = unit.UnitCode + "-" + ins.InstallationCode + "-GD-" + ndt.DetectionTypeCode + "-";
                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.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.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)) ////生成委托单的条件判断
                    {
                        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 (generateTrustItem.Count() > 0)
                {
                    var batch = BLL.Batch_PointBatchService.GetPointBatchById(generateTrustItem.First().PointBatchId);
                    batch.IsTrust = true;
                    Funs.DB.SubmitChanges();
                }
                
                // 回写委托批对应点口信息
                if (!string.IsNullOrEmpty(toPointBatch))
                {
                    List pointBatchList = Funs.GetStrListByStr(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
    }
}