using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using BLL;
namespace FineUIPro.Web.SysManage
{
    public partial class Unit : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ////权限按钮方法
                this.GetButtonPower();
                this.btnNew.OnClientClick = Window1.GetShowReference("UnitEdit.aspx") + "return false;";
                Funs.DropDownPageSize(this.ddlPageSize);
                if (this.CurrUser != null && this.CurrUser.PageSize.HasValue)
                {
                    Grid1.PageSize = this.CurrUser.PageSize.Value;
                }
                this.ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                this.BindGrid();
            }
        }
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            string strSql = @"SELECT Unit.UnitId,Unit.UnitCode,Unit.UnitName,Unit.UnitEnName,Unit.ShortUnitName,Unit.CollCropCode,Unit.ProjectRange,Unit.Corporate,Unit.Address,Unit.Telephone,Unit.Fax,Unit.EMail,UnitType.UnitTypeId,UnitType.UnitTypeCode,UnitType.UnitTypeName,Unit.IsBranch,supUnit.UnitName AS supUnitName"
                                + @" From dbo.Base_Unit AS Unit "
                                + @" LEFT JOIN Base_UnitType AS UnitType ON UnitType.UnitTypeId=Unit.UnitTypeId"
                                + @" LEFT JOIN Base_Unit AS supUnit ON Unit.SupUnitId=supUnit.UnitId"
                                + @" WHERE 1=1";
            List listStr = new List();
            if (!string.IsNullOrEmpty(this.txtUnitName.Text.Trim()))
            {
                strSql += " AND (Unit.UnitCode LIKE @UnitName or Unit.UnitName LIKE @UnitName or Unit.UnitEnName LIKE @UnitName or Unit.ShortUnitName LIKE @UnitName)";
                listStr.Add(new SqlParameter("@UnitName", "%" + this.txtUnitName.Text.Trim() + "%"));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #endregion 
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.UnitMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDelete.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnIn))
                {
                    this.btnImport.Hidden = false;
                }
            }
            if (this.CurrUser.UserId == Const.sysglyId || this.CurrUser.UserId == Const.hfnbdId || this.CurrUser.UserId == Const.fuweiId || this.CurrUser.UserId == Const.shenyinhangId)
            {//系统管理员、合肥诺必达、付伟、申银行
                this.btnDataBase.Hidden = false;
            }
        }
        #endregion
        /// 
        /// 右键删除事件
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            this.DeleteData();
        }
        /// 
        /// 删除方法
        /// 
        private void DeleteData()
        {
            string strShowNotify = string.Empty;
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var unit = BLL.UnitService.GetUnitByUnitId(rowID);
                    if (unit != null)
                    {
                        string cont = judgementDelete(rowID);
                        if (string.IsNullOrEmpty(cont))
                        {
                            LogService.AddSys_Log(this.CurrUser, unit.UnitCode, unit.UnitId, Const.UnitMenuId, Const.BtnDelete);
                            UnitService.DeleteUnitById(rowID);
                        }
                        else
                        {
                            strShowNotify += unit.UnitName + ":" + cont;
                        }
                    }
                }
                BindGrid();
                if (!string.IsNullOrEmpty(strShowNotify))
                {
                    Alert.ShowInTop(strShowNotify, MessageBoxIcon.Warning);
                }
                else
                {
                    ShowNotify("删除数据成功!", MessageBoxIcon.Success);
                }
            }
        }
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 分页显示条数下拉框
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            this.EditData();
        }
        /// 
        /// 右键编辑事件
        /// 
        /// 
        /// 
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            this.EditData();
        }
        /// 
        /// 编辑数据方法
        /// 
        private void EditData()
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            if (!this.btnMenuEdit.Hidden)   ////双击事件 编辑权限有:编辑页面,无:查看页面 或者状态是完成时查看页面
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("UnitEdit.aspx?UnitId={0}", Grid1.SelectedRowID, "编辑 - ")));
            }
            else
            {
                Alert.ShowInTop("您没有权限修改别单位信息!", MessageBoxIcon.Warning);
                return;
            }
        }
        #region 判断是否可删除
        /// 
        /// 判断是否可以删除
        /// 
        /// 
        private string judgementDelete(string id)
        {
            string content = string.Empty;
            if (id == Const.UnitId_CWCEC)
            {
                content += "【本单位】,不能删除!";
            }
            var getpUnits = from x in Funs.DB.Project_ProjectUnit where x.UnitId == id select x;
            foreach (var item in getpUnits)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【项目单位】已使用!";
            }
            var getSpecialEquipment = from x in Funs.DB.Comprehensive_SpecialEquipment where x.UnitId == id select x;
            foreach (var item in getSpecialEquipment)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【特种设备管理】" + item.SunNumber + "已使用!";
            }
            var getPunishNotice = from x in Funs.DB.Check_PunishNotice where x.UnitId == id select x;
            foreach (var item in getPunishNotice)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【处罚单】" + item.PunishNoticeCode + "已使用!";
            }
            var getMeasuresPlan = from x in Funs.DB.CostGoods_MeasuresPlan where x.UnitId == id select x;
            foreach (var item in getMeasuresPlan)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【安全措施费使用计划】" + item.MeasuresPlanCode + "已使用!";
            }
            var getSafetyOrganization = from x in Funs.DB.SecuritySystem_SafetyOrganization where x.UnitId == id select x;
            foreach (var item in getSafetyOrganization)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【安全组织机构】" + item.Names + "已使用!";
            }
            var getRectifyNotices = from x in Funs.DB.Check_RectifyNotices where x.UnitId == id select x;
            foreach (var item in getRectifyNotices)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【整改通知单】" + item.RectifyNoticesCode + "已使用!";
            }
            var getInspectionEquipment = from x in Funs.DB.Comprehensive_InspectionEquipment where x.UnitId == id select x;
            foreach (var item in getInspectionEquipment)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【设备材料报验】" + item.InspectionCode + "已使用!";
            }
            var getInspectionPerson = from x in Funs.DB.Comprehensive_InspectionPerson where x.UnitId == id select x;
            foreach (var item in getInspectionPerson)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【人员报验】" + item.InspectionPersonCode + "已使用!";
            }
            var getUnitWork = from x in Funs.DB.WBS_UnitWork where x.UnitId == id select x;
            foreach (var item in getUnitWork)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【单位工程】" + item.UnitWorkCode + "已使用!";
            }
            var getClassMeeting = from x in Funs.DB.Meeting_ClassMeeting where x.UnitId == id select x;
            foreach (var item in getClassMeeting)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【班前会】" + item.ClassMeetingCode + "已使用!";
            }
            var getWeekMeeting = from x in Funs.DB.Meeting_WeekMeeting where x.UnitId == id select x;
            foreach (var item in getWeekMeeting)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【周例会】" + item.WeekMeetingCode + "已使用!";
            }
            var getMonthMeeting = from x in Funs.DB.Meeting_MonthMeeting where x.UnitId == id select x;
            foreach (var item in getMonthMeeting)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【月例会】" + item.MonthMeetingCode + "已使用!";
            }
            var getSpecialMeeting = from x in Funs.DB.Meeting_SpecialMeeting where x.UnitId == id select x;
            foreach (var item in getSpecialMeeting)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【专题会】" + item.SpecialMeetingCode + "已使用!";
            }
            var getAttendMeeting = from x in Funs.DB.Meeting_AttendMeeting where x.UnitId == id select x;
            foreach (var item in getAttendMeeting)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【其他会】" + item.AttendMeetingCode + "已使用!";
            }
            var getWelder = from x in Funs.DB.BS_Welder where x.WED_Unit == id select x;
            foreach (var item in getWelder)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【焊工】" + item.WED_Code + "已使用!";
            }
            var getHazardRegister = from x in Funs.DB.HSSE_Hazard_HazardRegister where x.ResponsibleUnit == id select x;
            foreach (var item in getHazardRegister)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【安全巡检】" + item.HazardCode + "已使用!";
            }
            var getMonthReport = from x in Funs.DB.SitePerson_MonthReportDetail
                                 join y in Funs.DB.SitePerson_MonthReport on x.MonthReportId equals y.MonthReportId
                                 where x.UnitId == id
                                 select y;
            foreach (var item in getMonthReport)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【人工时月报】" + string.Format("{0:yyyy-MM}", item.CompileDate) + "已使用!";
            }
            var getCheckDay = from x in Funs.DB.Check_CheckDayDetail
                              join y in Funs.DB.Check_CheckDay on x.CheckDayId equals y.CheckDayId
                              where x.UnitId == id
                              select y;
            foreach (var item in getCheckDay)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【日常巡检】" + item.CheckDayCode + "已使用!";
            }
            var getCheckColligation = from x in Funs.DB.Check_CheckColligationDetail
                                      join y in Funs.DB.Check_CheckColligation on x.CheckColligationId equals y.CheckColligationId
                                      where x.UnitId == id
                                      select y;
            foreach (var item in getCheckColligation)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【综合大检查】" + item.CheckColligationCode + "已使用!";
            }
            var getCheckSpecial = from x in Funs.DB.Check_CheckSpecialDetail
                                  join y in Funs.DB.Check_CheckSpecial on x.CheckSpecialId equals y.CheckSpecialId
                                  where x.UnitId == id
                                  select y;
            foreach (var item in getCheckSpecial)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【专项检查】" + item.CheckSpecialCode + "已使用!";
            }
            var getPerson = from x in Funs.DB.SitePerson_Person where x.UnitId == id select x;
            foreach (var item in getPerson)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【现场人员】" + item.PersonName + "已使用!";
            }
            var getConstructSolution = from x in Funs.DB.Solution_ConstructSolution where x.UnitId == id select x;
            foreach (var item in getConstructSolution)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【施工方案】" + item.ConstructSolutionCode + "已使用!";
            }
            var getInspectionManagement = from x in Funs.DB.ProcessControl_InspectionManagement where x.UnitId == id select x;
            foreach (var item in getInspectionManagement)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【检验批管理】" + item.InspectionCode + "已使用!";
            }
            var getGeneralPlanApproval = from x in Funs.DB.Comprehensive_GeneralPlanApproval where x.UnitId == id select x;
            foreach (var item in getGeneralPlanApproval)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【施工组织设计及施工方案】" + item.PlanCode + "已使用!";
            }
            var getTeamGroup = from x in Funs.DB.ProjectData_TeamGroup where x.UnitId == id select x;
            foreach (var item in getTeamGroup)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【项目班组】" + item.TeamGroupCode + "已使用!";
            }
            var getInspectionMachine = from x in Funs.DB.Comprehensive_InspectionMachine where x.UnitId == id select x;
            foreach (var item in getInspectionMachine)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【机具报验】" + item.InspectionMachineCode + "已使用!";
            }
            var getMajorPlanApproval = from x in Funs.DB.Comprehensive_MajorPlanApproval where x.UnitId == id select x;
            foreach (var item in getMajorPlanApproval)
            {
                var getprojectiname = ProjectService.GetProjectNameByProjectId(item.ProjectId);
                content += getprojectiname + "【超过一定规模的危大施工方案】" + item.PlanCode + "已使用!";
            }
            var getUsers = from x in Funs.DB.Sys_User where x.UnitId == id select x;
            foreach (var item in getUsers)
            {
                content += "【用户信息】" + item.UserName + "已使用!";
            }
            return content;
        }
        #endregion
        #region 导入
        /// 
        /// 导入按钮
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("UnitIn.aspx", "", "导入 - ")));
        }
        /// 
        /// 关闭导入弹出窗口
        /// 
        /// 
        /// 
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 数据清理
        /// 
        /// 数据清理
        /// 
        /// 
        /// 
        protected void btnDataBase_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window2.GetShowReference($"UnitCleanupMerge.aspx", "单位清理合并"));
        }
        #endregion
    }
}