using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
namespace FineUIPro.Web.CQMS.ProcessControl
{
    public partial class InspectionManagement : PageBase
    {
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                BLL.CNProfessionalService.InitCNProfessionalDownList(this.drpCNProfessional, true);//专业
                BLL.UnitService.InitUnitByProjectIdUnitTypeDropDownList(drpUnit, this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, true);//施工分包商
                BindGrid();
            }
        }
        /// 
        /// 数据绑定
        /// 
        public void BindGrid()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT P.InspectionId,P.ProjectId,P.UnitId,P.CNProfessionalId,P.UnitWorkId,U.UnitName,C.ProfessionalName,P.NoticeCode,UnitWork.UnitWorkName,DP.DivisionName AS Branch,BP.BreakdownName AS ControlPointType,BP.Class,P.AcceptanceSite,P.AcceptanceCheckMan,(CASE WHEN IsOnceQualified='True' THEN '是' ELSE '否' END)AS IsOnceQualified,P.InspectionCode,P.InspectionDate,P.CompileDate ");
            sb.Append("FROM ProcessControl_InspectionManagement AS P ");
            sb.Append("LEFT JOIN Base_Unit AS U ON U.UnitId = P.UnitId ");
            sb.Append("LEFT JOIN Base_CNProfessional C ON C.CNProfessionalId = P.CNProfessionalId ");
            sb.Append("LEFT JOIN WBS_UnitWork AS UnitWork ON UnitWork.UnitWorkId = P.UnitWorkId ");
            sb.Append("LEFT JOIN WBS_DivisionProject AS DP ON DP.DivisionProjectId = P.Branch ");
            sb.Append("LEFT JOIN WBS_BreakdownProject AS BP ON BP.BreakdownProjectId = P.ControlPointType ");
            sb.Append("WHERE P.ProjectId=@ProjectId ");
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                sb.Append("AND P.UnitId=@UnitId ");
                listStr.Add(new SqlParameter("@UnitId", drpUnit.SelectedValue));
            }
            if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            {
                sb.Append("AND P.CNProfessionalId=@CNProfessionalId ");
                listStr.Add(new SqlParameter("@CNProfessionalId", drpCNProfessional.SelectedValue));
            }
            if (!string.IsNullOrWhiteSpace(txtStarTime.Text))
            {
                sb.Append("AND P.InspectionDate >= @startTime ");
                listStr.Add(new SqlParameter("@startTime", Funs.GetNewDateTime(txtStarTime.Text)));
            }
            if (!string.IsNullOrWhiteSpace(txtEndTime.Text))
            {
                var endTime = Funs.GetNewDateTime(txtEndTime.Text);
                if (endTime != null)
                {
                    sb.Append("AND P.InspectionDate <= @endTim ");
                    listStr.Add(new SqlParameter("@endTime", endTime));
                }
            }
            if (!string.IsNullOrEmpty(txtCompileDateS.Text.Trim()))
            {
                sb.Append("AND P.CompileDate >= @CompileDateS ");
                listStr.Add(new SqlParameter("@CompileDateS", Funs.GetNewDateTime(txtCompileDateS.Text.Trim())));
            }
            if (!string.IsNullOrEmpty(txtCompileDateE.Text.Trim()))
            {
                sb.Append("AND P.CompileDate <= @CompileDateE ");
                listStr.Add(new SqlParameter("@CompileDateE", Funs.GetNewDateTime(txtCompileDateE.Text.Trim())));
            }
            sb.Append("ORDER BY P.NoticeCode DESC ");
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(sb.ToString(), parameter);
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 分页、排序
        /// 
        /// 分页下拉
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 分页索引事件
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 关闭弹出窗口
        /// 
        ///关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 编辑
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            btnMenuModify_Click(null, null);
        }
        /// 
        /// 右键编辑
        /// 
        /// 
        /// 
        protected void btnMenuModify_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录", MessageBoxIcon.Warning);
                return;
            }
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("InspectionManagementEdit.aspx?InspectionId={0}", Grid1.SelectedRowID, "编辑 - ")));
        }
        #endregion
        #region 右键删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDel_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var InspectionEquipment = BLL.InspectionManagementService.GetInspectionManagementById(rowID);
                    if (InspectionEquipment != null)
                    {
                        BLL.InspectionManagementDetailService.DeleteAllInspectionDetail(rowID);
                        BLL.InspectionManagementService.DeleteInspectionManagement(rowID);
                    }
                }
                BindGrid();
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (Request.Params["value"] == "0")
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.InspectionManagementMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuModify.Hidden = false;
                    this.Grid1.EnableRowDoubleClickEvent = true;
                }
                else
                {
                    this.Grid1.EnableRowDoubleClickEvent = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDel.Hidden = false;
                }
            }
        }
        #endregion
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/");
            string initTemplatePath = Const.InspectionManagementTempUrl;
            string uploadfilepath = string.Empty;
            string newUrl = string.Empty;
            uploadfilepath = rootPath + initTemplatePath;
            //var lists = (from x in Funs.DB.ProcessControl_InspectionManagementDetail
            //             join y in Funs.DB.ProcessControl_InspectionManagement
            //             on x.InspectionId equals y.InspectionId
            //             where y.ProjectId == this.CurrUser.LoginProjectId
            //             select y);
            var db = Funs.DB;
            var lists = (from x in db.ProcessControl_InspectionManagement
                         join bu in db.Base_Unit on x.UnitId equals bu.UnitId into buGroup
                         from bu in buGroup.DefaultIfEmpty()
                         join bcn in db.Base_CNProfessional on x.CNProfessionalId equals bcn.CNProfessionalId into bcnGroup
                         from bcn in bcnGroup.DefaultIfEmpty()
                             //join wbsuw in db.WBS_UnitWork on x.UnitWorkId equals wbsuw.UnitWorkId into wbsuwGroup
                             //from wbsuw in wbsuwGroup.DefaultIfEmpty()
                             //join wbsd in db.WBS_DivisionProject on x.Branch equals wbsd.DivisionProjectId into wbsdGroup
                             //from wbsd in wbsdGroup.DefaultIfEmpty()
                             //join wbsbp in db.WBS_BreakdownProject on x.ControlPointType equals wbsbp.BreakdownProjectId into wbsbpGroup
                             //from wbsbp in wbsbpGroup.DefaultIfEmpty()
                         where x.ProjectId == this.CurrUser.LoginProjectId
                         orderby x.NoticeCode descending
                         select new
                         {
                             UnitId = x.UnitId,
                             UnitName = bu.UnitName,
                             CNProfessionalId = x.CNProfessionalId,
                             ProfessionalName = bcn.ProfessionalName,
                             NoticeCode = x.NoticeCode,
                             AcceptanceSite = x.AcceptanceSite,
                             AcceptanceCheckMan = x.AcceptanceCheckMan,
                             InspectionDate = x.InspectionDate,
                             IsOnceQualified = x.IsOnceQualified,
                             InspectionCode = x.InspectionCode
                         });
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                lists = lists.Where(x => x.UnitId == drpUnit.SelectedValue);
            }
            if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            {
                lists = lists.Where(x => x.CNProfessionalId == drpCNProfessional.SelectedValue);
            }
            if (!string.IsNullOrEmpty(txtStarTime.Text.Trim()))
            {
                lists = lists.Where(x => x.InspectionDate >= Funs.GetNewDateTime(txtStarTime.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            {
                lists = lists.Where(x => x.InspectionDate <= Funs.GetNewDateTime(txtEndTime.Text.Trim()));
            }
            if (lists != null)
            {
                string projectName = BLL.ProjectService.GetShortNameByProjectId(this.CurrUser.LoginProjectId);
                newUrl = uploadfilepath.Replace("控制点检查检测模板", "控制点检查检测(" + projectName.Replace("/", "") + DateTime.Now.ToString("yyyyMMdd") + ")");
                if (File.Exists(newUrl))
                {
                    File.Delete(newUrl);
                }
                File.Copy(uploadfilepath, newUrl);
                // 第一步:读取文件流
                NPOI.SS.UserModel.IWorkbook workbook;
                using (FileStream stream = new FileStream(newUrl, FileMode.Open, FileAccess.Read))
                {
                    //workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(stream);
                    workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(stream);
                }
                // 创建单元格样式
                NPOI.SS.UserModel.ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                cellStyle.WrapText = true;//自动换行
                var font = workbook.CreateFont();
                font.FontHeightInPoints = 11;
                cellStyle.SetFont(font);
                // 第二步:创建新数据行
                NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);
                NPOI.SS.UserModel.ICell cell;
                int i = 2;
                foreach (var item in lists)
                {
                    // 第二步:创建新数据行
                    row = sheet.CreateRow(i);
                    // 添加数据
                    cell = row.CreateCell(0);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.UnitName);//施工分包商
                    cell = row.CreateCell(1);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.ProfessionalName);//专业
                    cell = row.CreateCell(2);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.NoticeCode);//共检通知单编号
                    cell = row.CreateCell(3);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.AcceptanceSite);//验收部位
                    cell = row.CreateCell(4);
                    cell.CellStyle = cellStyle;
                    string userName = string.Empty;
                    if (!string.IsNullOrEmpty(item.AcceptanceCheckMan))
                    {
                        userName = ConvertCheckMan(item.AcceptanceCheckMan);
                    }
                    cell.SetCellValue(userName);//检查人
                    cell = row.CreateCell(5);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.IsOnceQualified == true ? "是" : "否");//是否一次合格
                    cell = row.CreateCell(6);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.InspectionCode);//报验编号
                    cell = row.CreateCell(7);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.InspectionDate.HasValue ? string.Format("{0:yyyy-MM-dd}", item.InspectionDate) : "");//验收日期
                    i++;
                }
                // 第三步:写入文件流
                using (FileStream stream = new FileStream(newUrl, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(stream);
                    workbook.Close();
                }
                string fileName = Path.GetFileName(newUrl);
                FileInfo info = new FileInfo(newUrl);
                long fileSize = info.Length;
                Response.Clear();
                Response.ContentType = "application/x-zip-compressed";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileSize.ToString());
                Response.TransmitFile(newUrl, 0, fileSize);
                Response.Flush();
                Response.Close();
                File.Delete(newUrl);
            }
            else
            {
                Alert.ShowInTop("当前无记录,无法导出!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        /// 
        /// 获取检查人名称
        /// 
        /// 
        /// 
        protected string ConvertCheckMan(object CarryUnitIds)
        {
            var uname = BLL.UserService.getUserNamesUserIds(CarryUnitIds);
            if (string.IsNullOrEmpty(uname))
            {
                uname = CarryUnitIds.ToString();
            }
            return uname;
        }
    }
}