using BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.ZHGL.Supervise
{
    public partial class SuperviseCheckReportEdit : PageBase
    {
        #region 定义变量
        /// 
        /// 主键
        /// 
        public string SuperviseCheckReportId
        {
            get
            {
                return (string)ViewState["SuperviseCheckReportId"];
            }
            set
            {
                ViewState["SuperviseCheckReportId"] = value;
            }
        }
        /// 
        /// 定义集合
        /// 
        private static List superviseCheckReportItems = new List();
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdItemId.Text = string.Empty;
                hdAttachUrl.Text = string.Empty;
                hdId.Text = string.Empty;
                btnClose.OnClientClick = ActiveWindow.GetHideReference();
                superviseCheckReportItems.Clear();
                if (Request.Params["type"] != "-1")
                {
                    ////权限按钮方法
                    this.GetButtonPower();
                }
                BLL.ProjectService.InitProjectDropDownList(this.ddlProjectId, true);
                BLL.UnitService.InitUnitDropDownList(this.ddlUnitId, this.ddlProjectId.SelectedValue, true);
                BLL.UnitService.InitBranchUnitDropDownList(this.ddlCheckUnitId, false);
                Funs.FineUIPleaseSelect(this.drpCheckMainType);
                //Funs.FineUIPleaseSelect(this.drpCheckType);
                this.SuperviseCheckReportId = Request.Params["SuperviseCheckReportId"];
                var superviseCheckReport = BLL.SuperviseCheckReportService.GetSuperviseCheckReportById(this.SuperviseCheckReportId);
                if (superviseCheckReport != null)
                {
                    this.txtSuperviseCheckReportCode.Text = superviseCheckReport.SuperviseCheckReportCode;
                    if (superviseCheckReport.CheckDate != null)
                    {
                        this.dpkCheckDate.Text = string.Format("{0:yyyy-MM-dd}", superviseCheckReport.CheckDate);
                    }
                    if (!string.IsNullOrWhiteSpace(superviseCheckReport.CheckMainType))
                    {
                        this.drpCheckMainType.SelectedValue = superviseCheckReport.CheckMainType;
                        BLL.SuperviseCheckTypeService.InitCheckTypeDropDownListByMainType(this.drpCheckType, superviseCheckReport.CheckMainType, false);
                    }
                    if (!string.IsNullOrWhiteSpace(superviseCheckReport.CheckType))
                    {
                        this.drpCheckType.SelectedValue = superviseCheckReport.CheckType;
                    }
                    if (!string.IsNullOrWhiteSpace(superviseCheckReport.ProjectId))
                    {
                        this.ddlProjectId.SelectedValue = superviseCheckReport.ProjectId;
                        this.ddlUnitId.Items.Clear();
                        BLL.UnitService.InitUnitDropDownList(this.ddlUnitId, this.ddlProjectId.SelectedValue, true);
                        if (!string.IsNullOrWhiteSpace(superviseCheckReport.UnitId))
                        {
                            this.ddlUnitId.SelectedValue = superviseCheckReport.UnitId;
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(superviseCheckReport.CheckUnitId))
                    {
                        this.ddlCheckUnitId.SelectedValue = superviseCheckReport.CheckUnitId;
                    }
                    this.txtCheckTeam.Text = superviseCheckReport.CheckTeam;
                    superviseCheckReportItems = (from x in Funs.DB.View_Supervise_SuperviseCheckReportItem where x.SuperviseCheckReportId == this.SuperviseCheckReportId orderby x.RectifyCode select x).ToList();
                    var report = BLL.SuperviseCheckReportService.GetSuperviseCheckReportById(this.SuperviseCheckReportId);
                    if (report != null && report.IsIssued == "1")    //已下发
                    {
                        this.btnSave.Hidden = true;
                        this.btnSelect.Hidden = true;
                        Grid1.Columns[10].Hidden = true;
                    }
                }
                else
                {
                    var thisUnit = BLL.CommonService.GetIsThisUnit();
                    this.ddlCheckUnitId.SelectedValue = thisUnit.UnitId;
                    this.txtCheckTeam.Text = BLL.UnitService.GetUnitNameByUnitId(this.CurrUser.UnitId) + this.CurrUser.UserName;
                    this.dpkCheckDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                }
                Grid1.DataSource = superviseCheckReportItems;
                Grid1.DataBind();
                GetCheckItem();
            }
        }
        /// 
        /// 检查大类下拉加载
        /// 
        /// 
        /// 
        protected void drpCheckMainType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //检查类别
            BLL.SuperviseCheckTypeService.InitCheckTypeDropDownListByMainType(this.drpCheckType, this.drpCheckMainType.SelectedValue, false);
        }
        private void GetCheckItem()
        {
            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                var item = superviseCheckReportItems.FirstOrDefault(x => x.SuperviseCheckReportItemId == Grid1.Rows[i].Values[7].ToString());
                if (item != null)
                {
                    CheckBoxField checkField = (CheckBoxField)Grid1.FindColumn("ckbIsSelected");
                    if (item.IsSelected == true)
                    {
                        //Grid1.Rows[i].Values[6] = "True";
                        checkField.SetCheckedState(i, true);
                    }
                }
            }
        }
        #endregion
        #region Grid行点击事件
        /// 
        /// Grid行事件
        /// 
        /// 
        /// 
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string rowID = Grid1.DataKeys[e.RowIndex][0].ToString();
            if (e.CommandName == "IsSelected")
            {
                CheckBoxField checkField = (CheckBoxField)Grid1.FindColumn("ckbIsSelected");
                if (checkField.GetCheckedState(e.RowIndex))
                {
                    hdId.Text = rowID;
                    PageContext.RegisterStartupScript(Window1.GetSaveStateReference(hdAttachUrl.ClientID)
              + Window1.GetShowReference("ShowFileUpload.aspx"));
                }
            }
            if (e.CommandName == "Attach")
            {
                var item = superviseCheckReportItems.FirstOrDefault(x => x.SuperviseCheckReportItemId == Grid1.Rows[e.RowIndex].Values[7].ToString());
                if (item != null)
                {
                    PageBase.ShowFileEvent(item.AttachUrl);
                }
            }
            if (e.CommandName == "Delete")
            {
                jerqueSaveList();
                superviseCheckReportItems = (from x in superviseCheckReportItems where x.SuperviseCheckReportItemId != rowID select x).ToList();
                Grid1.DataSource = superviseCheckReportItems;
                Grid1.DataBind();
                GetCheckItem();
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
        }
        #endregion
        #region 选择按钮
        /// 
        /// 选择按钮
        /// 
        /// 
        /// 
        protected void btnSelect_Click(object sender, EventArgs e)
        {
            jerqueSaveList();
            string lists = string.Empty;
            foreach (var item in superviseCheckReportItems)
            {
                lists += item.RectifyItemId + ",";
            }
            if (!string.IsNullOrWhiteSpace(lists))
            {
                lists = lists.Substring(0, lists.LastIndexOf(","));
            }
            string type = this.drpCheckMainType.SelectedValue;
            string window = String.Format("ShowRectifyItem.aspx?lists={0}&type={1}", lists, type, "选择 - ");
            PageContext.RegisterStartupScript(Window2.GetSaveStateReference(hdItemId.ClientID)
              + Window2.GetShowReference(window));
        }
        #endregion
        #region 关闭窗口
        /// 
        /// 关闭窗口
        /// 
        /// 
        /// 
        protected void Window2_Close(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(hdItemId.Text))
            {
                if (superviseCheckReportItems.Count == 0)
                {
                    List itemIds = hdItemId.Text.Split(',').ToList();
                    var rectifyItem = from x in Funs.DB.View_Technique_RectifyItem where itemIds.Contains(x.RectifyItemId) orderby x.RectifyCode select x;
                    foreach (var item in rectifyItem)
                    {
                        Model.View_Supervise_SuperviseCheckReportItem superviseCheckReportItem = new Model.View_Supervise_SuperviseCheckReportItem
                        {
                            SuperviseCheckReportItemId = SQLHelper.GetNewID(typeof(Model.Supervise_SuperviseCheckReportItem)),
                            SuperviseCheckReportId = this.SuperviseCheckReportId,
                            RectifyItemId = item.RectifyItemId,
                            HazardSourcePoint = item.HazardSourcePoint,
                            RiskAnalysis = item.RiskAnalysis,
                            RiskPrevention = item.RiskPrevention,
                            SimilarRisk = item.SimilarRisk,
                            RectifyName = item.RectifyName,
                            RectifyCode = item.RectifyCode,
                            IsSelected = false
                        };
                        superviseCheckReportItems.Add(superviseCheckReportItem);
                    }
                }
                else
                {
                    List itemIds = hdItemId.Text.Split(',').ToList();
                    List superviseCheckReportItemsRectifyItemIds = superviseCheckReportItems.Select(x => x.RectifyItemId).ToList();
                    foreach (var item in itemIds)
                    {
                        if (!superviseCheckReportItemsRectifyItemIds.Contains(item))
                        {
                            var rectifyItem = (from x in Funs.DB.View_Technique_RectifyItem where x.RectifyItemId == item orderby x.RectifyCode select x).FirstOrDefault();
                            if (rectifyItem != null)
                            {
                                Model.View_Supervise_SuperviseCheckReportItem superviseCheckReportItem = new Model.View_Supervise_SuperviseCheckReportItem
                                {
                                    SuperviseCheckReportItemId = SQLHelper.GetNewID(typeof(Model.Supervise_SuperviseCheckReportItem)),
                                    SuperviseCheckReportId = this.SuperviseCheckReportId,
                                    RectifyItemId = rectifyItem.RectifyItemId,
                                    HazardSourcePoint = rectifyItem.HazardSourcePoint,
                                    RiskAnalysis = rectifyItem.RiskAnalysis,
                                    RiskPrevention = rectifyItem.RiskPrevention,
                                    SimilarRisk = rectifyItem.SimilarRisk,
                                    RectifyName = rectifyItem.RectifyName,
                                    RectifyCode = rectifyItem.RectifyCode,
                                    IsSelected = false
                                };
                                superviseCheckReportItems.Add(superviseCheckReportItem);
                            }
                        }
                    }
                    superviseCheckReportItems = (from x in superviseCheckReportItems
                                                 join y in Funs.DB.View_Technique_RectifyItem
                                                 on x.RectifyItemId equals y.RectifyItemId
                                                 orderby y.RectifyCode
                                                 select x).ToList();
                }
                Grid1.DataSource = superviseCheckReportItems;
                Grid1.DataBind();
                hdItemId.Text = string.Empty;
            }
        }
        #endregion
        #region 保存按钮
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.drpCheckMainType.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("检查大类不能为空!", MessageBoxIcon.Warning);
                return;
            }
            if (this.drpCheckType.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("检查类别不能为空!", MessageBoxIcon.Warning);
                return;
            }
            if (this.ddlCheckUnitId.SelectedValue == BLL.Const._Null)
            {
                Alert.ShowInTop("检查单位不能为空!", MessageBoxIcon.Warning);
                return;
            }
            Model.Supervise_SuperviseCheckReport superviseCheckReport = new Model.Supervise_SuperviseCheckReport
            {
                SuperviseCheckReportCode = this.txtSuperviseCheckReportCode.Text.Trim()
            };
            if (!string.IsNullOrWhiteSpace(this.dpkCheckDate.Text.Trim()))
            {
                superviseCheckReport.CheckDate = Convert.ToDateTime(this.dpkCheckDate.Text.Trim());
            }
            if (this.drpCheckType.SelectedValue != BLL.Const._Null)
            {
                superviseCheckReport.CheckType = this.drpCheckType.SelectedValue;
            }
            if (this.drpCheckMainType.SelectedValue != BLL.Const._Null)
            {
                superviseCheckReport.CheckMainType = this.drpCheckMainType.SelectedValue;
            }
            if (this.ddlProjectId.SelectedValue != BLL.Const._Null)
            {
                superviseCheckReport.ProjectId = this.ddlProjectId.SelectedValue;
            }
            if (this.ddlUnitId.SelectedValue != BLL.Const._Null)
            {
                superviseCheckReport.UnitId = this.ddlUnitId.SelectedValue;
            }
            if (this.ddlCheckUnitId.SelectedValue != BLL.Const._Null)
            {
                superviseCheckReport.CheckUnitId = this.ddlCheckUnitId.SelectedValue;
            }
            superviseCheckReport.CheckTeam = this.txtCheckTeam.Text.Trim();
            if (string.IsNullOrWhiteSpace(this.SuperviseCheckReportId))
            {
                superviseCheckReport.SuperviseCheckReportId = SQLHelper.GetNewID(typeof(Model.Supervise_SuperviseCheckReport));
                SuperviseCheckReportId = superviseCheckReport.SuperviseCheckReportId;
                BLL.SuperviseCheckReportService.AddSuperviseCheckReport(superviseCheckReport);
                BLL.LogService.AddSys_Log(this.CurrUser, superviseCheckReport.SuperviseCheckReportCode, superviseCheckReport.SuperviseCheckReportId, BLL.Const.SuperviseCheckReportMenuId, Const.BtnAdd);
            }
            else
            {
                var report = BLL.SuperviseCheckReportService.GetSuperviseCheckReportById(this.SuperviseCheckReportId);
                if (report.IsIssued == "1")    //已下发
                {
                    ShowNotify("已下发检查整改,无法修改!", MessageBoxIcon.Warning);
                    return;
                }
                superviseCheckReport.SuperviseCheckReportId = this.SuperviseCheckReportId;
                BLL.SuperviseCheckReportService.UpdateSuperviseCheckReport(superviseCheckReport);
                BLL.SuperviseCheckReportItemService.DeleteSuperviseCheckReportItemBySuperviseCheckReportId(this.SuperviseCheckReportId);
                BLL.LogService.AddSys_Log(this.CurrUser, superviseCheckReport.SuperviseCheckReportCode, superviseCheckReport.SuperviseCheckReportId, BLL.Const.SuperviseCheckReportMenuId, Const.BtnModify);
            }
            jerqueSaveList();
            foreach (var item in superviseCheckReportItems)
            {
                Model.Supervise_SuperviseCheckReportItem superviseCheckReportItem = new Model.Supervise_SuperviseCheckReportItem
                {
                    SuperviseCheckReportItemId = item.SuperviseCheckReportItemId,
                    SuperviseCheckReportId = superviseCheckReport.SuperviseCheckReportId,
                    RectifyItemId = item.RectifyItemId,
                    IsSelected = item.IsSelected,
                    AttachUrl = item.AttachUrl
                };
                BLL.SuperviseCheckReportItemService.AddSuperviseCheckReportItem(superviseCheckReportItem);
            }
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion
        #region 关闭弹出窗
        /// 
        /// 关闭弹出窗
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, EventArgs e)
        {
            jerqueSaveList();
            if (!string.IsNullOrWhiteSpace(hdAttachUrl.Text))
            {
                var item = superviseCheckReportItems.FirstOrDefault(x => x.SuperviseCheckReportItemId == hdId.Text);
                item.AttachUrl = hdAttachUrl.Text;
                item.AttachUrlName = hdAttachUrl.Text.Substring((hdAttachUrl.Text.LastIndexOf("~") + 1), (hdAttachUrl.Text.Length - hdAttachUrl.Text.LastIndexOf("~") - 1));
            }
            Grid1.DataSource = superviseCheckReportItems;
            Grid1.DataBind();
            GetCheckItem();
            hdId.Text = string.Empty;
            hdAttachUrl.Text = string.Empty;
        }
        #endregion
        #region 保存集合
        /// 
        /// 保存集合
        /// 
        private void jerqueSaveList()
        {
            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                if (Grid1.Rows[i].Values[7] != null && Grid1.Rows[i].Values[7].ToString() != "")
                {
                    var item = superviseCheckReportItems.FirstOrDefault(e => e.SuperviseCheckReportItemId == Grid1.Rows[i].Values[7].ToString());
                    //item.IsSelected = ((System.Web.UI.WebControls.CheckBox)(Grid1.Rows[i].FindControl("ckbIsSelected"))).Checked;
                    CheckBoxField checkField = (CheckBoxField)Grid1.FindColumn("ckbIsSelected");
                    item.IsSelected = checkField.GetCheckedState(i);
                    item.AttachUrl = Grid1.Rows[i].Values[8].ToString();
                }
            }
        }
        #endregion
        #region 验证检查编号是否存在
        /// 
        /// 验证检查编号是否存在
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            var standard = Funs.DB.Supervise_SuperviseCheckReport.FirstOrDefault(x => x.SuperviseCheckReportCode == this.txtSuperviseCheckReportCode.Text.Trim() && (x.SuperviseCheckReportId != this.SuperviseCheckReportId || (this.SuperviseCheckReportId == null && x.SuperviseCheckReportId != null)));
            if (standard != null)
            {
                ShowNotify("输入的检查编号已存在!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.SuperviseCheckReportMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnSave.Hidden = false;
                }
            }
        }
        #endregion
        protected void ddlProjectId_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlUnitId.Items.Clear();
            BLL.UnitService.InitUnitDropDownList(this.ddlUnitId, this.ddlProjectId.SelectedValue, true);
        }
        #region 附件上传
        /// 
        /// 上传附件
        /// 
        /// 
        /// 
        protected void btnAttachUrl_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.SuperviseCheckReportId))
            {
                if (this.drpCheckMainType.SelectedValue == BLL.Const._Null)
                {
                    Alert.ShowInTop("检查大类不能为空!", MessageBoxIcon.Warning);
                    return;
                }
                if (this.drpCheckType.SelectedValue == BLL.Const._Null)
                {
                    Alert.ShowInTop("检查类别不能为空!", MessageBoxIcon.Warning);
                    return;
                }
                if (this.ddlCheckUnitId.SelectedValue == BLL.Const._Null)
                {
                    Alert.ShowInTop("检查单位不能为空!", MessageBoxIcon.Warning);
                    return;
                }
                Model.Supervise_SuperviseCheckReport superviseCheckReport = new Model.Supervise_SuperviseCheckReport
                {
                    SuperviseCheckReportCode = this.txtSuperviseCheckReportCode.Text.Trim()
                };
                if (!string.IsNullOrWhiteSpace(this.dpkCheckDate.Text.Trim()))
                {
                    superviseCheckReport.CheckDate = Convert.ToDateTime(this.dpkCheckDate.Text.Trim());
                }
                if (this.drpCheckMainType.SelectedValue != BLL.Const._Null)
                {
                    superviseCheckReport.CheckMainType = this.drpCheckMainType.SelectedValue;
                }
                if (this.drpCheckType.SelectedValue != BLL.Const._Null)
                {
                    superviseCheckReport.CheckType = this.drpCheckType.SelectedValue;
                }
                if (this.ddlProjectId.SelectedValue != BLL.Const._Null)
                {
                    superviseCheckReport.ProjectId = this.ddlProjectId.SelectedValue;
                }
                if (this.ddlUnitId.SelectedValue != BLL.Const._Null)
                {
                    superviseCheckReport.UnitId = this.ddlUnitId.SelectedValue;
                }
                if (this.ddlCheckUnitId.SelectedValue != BLL.Const._Null)
                {
                    superviseCheckReport.CheckUnitId = this.ddlCheckUnitId.SelectedValue;
                }
                superviseCheckReport.CheckTeam = this.txtCheckTeam.Text.Trim();
                if (string.IsNullOrWhiteSpace(this.SuperviseCheckReportId))
                {
                    superviseCheckReport.SuperviseCheckReportId = SQLHelper.GetNewID(typeof(Model.Supervise_SuperviseCheckReport));
                    SuperviseCheckReportId = superviseCheckReport.SuperviseCheckReportId;
                    BLL.SuperviseCheckReportService.AddSuperviseCheckReport(superviseCheckReport);
                    BLL.LogService.AddSys_Log(this.CurrUser, superviseCheckReport.SuperviseCheckReportCode, superviseCheckReport.SuperviseCheckReportId, BLL.Const.SuperviseCheckReportMenuId, Const.BtnAdd);
                }
                else
                {
                    var report = BLL.SuperviseCheckReportService.GetSuperviseCheckReportById(this.SuperviseCheckReportId);
                    if (report.IsIssued == "1")    //已下发
                    {
                        ShowNotify("已下发检查整改,无法修改!", MessageBoxIcon.Warning);
                        return;
                    }
                    superviseCheckReport.SuperviseCheckReportId = this.SuperviseCheckReportId;
                    BLL.SuperviseCheckReportService.UpdateSuperviseCheckReport(superviseCheckReport);
                    BLL.SuperviseCheckReportItemService.DeleteSuperviseCheckReportItemBySuperviseCheckReportId(this.SuperviseCheckReportId);
                    BLL.LogService.AddSys_Log(this.CurrUser, superviseCheckReport.SuperviseCheckReportCode, superviseCheckReport.SuperviseCheckReportId, BLL.Const.SuperviseCheckReportMenuId, Const.BtnModify);
                }
                jerqueSaveList();
                foreach (var item in superviseCheckReportItems)
                {
                    Model.Supervise_SuperviseCheckReportItem superviseCheckReportItem = new Model.Supervise_SuperviseCheckReportItem
                    {
                        SuperviseCheckReportItemId = item.SuperviseCheckReportItemId,
                        SuperviseCheckReportId = superviseCheckReport.SuperviseCheckReportId,
                        RectifyItemId = item.RectifyItemId,
                        IsSelected = item.IsSelected,
                        AttachUrl = item.AttachUrl
                    };
                    BLL.SuperviseCheckReportItemService.AddSuperviseCheckReportItem(superviseCheckReportItem);
                }
            }
            if (btnSave.Hidden == true)
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?toKeyId={0}&path=FileUpload/SuperviseCheckReportEdit&type=-1&menuId={1}", SuperviseCheckReportId, BLL.Const.SuperviseCheckReportMenuId)));
            }
            else
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?toKeyId={0}&path=FileUpload/SuperviseCheckReportEdit&menuId={1}", SuperviseCheckReportId, BLL.Const.SuperviseCheckReportMenuId)));
            }
        }
        #endregion
    }
}