using BLL;
using FineUIPro.Web.common.BaseInfo;
using Model;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.WeldingProcess.PMI
{
    public partial class PMIDelegationEdit : PageBase
    {
        #region 定义项
        /// 
        /// PMI委托主键
        /// 
        public string PMIDelegationId
        {
            get
            {
                return (string)ViewState["PMIDelegationId"];
            }
            set
            {
                ViewState["PMIDelegationId"] = value;
            }
        }
     
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.PMIDelegationId = Request.QueryString["PMIDelegationId"];
                BLL.Project_InstallationService.InitInstallationDropDownList(this.drpInstallationId, true, this.CurrUser.LoginProjectId, Resources.Lan.PleaseSelect);//装置
                BLL.Base_UnitService.InitUnitDropDownList(this.drpUnitId, true, BLL.Const.UnitType_5, Resources.Lan.PleaseSelect);//单位
                this.PageInfoLoad(); ///加载页面 
                this.txtDetectionMethod.Text = "PMI光谱分析";
                this.txtDetectionMethod.Enabled = false;
                var viewData=Funs.DB.View_PMI_DelegationDetails.Where(t=>t.PMIId==this.PMIDelegationId).ToList();
                this.BindGrid(viewData); ////初始化页面
                this.txtDelegationDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
        }
        #endregion
        #region 加载页面输入提交信息
        /// 
        /// 加载页面输入提交信息
        /// 
        private void PageInfoLoad()
        {
            var trust = Funs.DB.PMI_Delegation.FirstOrDefault(t=>t.Id==this.PMIDelegationId);
            if (trust != null)
            {
                //this.ProjectId = trust.ProjectId;
                this.txtDelegationNo.Text = trust.DelegationNo;
                if (trust.DelegationDate.HasValue)
                {
                    this.txtDelegationDate.Text = string.Format("{0:yyyy-MM-dd}", trust.DelegationDate);
                }
                if (!string.IsNullOrEmpty(trust.InstallationId))
                {
                    this.drpInstallationId.SelectedValue = trust.InstallationId;
                }
                if (!string.IsNullOrEmpty(trust.UnitId))
                {
                    this.drpUnitId.SelectedValue = trust.UnitId;
                }
                this.txtDetectionMethod.Text = "PMI光谱分析";
                this.txtDetectionStandard.Text = trust.DetectionStandard;
                if (!string.IsNullOrEmpty(trust.Tabler))
                {
                    this.txtTabler.Text = BLL.Sys_UserService.GetUserNameByUserId(trust.Tabler);
                }
                this.txtRemark.Text = trust.Remark;
            }
            else
            {
                this.txtTabler.Text = this.CurrUser.UserName;
                this.SimpleForm1.Reset(); //重置所有字段
            }
        }
        #endregion
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        private void BindGrid(List lists)
        {
            DataTable tb = this.LINQToDataTable(lists);
            Grid1.RecordCount = tb.Rows.Count;
            tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 查找需要热处理的焊口
        /// 
        /// 查找需要PMI处理的焊口
        /// 
        /// 
        /// 
        protected void ckSelect_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.drpUnitId.SelectedValue) && this.drpUnitId.SelectedValue != BLL.Const._Null)
            {
                string weldJointIds = string.Empty;
                for (int i = 0; i < Grid1.Rows.Count; i++)
                {
                    string jotId = Grid1.DataKeys[i][0].ToString();
                    weldJointIds += jotId + "|";
                }
                if (weldJointIds != string.Empty)
                {
                    weldJointIds = weldJointIds.Substring(0, weldJointIds.Length - 1);
                }
            
                //url查询
                string window = String.Format($"PMISelectList.aspx?unitId={this.drpUnitId.SelectedValue}&projectId={this.CurrUser.LoginProjectId}&weldJointIds={weldJointIds}", "编辑 - ");
                PageContext.RegisterStartupScript(Window1.GetSaveStateReference(hdItemsString.ClientID) + Window1.GetShowReference(window));
            }
            else
            {
                Alert.ShowInTop(Resources.Lan.PleaseSelectCompany, MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region Grid 关闭弹出窗口事件
        /// 
        /// 关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            string weldJointIds = string.Empty;
            if (!string.IsNullOrEmpty(hdItemsString.Text))
            {
                weldJointIds = hdItemsString.Text.Substring(0, hdItemsString.Text.LastIndexOf('|'));
            
                var lists = GetGridDataTable(weldJointIds);
                this.BindGrid(lists);
                if (string.IsNullOrEmpty(this.txtDelegationNo.Text))
                {
                    //获取单位
                    string unitCode = Funs.DB.Base_Unit.FirstOrDefault(t => t.UnitId == drpUnitId.SelectedValue)?.UnitCode;
                    //获取区域code
                    var workdAreaIdList = lists.Select(t => t.WorkAreaId).ToList();
                    var workAreaCode = Funs.DB.Project_WorkArea.AsQueryable().Where(t => workdAreaIdList.Contains(t.WorkAreaId)).Distinct().FirstOrDefault()?.WorkAreaCode;
                    string perfix = string.Empty;
                    perfix = $"PMI-{unitCode}-{workAreaCode}-PI-";
                    this.txtDelegationNo.Text = BLL.SQLHelper.RunProcNewId("SpGetNewCode", "dbo.PMI_Delegation", "DelegationNo", this.CurrUser.LoginProjectId, perfix);
                }
            }
        }
        #endregion
        #region PMI委托 提交事件
        /// 
        /// 编辑PMI委托
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.PMIDelegationId, Const.BtnSave))
            {
                
                try
                {
                    SaveData();
                }
                catch (Exception ex)
                {
                    BLL.ErrLogInfo.WriteLog(ex);
                    ShowNotify(Resources.Lan.PMIError, MessageBoxIcon.Error);
                    return;
                }
                ShowNotify(Resources.Lan.SaveSuccessfully, MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(this.PMIDelegationId)
                + ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        void SaveData()
        {
           
            if (!string.IsNullOrEmpty(this.PMIDelegationId))
            {
                
                var isExists = Funs.DB.PMI_Delegation.Any(t => t.DelegationNo == this.txtDelegationNo.Text.Trim()
                && t.ProjectId == this.CurrUser.LoginProjectId && t.Id!=this.PMIDelegationId);
                if (isExists)
                {
                    ShowNotify(Resources.Lan.PMICodeExists, MessageBoxIcon.Warning);
                    return;
                }
                var result = Funs.DB.PMI_Delegation.FirstOrDefault(t => t.Id == this.PMIDelegationId);
                if(result==null)
                {
                    ShowNotify(Resources.Lan.PMICodeNotExists, MessageBoxIcon.Warning);
                    return;
                }
                result.DelegationNo = txtDelegationNo.Text.Trim();
                result.DelegationDate = !string.IsNullOrEmpty(txtDelegationDate.Text.Trim()) ? DateTime.Parse(txtDelegationDate.Text.Trim()) : DateTime.Now;
                result.InstallationId = drpInstallationId.SelectedValue;
                result.UnitId = drpUnitId.SelectedValue;
                result.ProjectId = this.CurrUser.LoginProjectId;
                result.Remark = txtRemark.Text.Trim();
                result.DetectionStandard = txtDetectionStandard.Text.Trim();
                result.Tabler = this.CurrUser.UserId;
                
            }
            else
            {
                var isExists = Funs.DB.PMI_Delegation.Any(t => t.DelegationNo == this.txtDelegationNo.Text.Trim() && t.ProjectId == this.CurrUser.LoginProjectId);
                if (isExists)
                {
                    ShowNotify(Resources.Lan.PMICodeExists, MessageBoxIcon.Warning);
                    return;
                }
                var pmiModel = new Model.PMI_Delegation();
                pmiModel.DelegationNo = txtDelegationNo.Text.Trim();
                pmiModel.DelegationDate = !string.IsNullOrEmpty(txtDelegationDate.Text.Trim()) ? DateTime.Parse(txtDelegationDate.Text.Trim()) : DateTime.Now;
                pmiModel.InstallationId = drpInstallationId.SelectedValue;
                pmiModel.UnitId = drpUnitId.SelectedValue;
                pmiModel.ProjectId = this.CurrUser.LoginProjectId;
                pmiModel.Remark = txtRemark.Text.Trim();
                pmiModel.DetectionStandard = txtDetectionStandard.Text.Trim();
                pmiModel.Tabler = this.CurrUser.UserId;
                pmiModel.Id = SQLHelper.GetNewID(typeof(Model.PMI_Delegation));
                this.PMIDelegationId = pmiModel.Id;
                pmiModel.CreatedTime = DateTime.Now;
                Funs.DB.PMI_Delegation.InsertOnSubmit(pmiModel);
            }
            
            //先删除明细表
            var deleteEntity = Funs.DB.PMI_DelegationDetails.Where(t => t.PMIId == this.PMIDelegationId).ToList();
            if (deleteEntity.Any())
            {
                Funs.DB.PMI_DelegationDetails.DeleteAllOnSubmit(deleteEntity);
            }
            //再插入明细表
            this.CollectGridJointInfo();
            Funs.DB.SubmitChanges();
        }
        #endregion
        #region 获取Grid里面的数据返回集合
        private List GetGridDataTable(string weldJointIds)
        {
            string[] arr = weldJointIds.Split('|');
            JArray mergedData = Grid1.GetMergedData();
            var result = Funs.DB.View_Pipeline_WeldJoint.Select(t => new View_PMI_DelegationDetails {
                   WeldJointId= t.WeldJointId,
                PipelineCode= t.PipelineCode,
                ProjectId= t.ProjectId,
                 Acceptance="",
                    QualityNo="",
                WeldJointCode=t.WeldJointCode,
                Specification=t.Specification,
                MaterialCode=t.MaterialCode,
                WorkAreaId=t.WorkAreaId,
                Status=0,
                PMIId=this.PMIDelegationId
            }).Where(t => arr.Contains(t.WeldJointId)).ToList();
            result.ForEach(item =>
            {
                item.Id = SQLHelper.GetNewID(typeof(PMI_DelegationDetails));
            });
            if (mergedData.Count == 0)
            {
                return result;
            }
            else
            {
                foreach (JObject mergedRow in mergedData)
                {
                    JObject values = mergedRow.Value("values");
                    Model.View_PMI_DelegationDetails newTrustItem = new Model.View_PMI_DelegationDetails();
                    newTrustItem.Id = values.Value("Id").ToString();
                    newTrustItem.PipelineCode = values.Value("PipelineCode").ToString();
                    newTrustItem.WeldJointId = values.Value("WeldJointId").ToString();
                    newTrustItem.Acceptance = values.Value("Acceptance").ToString();
                    newTrustItem.QualityNo = values.Value("QualityNo").ToString();
                    newTrustItem.WeldJointCode = values.Value("WeldJointCode").ToString();
                    newTrustItem.Specification =HttpUtility.HtmlDecode(values.Value("Specification").ToString());
                    newTrustItem.MaterialCode = values.Value("MaterialCode").ToString();
                    newTrustItem.Status = 0;
                    newTrustItem.PMIId = this.PMIDelegationId;
                    result.Add(newTrustItem);
                }
            } 
            
            return result;
        }
        #endregion 
        #region 收集Grid页面信息,提交明细
        /// 
        /// 收集Grid页面信息,提交明细
        /// 
        /// 
        private void CollectGridJointInfo()
        {
            var listData = new List();
            JArray mergedData = Grid1.GetMergedData();
            foreach (JObject mergedRow in mergedData)
            {
                JObject values = mergedRow.Value("values");
                Model.PMI_DelegationDetails newTrustItem = new Model.PMI_DelegationDetails();
                newTrustItem.Id = SQLHelper.GetNewID(typeof(PMI_DelegationDetails));
                newTrustItem.JointId = values.Value("WeldJointId").ToString();
                newTrustItem.Acceptance = values.Value("Acceptance").ToString();
                newTrustItem.QualityNo = values.Value("QualityNo").ToString();
                newTrustItem.Status = 0;
                newTrustItem.CheckTime = DateTime.Now;
                newTrustItem.ReportTime = DateTime.Now;
                newTrustItem.PMIId = this.PMIDelegationId;
                listData.Add(newTrustItem);
            }
            Funs.DB.PMI_DelegationDetails.InsertAllOnSubmit(listData);
        }
        #endregion     
        #region 右键删除事件
        /// 
        /// 右键删除事件
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.hdItemsString.Text))
            {
                this.hdItemsString.Text = this.hdItemsString.Text.Substring(0, this.hdItemsString.Text.LastIndexOf('|'));
            }
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                var listData = GetGridDataTable("");
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var item = listData.FirstOrDefault(x => x.WeldJointId == rowID);
                    if (item != null)
                    {
                        listData.Remove(item);
                    }
                }
                BindGrid(listData);
                ShowNotify(Resources.Lan.DeletedSuccessfully, MessageBoxIcon.Success);
            }
        }
        #endregion        
    }
}