using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FineUIPro.Web.CQMS.ProcessControl
{
    public partial class InspectionNoticeEdit : PageBase
    {


        #region 加载
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                BLL.UnitService.InitUnitByProjectIdUnitTypeDropDownList(drpUnit, this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, true);//施工分包商
                drpUnit.DataValueField = "UnitId";
                drpUnit.DataTextField = "UnitName";
               
                drpUnit.DataBind();
                drpUnit.SelectedValue = this.CurrUser.UnitId;
                if ( this.CurrUser.UnitId==Const.UnitId_CD|| this.CurrUser.UserId ==Const.hfnbdId)
                {
                    drpUnit.Enabled= true;
                }
                else
                {
                    drpUnit.Enabled = false ;
                }
                drpMainSendUnit.DataValueField = "UnitId";
                drpMainSendUnit.DataTextField = "UnitName";
                drpMainSendUnit.DataSource = Funs.DB.Base_Unit.Where(x => x.UnitId == Const.UnitId_CD).ToList();
                drpMainSendUnit.DataBind();
                drpMainSendUnit.SelectedValue = this.CurrUser.UnitId;

                this.drpWorkArea.DataValueField = "Value";
                this.drpWorkArea.DataTextField = "Text";
                this.drpWorkArea.DataSource = BLL.UnitWorkService.GetUnitWork(CurrUser.LoginProjectId);
                this.drpWorkArea.DataBind();
                Funs.FineUIPleaseSelect(drpWorkArea);

                BLL.CNProfessionalService.InitCNProfessionalDownList(this.drpCNProfessionalId, true);//专业
                                       
                //抄送单位
                gvCCUnit.DataSource = UnitService.GetUnitByProjectIdList(CurrUser.LoginProjectId);
                gvCCUnit.DataBind();
 


				this.hdInspectionNoticeId.Text = Request.Params["inspectionId"];
                if (!string.IsNullOrEmpty(this.hdInspectionNoticeId.Text))
                {
                    Model.ProcessControl_InspectionManagement inspectionManagement = BLL.InspectionManagementService.GetInspectionManagementById(this.hdInspectionNoticeId.Text.Trim());
                    if (inspectionManagement != null)
                    {


                        if (inspectionManagement.Status == "0")
                        {
                            this.txtUnqualifiedReason.Text = inspectionManagement.UnqualifiedReason;
                            this.txtUnqualifiedReason.Hidden = false; 
                            this.dpRePlanComplateDate.Hidden = false; 
                            this.txtUnqualifiedOption.Text = inspectionManagement.UnqualifiedOption;
                            this.txtUnqualifiedOption.Hidden = false;
                        }
                        if (!string.IsNullOrEmpty(inspectionManagement.UnitWorkId))
                        {
                            this.drpWorkArea.SelectedValue = inspectionManagement.UnitWorkId;
                        }
                        if (!string.IsNullOrEmpty(inspectionManagement.UnitId))
                        {
                            this.drpUnit.SelectedValue = inspectionManagement.UnitId;
                        }
                        if (!string.IsNullOrEmpty(inspectionManagement.CNProfessionalId))
                        {
                            this.drpCNProfessionalId.SelectedValue = inspectionManagement.CNProfessionalId;
                        }
                        this.txtAcceptanceSite.Text = inspectionManagement.AcceptanceSite;
                        this.txtAcceptanceCheckMan.Text = inspectionManagement.AcceptanceCheckMan;
                        this.txtNoticeCode.Text = inspectionManagement.NoticeCode;

                        if (!string.IsNullOrEmpty(inspectionManagement.MainSendUnitId))
                        {
                            drpMainSendUnit.SelectedValue = inspectionManagement.MainSendUnitId;
                        }
                        if (!string.IsNullOrEmpty(inspectionManagement.CCUnitIds))
                        {
                            txtCCUnit.Values = inspectionManagement.CCUnitIds.Split(',');
                        }                         
                        if (inspectionManagement.PlanComplateDate != null)
                        {
                            this.dpPlanComplateDate.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss}", inspectionManagement.PlanComplateDate);
                        }
                        if (inspectionManagement.RePlanComplateDate != null)
                        {
                            this.dpRePlanComplateDate.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss}", inspectionManagement.RePlanComplateDate);
                        }
                        this.Grid1.DataSource = BLL.InspectionManagementDetailService.GetInspectionDetails(this.hdInspectionNoticeId.Text.Trim());
                        this.Grid1.DataBind();

                        if (inspectionManagement.Status == "3" ||(inspectionManagement.Status=="1"&&inspectionManagement.CompileMan!=CurrUser.UserId))
                        {
                            this.drpWorkArea.Enabled = false;
                            this.drpUnit.Enabled = false;
                            this.drpCNProfessionalId.Enabled = false;
                            this.txtNoticeCode.Enabled = false;
                            this.txtAcceptanceSite.Enabled = false;
                            this.txtAcceptanceCheckMan.Enabled = false;
                            this.dpPlanComplateDate.Enabled = false;
                            this.drpMainSendUnit.Enabled = false;
                            this.txtCCUnit.EnableEdit = false;
                            this.Toolbar4.Hidden = true;
                            this.btnSubmit.Hidden = true;
                            this.btnSave.Hidden = true;
                            this.txtCCUnit.Enabled = false;
                            this.Grid1.Columns[9].Hidden = true;
                        }
                         
                    }
                }
            }
        }
        #endregion


        protected void drpWorkArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (drpWorkArea.SelectedValue != BLL.Const._Null && drpCNProfessionalId.SelectedValue != BLL.Const._Null)
            {
                string workAreaCode = "";
                if (!string.IsNullOrEmpty(this.drpWorkArea.SelectedText))
                {
                    workAreaCode = this.drpWorkArea.SelectedText.Split('-')[0];
                }
                string professtionId = this.drpCNProfessionalId.SelectedValue;
                var professional = BLL.CNProfessionalService.GetCNProfessional(professtionId);
                string code = workAreaCode + "-" + professional.CNProfessionalCode + "-";
                this.txtNoticeCode.Text = BLL.SQLHelper.RunProcNewId("SpGetNewCode5ByProjectId", "dbo.ProcessControl_InspectionManagement", "NoticeCode", this.CurrUser.LoginProjectId, code);

            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bool changeAudit = true;
            if (this.drpUnit.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("请先选择施工分包商!", MessageBoxIcon.Warning);
                return;
            }
            if (this.drpCNProfessionalId.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("请先选择专业!", MessageBoxIcon.Warning);
                return;
			}
			if (this.Grid1.Rows.Count == 0)
            {
                Alert.ShowInTop("请先选择共检内容!", MessageBoxIcon.Warning);
                return;
            }
            Model.ProcessControl_InspectionManagement inspectionManagement = new Model.ProcessControl_InspectionManagement();
            inspectionManagement.ProjectId = this.CurrUser.LoginProjectId;
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                inspectionManagement.UnitId = this.drpUnit.SelectedValue;
            }
            if (this.drpWorkArea.SelectedValue != BLL.Const._Null)
            {
                inspectionManagement.UnitWorkId = this.drpWorkArea.SelectedValue;
            }

            if (this.drpCNProfessionalId.SelectedValue != BLL.Const._Null)
            {
                inspectionManagement.CNProfessionalId = this.drpCNProfessionalId.SelectedValue;
            }
            inspectionManagement.MainSendUnitId = drpMainSendUnit.SelectedValue;
            if (!string.IsNullOrWhiteSpace(String.Join(",", txtCCUnit.Values)))
            {
                inspectionManagement.CCUnitIds = String.Join(",", txtCCUnit.Values);
            }
            inspectionManagement.NoticeCode = this.txtNoticeCode.Text.Trim();
            inspectionManagement.AcceptanceSite = this.txtAcceptanceSite.Text.Trim();
            inspectionManagement.AcceptanceCheckMan = this.txtAcceptanceCheckMan.Text.Trim();
            inspectionManagement.Status = "3";
			inspectionManagement.AuditMan = this.CurrUser.UserId;

			if (!string.IsNullOrEmpty(this.dpPlanComplateDate.Text.Trim()))
            {
                inspectionManagement.PlanComplateDate = Convert.ToDateTime(this.dpPlanComplateDate.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.dpRePlanComplateDate.Text.Trim()))
            {
                inspectionManagement.RePlanComplateDate = Convert.ToDateTime(this.dpRePlanComplateDate.Text.Trim());
            }
            
            if (string.IsNullOrEmpty(Request.Params["inspectionId"]))
            {
                inspectionManagement.CompileMan = this.CurrUser.UserId;
                inspectionManagement.CompileDate = DateTime.Now;
                if (!string.IsNullOrEmpty(this.hdInspectionNoticeId.Text.Trim()))
                {
                    inspectionManagement.InspectionId = this.hdInspectionNoticeId.Text.Trim();
                }
                else
                {
                    inspectionManagement.InspectionId = SQLHelper.GetNewID(typeof(Model.ProcessControl_InspectionManagement));
                    this.hdInspectionNoticeId.Text = inspectionManagement.InspectionId;
                }
                BLL.InspectionManagementService.AddInspectionManagement(inspectionManagement);
            }
            else
            {
                Model.ProcessControl_InspectionManagement oldInspectionManagement = BLL.InspectionManagementService.GetInspectionManagementById(this.hdInspectionNoticeId.Text.Trim());
                inspectionManagement.AttachUrl2 = oldInspectionManagement.AttachUrl2;
                inspectionManagement.InspectionCode = oldInspectionManagement.InspectionCode;
				inspectionManagement.InspectionId = this.hdInspectionNoticeId.Text.Trim();                 
                inspectionManagement.Status = "3";        
				BLL.InspectionManagementService.UpdateInspectionManagement(inspectionManagement);
                BLL.InspectionManagementDetailService.DeleteAllInspectionDetail(inspectionManagement.InspectionId);
            }
            var details = jerqueSaveList();
            foreach (var detail in details)
            {
                detail.InspectionId = inspectionManagement.InspectionId;
                BLL.InspectionManagementDetailService.AddInspectionDetail(detail);
            }
            ShowNotify("提交成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #region 保存
        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.drpUnit.SelectedValue==BLL.Const._Null)
            {
                Alert.ShowInTop("请先选择施工分包商!", MessageBoxIcon.Warning);
                return;
            }
            if (this.drpCNProfessionalId.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("请先选择专业!", MessageBoxIcon.Warning);
                return;
            }
            if (this.Grid1.Rows.Count == 0)
            {
                Alert.ShowInTop("请先选择共检内容!", MessageBoxIcon.Warning);
                return;
            }
            Model.ProcessControl_InspectionManagement inspectionManagement = new Model.ProcessControl_InspectionManagement();
            inspectionManagement.ProjectId = this.CurrUser.LoginProjectId;
            if (drpWorkArea.SelectedValue !=BLL.Const._Null)
            {
                inspectionManagement.UnitWorkId = drpWorkArea.SelectedValue;
            }
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                inspectionManagement.UnitId = this.drpUnit.SelectedValue;
            }
            if (this.drpCNProfessionalId.SelectedValue != BLL.Const._Null)
            {
                inspectionManagement.CNProfessionalId = this.drpCNProfessionalId.SelectedValue;
            }
            inspectionManagement.MainSendUnitId = drpMainSendUnit.SelectedValue;
            if (!string.IsNullOrWhiteSpace(String.Join(",", txtCCUnit.Values)))
            {
                inspectionManagement.CCUnitIds = String.Join(",", txtCCUnit.Values);
            }
            inspectionManagement.NoticeCode = this.txtNoticeCode.Text.Trim();
            inspectionManagement.AcceptanceSite = this.txtAcceptanceSite.Text.Trim();
            inspectionManagement.AcceptanceCheckMan = this.txtAcceptanceCheckMan.Text.Trim();
            inspectionManagement.Status = "1";
            if (!string.IsNullOrEmpty(this.dpPlanComplateDate.Text.Trim()))
            {
                inspectionManagement.PlanComplateDate = Convert.ToDateTime(this.dpPlanComplateDate.Text.Trim());
            }
            if (string.IsNullOrEmpty(Request.Params["inspectionId"]))
            {
                inspectionManagement.CompileMan = this.CurrUser.UserId;
                inspectionManagement.CompileDate = DateTime.Now;
                if (!string.IsNullOrEmpty(this.hdInspectionNoticeId.Text.Trim()))
                {
                    inspectionManagement.InspectionId = this.hdInspectionNoticeId.Text.Trim();
                }
                else
                {
                    inspectionManagement.InspectionId = SQLHelper.GetNewID(typeof(Model.ProcessControl_InspectionManagement));
                    this.hdInspectionNoticeId.Text = inspectionManagement.InspectionId;
                }
                BLL.InspectionManagementService.AddInspectionManagement(inspectionManagement);
            }
            else
            {
                Model.ProcessControl_InspectionManagement oldInspectionManagement = BLL.InspectionManagementService.GetInspectionManagementById(this.hdInspectionNoticeId.Text.Trim());
                inspectionManagement.AttachUrl2 = oldInspectionManagement.AttachUrl2;
                inspectionManagement.InspectionId = this.hdInspectionNoticeId.Text.Trim(); 
                BLL.InspectionManagementService.UpdateInspectionManagement(inspectionManagement);
                BLL.InspectionManagementDetailService.DeleteAllInspectionDetail(inspectionManagement.InspectionId);
            }
            var details = jerqueSaveList();
            foreach (var detail in details)
            {
                detail.InspectionId = inspectionManagement.InspectionId;
                BLL.InspectionManagementDetailService.AddInspectionDetail(detail);
            }
            ShowNotify("保存成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion

        #region 附件上传
        /// <summary>
        /// 附件上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAttach_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.hdInspectionNoticeId.Text))   //新增记录
            {
                this.hdInspectionNoticeId.Text = SQLHelper.GetNewID(typeof(Model.ProcessControl_InspectionManagement));
            }
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=0&toKeyId={0}&path=FileUpload/CQMS/InspectionManagement&menuId={1}", this.hdInspectionNoticeId.Text, BLL.Const.InspectionNoticeMenuId)));
        }
        #endregion

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string itemId = Grid1.DataKeys[e.RowIndex][0].ToString();
            List<Model.ProcessControl_InspectionManagementDetail> details = jerqueSaveList();
            if (e.CommandName == "delete")
            {
                foreach (Model.ProcessControl_InspectionManagementDetail detail in details)
                {
                    if (detail.InspectionDetailId == itemId)
                    {
                        details.Remove(detail);
                        break;
                    }
                }
                Grid1.DataSource = details;
                Grid1.DataBind();
            }
        }

        #region 搜索
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNew_Click(object sender, EventArgs e)
        {
            if (this.drpCNProfessionalId.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("请先选择专业!", MessageBoxIcon.Warning);
                return;
            }
            string window = String.Format("ShowUnitWork.aspx?CNPrefessionalId={0}&WorkAreaId={1}", this.drpCNProfessionalId.SelectedValue, this.drpWorkArea.SelectedValue, "查找 - ");
            PageContext.RegisterStartupScript(Window1.GetSaveStateReference(hdItemsString.ClientID) + Window1.GetShowReference(window));
        }
        #endregion

        #region  保存Grid集合
        /// <summary>
        /// 检查并保存集合
        /// </summary>
        private List<Model.ProcessControl_InspectionManagementDetail> jerqueSaveList()
        {
            List<Model.ProcessControl_InspectionManagementDetail> details = new List<Model.ProcessControl_InspectionManagementDetail>();
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value<JObject>("values");
                int i = mergedRow.Value<int>("index");
                Model.ProcessControl_InspectionManagementDetail detail = new Model.ProcessControl_InspectionManagementDetail();
                detail.InspectionDetailId = this.Grid1.Rows[i].RowID;
                detail.UnitWorkId = values.Value<string>("UnitWorkId");
                detail.Branch = values.Value<string>("Branch");
                detail.ControlPointType = this.Grid1.Rows[i].DataKeys[1].ToString();
                string createDate = values.Value<string>("CreateDate");
                if (!string.IsNullOrEmpty(createDate))
                {
                    detail.CreateDate = Convert.ToDateTime(createDate);
                }
             
                details.Add(detail);
            }
            return details;
        }
        #endregion

        #region 关闭弹出窗口
        /// <summary>
        /// 关闭弹出窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {

            if (!string.IsNullOrEmpty(hdItemsString.Text))
            {
                string[] ids = hdItemsString.Text.Split(',');
                int i = 1;
                var details = jerqueSaveList();
                foreach (var id in ids)
                {
                    var oldDetail = details.FirstOrDefault(x => x.ControlPointType == id);
                    if (oldDetail == null)   //添加集合没有的新纪录
                    {
                        Model.ProcessControl_InspectionManagementDetail detail = new Model.ProcessControl_InspectionManagementDetail();
                        detail.InspectionDetailId = SQLHelper.GetNewID();
                        var breakdownProject = BLL.BreakdownProjectService.GetBreakdownProjectById(id);
                        if (breakdownProject != null)
                        {
                            var divisionProject = BLL.DivisionProjectService.GetDivisionProjectById(breakdownProject.DivisionProjectId);
                            if (divisionProject != null)
                            {
                                detail.UnitWorkId = divisionProject.UnitWorkId;
                                detail.Branch = divisionProject.DivisionProjectId;
                            }
                        }
                        detail.ControlPointType = id;
                        detail.CreateDate = DateTime.Now.AddMinutes(i);
                        details.Add(detail);
                    }
                    i++;
                }
                this.Grid1.DataSource = details;
                this.Grid1.DataBind();
            }
        }
        #endregion

        #region 获取按钮权限
        /// <summary>
        /// 获取按钮权限
        /// </summary>
        /// <param name="button"></param>
        /// <returns></returns>
        private void GetButtonPower()
        {
            if (Request.Params["value"] == BLL.Const._Null)
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.InspectionNoticeMenuId);
            if (buttonList.Count > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnSave.Hidden = false;
                }
            }
        }
        #endregion

        #region 转换字符串
        /// <summary>
        /// 获取单位工程
        /// </summary>
        /// <param name="UnitWorkId"></param>
        /// <returns></returns>
        protected string ConvertUnitWork(object UnitWorkId)
        {
            string name = string.Empty;
            if (UnitWorkId != null)
            {
                Model.WBS_UnitWork unitWork = BLL.UnitWorkService.GetUnitWorkByUnitWorkId(UnitWorkId.ToString());
                if (unitWork != null)
                {
                    name = unitWork.UnitWorkName;
                }
            }
            return name;
        }

        /// <summary>
        /// 获取分部
        /// </summary>
        /// <param name="Branch"></param>
        /// <returns></returns>
        protected string ConvertBranch(object Branch)
        {
            string name = string.Empty;
            if (Branch != null)
            {
                var branch = BLL.DivisionProjectService.GetDivisionProjectById(Branch.ToString());
                if (branch != null)
                {
                    name = branch.DivisionName;
                }
            }
            return name;
        }

        /// <summary>
        /// 获取控制点内容
        /// </summary>
        /// <param name="ControlPointType"></param>
        /// <returns></returns>
        protected string ConvertControlPointType(object ControlPointType)
        {
            string name = string.Empty;
            if (ControlPointType != null)
            {
                var controlPointType = BLL.BreakdownProjectService.GetBreakdownProjectById(ControlPointType.ToString());
                if (controlPointType != null)
                {
                    name = controlPointType.BreakdownName;
                }
            }
            return name;
        }

        /// <summary>
        /// 获取控制点等级
        /// </summary>
        /// <param name="ControlPointType"></param>
        /// <returns></returns>
        protected string ConvertClass(object ControlPointType)
        {
            string name = string.Empty;
            if (ControlPointType != null)
            {
                var controlPointType = BLL.BreakdownProjectService.GetBreakdownProjectById(ControlPointType.ToString());
                if (controlPointType != null)
                {
                    name = controlPointType.Class;
                }
            }
            return name;
        }
        #endregion
    }
}