using BLL;
using BLL.CQMS.Comprehensive;
using System;
using System.Linq;
namespace FineUIPro.Web.CQMS.Comprehensive
{
    public partial class QualityAccidentEdit : PageBase
    {
        #region 定义变量
        /// 
        /// 主键
        /// 
        public string QualityAccidentId
        {
            get
            {
                return (string)ViewState["QualityAccidentId"];
            }
            set
            {
                ViewState["QualityAccidentId"] = value;
            }
        }
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                BLL.UnitWorkService.InitUnitWorkDownList(this.drpUnitWorkId, this.CurrUser.LoginProjectId, false);
                BLL.UnitService.InitUnitDownList(this.drpUnit, this.CurrUser.LoginProjectId, true);
                LoadAuditSelect();
                this.agree.Hidden = true;
                this.options.Hidden = true;
                this.btnSave.Hidden = true;
                this.btnSubmit.Hidden = true;
                
                this.QualityAccidentId = Request.Params["QualityAccidentId"];
                Model.Comprehensive_QualityAccident pressurePipe = BLL.QualityAccidentService.GetQualityAccidentById(this.QualityAccidentId);
                if (pressurePipe != null)
                {
                    this.hdAttachUrl.Text = this.QualityAccidentId;
                    this.QualityAccidentId = pressurePipe.QualityAccidentId;
                    this.txtCorrectiveActions.Text = pressurePipe.CorrectiveActions;
                    this.txtPlace.Text = pressurePipe.Place;
                    this.txtDirectEconomicLoss.Text = pressurePipe.DirectEconomicLoss;
                    this.txtRemedialMeasures.Text = pressurePipe.RemedialMeasures;
                    this.txtResponsibilityDetermination.Text = pressurePipe.ResponsibilityDetermination;
                    this.txtTime.Text = pressurePipe.Time.HasValue ? string.Format("{0:yyyy-MM-dd}", pressurePipe.Time) : "";
                    this.drpUnit.SelectedValue = pressurePipe.UnitId;
                    if (!string.IsNullOrEmpty(pressurePipe.UnitWorkId))
                    {
                        this.drpUnitWorkId.SelectedValueArray = pressurePipe.UnitWorkId.Split(',');
                    }
                    var currApprove = QualityAccidentApproveService.GetCurrentApprove(pressurePipe.QualityAccidentId);
                    if (currApprove != null)
                    {
                        this.drpAudit.SelectedValue = currApprove.ApproveMan;
                        //重新编制  编制人 可以 显示 提交 保存按钮
                        if (currApprove.ApproveType == BLL.Const.Comprehensive_ReCompile && pressurePipe.CompileMan == CurrUser.UserId)
                        {
                            this.btnSubmit.Hidden = false;
                            this.btnSave.Hidden = false;
                        }//审核状态 审核人 可以显示  提交 保存按钮
                        else if (currApprove.ApproveType == BLL.Const.Comprehensive_Audit && currApprove.ApproveMan == CurrUser.UserId)
                        {
                            //审核状态不可编辑
                            Readonly();
                            this.agree.Hidden = false;
                            this.options.Hidden = false;
                            this.btnSubmit.Hidden = false;
                            this.btnSave.Hidden = false;
                        }
                    }//没有当前审核人,已完成状态 或者 待提交状态
                    else
                    {
                        if (pressurePipe.Status == BLL.Const.Comprehensive_Compile && pressurePipe.CompileMan == CurrUser.UserId)
                        {
                            this.btnSubmit.Hidden = false;
                            this.btnSave.Hidden = false;
                        }
                    }
                }
                else
                {
                    this.txtTime.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                    this.btnSave.Hidden = false;
                    this.btnSubmit.Hidden = false;
                }
            }
        }
        /// 
        /// 禁止编辑
        /// 
        public void Readonly()
        {
            this.txtCorrectiveActions.Readonly = true;
            this.txtDirectEconomicLoss.Readonly = true;
            this.txtPlace.Readonly = true;
            this.txtRemedialMeasures.Readonly = true;
            this.txtResponsibilityDetermination.Readonly = true;
            this.txtTime.Readonly = true;
            this.drpUnit.Readonly = true;
            this.drpUnitWorkId.Readonly = true; 
            this.drpAudit.Readonly = true; 
            //this.btnAttach.Enabled = false; 
           
        }
        /// 
        /// 加载专业工程师
        /// 
        public void LoadAuditSelect()
        {
            var db = Funs.DB;
            var userList = from x in db.Sys_User
                           join y in db.Project_ProjectUnit
                           on x.UnitId equals y.UnitId
                           join p in db.Project_ProjectUser
                           on x.UserId equals p.UserId
                           where y.UnitId == Const.UnitId_TCC && p.ProjectId == CurrUser.LoginProjectId && y.ProjectId == CurrUser.LoginProjectId
                           where p.RoleId.Contains(Const.ZBCNEngineer)
                           select new { UserId = x.UserId, UserName = x.UserName };
            drpAudit.DataValueField = "UserId";
            drpAudit.DataTextField = "UserName";
            this.drpAudit.DataSource = userList.ToList();
            this.drpAudit.DataBind();
        }
        #endregion
        #region 保存
        /// 
        /// 保存方法
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                Model.Comprehensive_QualityAccident pressurePipe = new Model.Comprehensive_QualityAccident();
                pressurePipe.ProjectId = this.CurrUser.LoginProjectId;
                if (!string.IsNullOrEmpty(this.drpAudit.SelectedValue))
                {
                    pressurePipe.AuditMan = drpAudit.SelectedValue;
                }   //审核人
                if (!string.IsNullOrEmpty(this.txtTime.Text))
                {
                    pressurePipe.Time = Convert.ToDateTime(this.txtTime.Text);
                }
                else
                {
                    pressurePipe.Time = DateTime.Now;
                }
                pressurePipe.Place = this.txtPlace.Text;
                pressurePipe.DirectEconomicLoss = this.txtDirectEconomicLoss.Text;
                pressurePipe.RemedialMeasures = this.txtRemedialMeasures.Text;
                pressurePipe.ResponsibilityDetermination = this.txtResponsibilityDetermination.Text;
                pressurePipe.CorrectiveActions = this.txtCorrectiveActions.Text;
                pressurePipe.UnitId = this.drpUnit.SelectedValue;
                string ids = string.Empty;
                var lists = this.drpUnitWorkId.SelectedValueArray;
                foreach (var item in lists)
                {
                    ids += item + ",";
                }
                if (!string.IsNullOrEmpty(ids))
                {
                    ids = ids.Substring(0, ids.LastIndexOf(","));
                }
                pressurePipe.UnitWorkId = ids;
                if (string.IsNullOrEmpty(this.QualityAccidentId))
                {
                    if (!string.IsNullOrEmpty(this.hdAttachUrl.Text))
                    {
                        pressurePipe.QualityAccidentId = this.hdAttachUrl.Text;
                    }
                    else
                    {
                        pressurePipe.QualityAccidentId = SQLHelper.GetNewID(typeof(Model.Comprehensive_QualityAccident));
                        this.hdAttachUrl.Text = pressurePipe.QualityAccidentId;
                    }
                    var sour = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == pressurePipe.QualityAccidentId);
                    if (sour == null || string.IsNullOrEmpty(sour.AttachUrl))
                    {
                        Alert.ShowInTop("请上传附件!", MessageBoxIcon.Warning);
                        return;
                    }
                    pressurePipe.CompileMan = this.CurrUser.UserId;
                    pressurePipe.CompileDate = DateTime.Now;
                    pressurePipe.Status = BLL.Const.Comprehensive_Compile;
                    BLL.QualityAccidentService.AddQualityAccident(pressurePipe);
                }
                else
                {
                    pressurePipe.QualityAccidentId = this.QualityAccidentId;
                    var sour = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == this.QualityAccidentId);
                    if (sour == null || string.IsNullOrEmpty(sour.AttachUrl))
                    {
                        Alert.ShowInTop("请上传附件!", MessageBoxIcon.Warning);
                        return;
                    }
                    var model = Funs.DB.Comprehensive_QualityAccident.Where(u => u.QualityAccidentId == this.QualityAccidentId).FirstOrDefault();
                    if (model != null)
                    {
                        pressurePipe.Status = model.Status;
                    }
                    BLL.QualityAccidentService.UpdateQualityAccident(pressurePipe);
                }  
                ShowNotify("保存成功!", MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.ShowInTop("请选择所属单位!", MessageBoxIcon.Warning);
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                Model.Comprehensive_QualityAccident pressurePipe = new Model.Comprehensive_QualityAccident();
                pressurePipe.ProjectId = this.CurrUser.LoginProjectId;
                if (!string.IsNullOrEmpty(this.drpAudit.SelectedValue))
                {
                    pressurePipe.AuditMan = drpAudit.SelectedValue;
                }   //审核人
                if (!string.IsNullOrEmpty(this.txtTime.Text))
                {
                    pressurePipe.Time = Convert.ToDateTime(this.txtTime.Text);
                }
                else
                {
                    pressurePipe.Time = DateTime.Now;
                }
                pressurePipe.Place = this.txtPlace.Text;
                pressurePipe.DirectEconomicLoss = this.txtDirectEconomicLoss.Text;
                pressurePipe.RemedialMeasures = this.txtRemedialMeasures.Text;
                pressurePipe.ResponsibilityDetermination = this.txtResponsibilityDetermination.Text;
                pressurePipe.CorrectiveActions = this.txtCorrectiveActions.Text;
                pressurePipe.UnitId = this.drpUnit.SelectedValue;
                string ids = string.Empty;
                var lists = this.drpUnitWorkId.SelectedValueArray;
                foreach (var item in lists)
                {
                    ids += item + ",";
                }
                if (!string.IsNullOrEmpty(ids))
                {
                    ids = ids.Substring(0, ids.LastIndexOf(","));
                }
                pressurePipe.UnitWorkId = ids;
                if (string.IsNullOrEmpty(this.QualityAccidentId))
                {
                    if (!string.IsNullOrEmpty(this.hdAttachUrl.Text))
                    {
                        pressurePipe.QualityAccidentId = this.hdAttachUrl.Text;
                    }
                    else
                    {
                        pressurePipe.QualityAccidentId = SQLHelper.GetNewID(typeof(Model.Comprehensive_QualityAccident));
                        this.hdAttachUrl.Text = pressurePipe.QualityAccidentId;
                    }
                    var sour = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == pressurePipe.QualityAccidentId);
                    if (sour == null || string.IsNullOrEmpty(sour.AttachUrl))
                    {
                        Alert.ShowInTop("请上传附件!", MessageBoxIcon.Warning);
                        return;
                    }
                    pressurePipe.CompileMan = this.CurrUser.UserId;
                    pressurePipe.CompileDate = DateTime.Now;
                    pressurePipe.Status = BLL.Const.Comprehensive_Audit;
                    BLL.QualityAccidentService.AddQualityAccident(pressurePipe);
                }
                else
                {
                    pressurePipe.QualityAccidentId = this.QualityAccidentId;
                    var sour = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == this.QualityAccidentId);
                    if (sour == null || string.IsNullOrEmpty(sour.AttachUrl))
                    {
                        Alert.ShowInTop("请上传附件!", MessageBoxIcon.Warning);
                        return;
                    }
                    // BLL.QualityAccidentService.UpdateQualityAccident(pressurePipe);
                    var oldQualityAccident = Funs.DB.Comprehensive_QualityAccident.Where(u => u.QualityAccidentId == this.QualityAccidentId).FirstOrDefault();
                    if (oldQualityAccident == null) //数据库没有记录 直接点提交 当前状态为 审核状态
                    {
                        pressurePipe.CompileMan = this.CurrUser.UserId;
                        pressurePipe.CompileDate = DateTime.Now;
                        pressurePipe.Status = BLL.Const.Comprehensive_Audit;
                        BLL.QualityAccidentService.AddQualityAccident(pressurePipe);
                    }
                    else
                    {
                        pressurePipe.CompileMan = oldQualityAccident.CompileMan;
                        pressurePipe.CompileDate = oldQualityAccident.CompileDate;
                        if (oldQualityAccident.Status == BLL.Const.Comprehensive_Compile)//编制状态提交变审核
                        {
                            pressurePipe.Status = BLL.Const.Comprehensive_Audit;
                        }
                        else if (oldQualityAccident.Status == BLL.Const.Comprehensive_ReCompile)//重新编制状态提交变审核
                        {
                            pressurePipe.Status = BLL.Const.Comprehensive_Audit;
                        }
                        else //审核状态  提交 变 完成 或者 重新编制
                        {
                            if (Convert.ToBoolean(rblIsAgree.SelectedValue))
                            {
                                pressurePipe.Status = BLL.Const.Comprehensive_Complete;
                            }
                            else
                            {
                                pressurePipe.Status = BLL.Const.Comprehensive_ReCompile;
                            }
                        }
                        BLL.QualityAccidentService.UpdateQualityAccident(pressurePipe);
                    }
                }
                #region 审核记录
                var currApprove = QualityAccidentApproveService.GetCurrentApprove(pressurePipe.QualityAccidentId);
                if (currApprove == null) //为获取到为 当前编制状态 直接提交
                {
                    var approve = new Model.Comprehensive_QualityAccidentApprove();
                    approve.QualityAccidentId = pressurePipe.QualityAccidentId;
                    approve.ApproveMan = this.CurrUser.UserId;
                    approve.ApproveType = Const.Comprehensive_Compile;
                    approve.ApproveDate = DateTime.Now;
                    QualityAccidentApproveService.EditApprove(approve);  //新增编制记录
                    Model.Comprehensive_QualityAccidentApprove newApprove = new Model.Comprehensive_QualityAccidentApprove();
                    newApprove.QualityAccidentId = pressurePipe.QualityAccidentId;
                    newApprove.ApproveMan = this.drpAudit.SelectedValue;
                    newApprove.ApproveType = Const.InspectionManagement_Audit;
                    QualityAccidentApproveService.EditApprove(newApprove); //新增专业工程师审核记录
                }
                else if (currApprove.ApproveMan == CurrUser.UserId)
                {
                    if (currApprove.ApproveType == BLL.Const.Comprehensive_ReCompile)
                    {
                        currApprove.ApproveDate = DateTime.Now;
                        //currApprove.IsAgree = true;
                        QualityAccidentApproveService.EditApprove(currApprove); //新增专业工程师审核记录
                        Model.Comprehensive_QualityAccidentApprove newApprove = new Model.Comprehensive_QualityAccidentApprove();
                        newApprove.QualityAccidentId = pressurePipe.QualityAccidentId;
                        newApprove.ApproveMan = this.drpAudit.SelectedValue;
                        newApprove.ApproveType = Const.InspectionManagement_Audit;
                        QualityAccidentApproveService.EditApprove(newApprove); //新增专业工程师审核记录
                    }
                    else
                    {
                        currApprove.ApproveDate = DateTime.Now;  //更新审核时间
                        currApprove.IsAgree = Convert.ToBoolean(rblIsAgree.SelectedValue);
                        currApprove.ApproveIdea = this.txtidea.Text;
                        QualityAccidentApproveService.EditApprove(currApprove);
                        if (Convert.ToBoolean(rblIsAgree.SelectedValue))  //同意时 审批完成
                        {
                            Model.Comprehensive_QualityAccidentApprove reApprove = new Model.Comprehensive_QualityAccidentApprove();
                            reApprove.QualityAccidentId = currApprove.QualityAccidentId;
                            reApprove.ApproveDate = DateTime.Now.AddSeconds(10);
                            reApprove.ApproveMan = CurrUser.UserId;
                            reApprove.ApproveType = Const.Comprehensive_Complete;
                            reApprove.ApproveIdea = txtidea.Text;
                            QualityAccidentApproveService.EditApprove(reApprove);
                        }
                        else
                        {
                            Model.Comprehensive_QualityAccidentApprove reApprove = new Model.Comprehensive_QualityAccidentApprove();
                            reApprove.QualityAccidentId = currApprove.QualityAccidentId;
                            reApprove.ApproveMan = pressurePipe.CompileMan;
                            reApprove.ApproveType = Const.Comprehensive_ReCompile;
                            QualityAccidentApproveService.EditApprove(reApprove);
                        }
                    }
                }
                #endregion
                ShowNotify("保存成功!", MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.ShowInTop("请选择所属单位!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 附件上传
        /// 
        /// 附件上传
        /// 
        /// 
        /// 
        protected void btnAttach_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.hdAttachUrl.Text))   //新增记录
            {
                this.hdAttachUrl.Text = SQLHelper.GetNewID(typeof(Model.Comprehensive_QualityAccident));
            }
            Model.Comprehensive_QualityAccident pressurePipe = BLL.QualityAccidentService.GetQualityAccidentById(this.QualityAccidentId);
            if (pressurePipe == null || ((pressurePipe.CompileMan == CurrUser.UserId && pressurePipe.Status == BLL.Const.Comprehensive_Compile) || (pressurePipe.CompileMan == CurrUser.UserId && pressurePipe.Status == BLL.Const.Comprehensive_ReCompile)))
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=0&toKeyId={0}&path=FileUpload/CQMS/pressurePipe&menuId={1}", this.hdAttachUrl.Text, BLL.Const.QualityAccidentMenuId)));
            }
            else
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=-1&toKeyId={0}&path=FileUpload/CQMS/pressurePipe&menuId={1}", this.hdAttachUrl.Text, BLL.Const.QualityAccidentMenuId)));
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (Request.Params["value"] == BLL.Const._Null)
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.QualityAccidentMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnSave.Hidden = false;
                }
            }
        }
        #endregion
    }
}