using Aspose.Words;
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FineUIPro.Web.CQMS.Check
{
    public partial class CheckFineList : PageBase
    {
        /// 
        /// 项目id
        /// 
        public string ProjectId
        {
            get
            {
                return (string)ViewState["ProjectId"];
            }
            set
            {
                ViewState["ProjectId"] = value;
            }
        }
        public int TotalNum
        {
            get
            {
                return (int)ViewState["TotalNum"];
            }
            set
            {
                ViewState["TotalNum"] = value;
            }
        }
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            // 表头过滤
            //FilterDataRowItem = FilterDataRowItemImplement;
            if (!IsPostBack)
            {
                this.ProjectId = this.CurrUser.LoginProjectId;
                GetButtonPower();
                //if (!string.IsNullOrEmpty(Request.Params["projectId"]) && Request.Params["projectId"] != this.ProjectId)
                //{
                //    this.ProjectId = Request.Params["projectId"];
                //}
                //权限按钮方法
                UnitService.InitUnitByProjectIdUnitTypeDropDownList(drpSponsorUnit, this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, true);
                UnitWorkService.InitUnitWorkDownList(drpUnitWork, this.CurrUser.LoginProjectId, true);
                 
                btnNew.OnClientClick = Window1.GetShowReference("CheckFineListEdit.aspx") + "return false;";
                ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                BindGrid();
            }
            
        }
        #endregion
      
       
        public Task data()
        {
            Task task = new Task(() =>
            {
                return ChecklistData();
            });
            task.Start();
            return task;
        }
        protected DataTable ChecklistData()
        {
            string strSql = @"SELECT Fee,chec.CheckFineId,chec.CheckControlCode,chec.ProjectId,chec.unitId,
		chec.checkman,chec.CheckDate,chec.DocCode,chec.state,
		unit.UnitName,unitWork.UnitWorkName+(case unitWork.ProjectType when '1' then '(建筑)' else '(安装)' end) as UnitWorkName,u.userName 
		FROM Check_CheckFine chec
		left join Base_Unit unit on unit.unitId=chec.unitId
		left join WBS_UnitWork unitWork on unitWork.UnitWorkId = chec.UnitWorkId
		left join sys_User u on u.userId = chec.CheckMan where chec.ProjectId=@ProjectId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            strSql += " AND (chec.CheckDate>=@startTime or @startTime='') and (chec.CheckDate<=@endTime or @endTime='') ";
            listStr.Add(new SqlParameter("@startTime", !string.IsNullOrEmpty(txtStartTime.Text.Trim()) ? txtStartTime.Text.Trim() + " 00:00:00" : ""));
            listStr.Add(new SqlParameter("@endTime", !string.IsNullOrEmpty(txtEndTime.Text.Trim()) ? txtEndTime.Text.Trim() + "  23:59:59" : ""));
            if (drpSponsorUnit.SelectedValue != BLL.Const._Null)
            {
                strSql += " AND chec.unitId=@unitId";
                listStr.Add(new SqlParameter("@unitId", drpSponsorUnit.SelectedValue));
            }
            if (drpUnitWork.SelectedValue != Const._Null)
            {
                strSql += " AND chec.unitworkId=@unitworkId";
                listStr.Add(new SqlParameter("@unitworkId", drpUnitWork.SelectedValue));
            }
           
            
             
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            return tb;
        }
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            string filename = Funs.GetNewFileName();
            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("日常巡检" + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            this.Grid1.PageSize = 100000;
            this.BindGrid();
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        protected string ConvertImageUrlByImage(object registrationId)
        {
            string url = string.Empty;
            if (registrationId != null)
            {
                IList sourlist = AttachFileService.GetBeforeFileList(registrationId.ToString(), BLL.Const.CheckFineListMenuId);
                 if (sourlist != null&& sourlist.Count>0)
                {
                    string AttachUrl = "";
                    foreach(var item in sourlist)
                    {   if(!string.IsNullOrEmpty(item.AttachUrl)&& item.AttachUrl.ToLower().EndsWith(".jpg")|| item.AttachUrl.ToLower().EndsWith(".jpeg")|| item.AttachUrl.ToLower().EndsWith(".png"))
                        AttachUrl += item.AttachUrl.TrimEnd(',')+",";
                    }
                    url = BLL.UploadAttachmentService.ShowImage("../../", AttachUrl.TrimEnd(','));
                }
            }
            return url;
        }
        protected string ConvertImgUrlByImage(object registrationId)
        {
            string url = string.Empty;
            if (registrationId != null)
            {
                IList sourlist = AttachFileService.Getfilelist(registrationId.ToString()+"r", BLL.Const.CheckListMenuId);
                if (sourlist != null && sourlist.Count > 0)
                {
                    string AttachUrl = "";
                    foreach (var item in sourlist)
                    {
                        if (!string.IsNullOrEmpty(item.AttachUrl) && item.AttachUrl.ToLower().EndsWith(".jpg") || item.AttachUrl.ToLower().EndsWith(".jpeg") || item.AttachUrl.ToLower().EndsWith(".png"))
                            AttachUrl += item.AttachUrl.TrimEnd(',') + ",";
                    }
                    url = BLL.UploadAttachmentService.ShowImage("../../", AttachUrl.TrimEnd(','));
                }
            }
            return url;
        }
        
         
        /// 
        /// 绑定数据
        /// 
        public void BindGrid()
        {
            DataTable tb = ChecklistData();
            // 2.获取当前分页数据
            //var table = this.GetPagedDataTable(Grid1, tb1);
            Grid1.RecordCount = tb.Rows.Count;
            tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
         
        }
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #endregion
        #region 过滤表头、排序、分页、关闭窗口
        /// 
        /// 过滤表头
        /// 
        /// 
        /// 
        protected void Grid1_FilterChange(object sender, EventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            //Grid1.SortDirection = e.SortDirection;
            //Grid1.SortField = e.SortField;
            BindGrid();
        }
        /// 
        /// 分页显示条数下拉框
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 关闭弹出窗
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region Grid双击事件
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            btnMenuModify_Click(null, null);
        }
        #endregion
        #region 编辑
        /// 
        /// 编辑按钮
        /// 
        /// 
        /// 
        protected void btnMenuModify_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string codes = Grid1.SelectedRowID.Split(',')[0];
            var checks = BLL.CheckFineService.CheckFine(codes);
            if (checks != null)
            {
                if (checks.CheckMan.Equals(Const.CheckControl_Complete))
                {
                    Alert.ShowInTop("您不是当前办理人,无法编辑,请右键查看!", MessageBoxIcon.Warning);
                    return;
                }
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("CheckFineListEdit.aspx?CheckFineId={0}", codes, "编辑 - ")));
                return;
            }
        }
        #endregion
        #region 删除
        /// 
        /// 批量删除
        /// 
        /// 
        /// 
        protected void btnMenuDel_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string codes = Grid1.SelectedRowID.Split(',')[0];
            var checks = BLL.CheckFineService.CheckFine(codes);
            BLL.CheckFineService.DeleteCheckList(codes);
            BLL.LogService.AddSys_Log(this.CurrUser, checks.DocCode, codes, BLL.Const.CheckListMenuId, "删除质量罚款单记录");
            Grid1.DataBind();
            BindGrid();
            Alert.ShowInTop("删除数据成功!", MessageBoxIcon.Success);
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (Request.Params["value"] == "0")
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.ProjectId, this.CurrUser.UserId, BLL.Const.CheckListMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuModify.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDel.Hidden = false;
                }
            }
        }
        #endregion
        
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            //if (checkControl.State.Equals("5") || checkControl.State.Equals("6"))
            //{
            //    Grid1.Rows[i].RowCssClass = "lightgreen";//未确认
            //}
            //else if (checkControl.State == Const.CheckControl_Complete)
            //{ //闭环
            //    Grid1.Rows[i].RowCssClass = "green";
            //}
            ////else if( checkControl.LimitDate> )
            //else if (Convert.ToDateTime(checkControl.LimitDate).AddDays(1).Date < DateTime.Now && checkControl.State != BLL.Const.CheckControl_Complete)  //延期未整改
            //{
            //    Grid1.Rows[i].RowCssClass = "orange";
            //}
            //else  //期内未整改
            //{
            //    Grid1.Rows[i].RowCssClass = "red";
            //}
        }
        protected void btnMenuView_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string codes = Grid1.SelectedRowID.Split(',')[0];
            var checks = BLL.CheckControlService.GetCheckControl(codes);
            if (checks != null)
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("CheckListView.aspx?CheckFineId={0}", codes, "查看 - ")));
            }
        }
        protected void btnMenuNotice_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string codes = Grid1.SelectedRowID.Split(',')[0];
            Model.Check_CheckFine checkControl = CheckFineService.CheckFine(codes);
            string rootPath = Server.MapPath("~/");
            string initTemplatePath = string.Empty;
            string uploadfilepath = string.Empty;
            string newUrl = string.Empty;
            initTemplatePath = Const.CheckFineTemplateUrl;
            uploadfilepath = rootPath + initTemplatePath;
            newUrl = uploadfilepath.Replace(".doc", checkControl.DocCode + ".doc");
            if (File.Exists(newUrl))
            {
                File.Delete(newUrl);
            }
            File.Copy(uploadfilepath, newUrl);
            Document doc = new Aspose.Words.Document(newUrl);
            Bookmark bookmarkProjectName = doc.Range.Bookmarks["ProjectName"];
            Bookmark bookmarkProjectCode = doc.Range.Bookmarks["ProjectCode"];
            var project = ProjectService.GetProjectByProjectId(checkControl.ProjectId);
            if (bookmarkProjectName != null)
            {
                if (project != null)
                {
                    bookmarkProjectName.Text = string.IsNullOrEmpty(project.ShortName) ? project.ProjectName : project.ShortName;
                }
            }
            if (bookmarkProjectCode != null)
            {
                if (project != null)
                {
                    bookmarkProjectCode.Text = project.ProjectCode;
                }
            }
            Bookmark bookmarkFileNum2 = doc.Range.Bookmarks["FileNum2"];
            if (bookmarkFileNum2 != null)
            {
                bookmarkFileNum2.Text = checkControl.DocCode;
            }
            Bookmark bookmarkFileNum = doc.Range.Bookmarks["FileNum"];
            if (bookmarkFileNum != null)
            {
                bookmarkFileNum.Text = checkControl.DocCode;
            }
            Bookmark bookmarkUnit = doc.Range.Bookmarks["Unit"];
            if (bookmarkUnit != null)
            {
                var unit = UnitService.GetUnitByUnitId(checkControl.UnitId);
                if (unit != null)
                {
                    bookmarkUnit.Text = unit.UnitName;
                }
            }
            Bookmark bookmarkWorkArea = doc.Range.Bookmarks["WorkArea"];
            if (bookmarkWorkArea != null)
            {
                string option = "";
                var unitWork = UnitWorkService.GetUnitWorkByUnitWorkId(checkControl.UnitWorkId);
                if (unitWork != null)
                {
                    bookmarkWorkArea.Text = unitWork.UnitWorkCode + "-" + unitWork.UnitWorkName;
                }
            }
            Bookmark bookmarkCheckDate = doc.Range.Bookmarks["CheckDate"];
            if (bookmarkCheckDate != null)
            {
                if (checkControl.CheckDate.HasValue)
                {
                    bookmarkCheckDate.Text = checkControl.CheckDate.Value.ToString("yyyy年MM月dd日");
                }
            }
            Bookmark bookmarkFine = doc.Range.Bookmarks["Fine"];
            if (bookmarkFine != null)
            {
                if (checkControl.Fee.HasValue)
                {
                    bookmarkFine.Text = checkControl.Fee.Value.ToString("##.##");
                }
            }
            Bookmark bookmarkFine2 = doc.Range.Bookmarks["Fine2"];
            if (bookmarkFine2 != null)
            {
                if (checkControl.Fee.HasValue)
                {
                    bookmarkFine2.Text = checkControl.Fee.Value.ToString("##");
                }
            }
            Bookmark bookmarkQuestionDef = doc.Range.Bookmarks["QuestionDef"];
            if (bookmarkQuestionDef != null)
            {
                if (!string.IsNullOrEmpty(checkControl.QuestionDef))
                {
                    bookmarkQuestionDef.Text = checkControl.QuestionDef;
                }
            }
            Bookmark bookmarkFine3 = doc.Range.Bookmarks["Fine3"];
            if (bookmarkFine3 != null)
            {
                if (checkControl.Fee.HasValue)
                {
                    bookmarkFine3.Text = checkControl.Fee.Value.ToString("##.##");
                }
            }
            Bookmark bookmarkFine4 = doc.Range.Bookmarks["Fine4"];
            if (bookmarkFine4 != null)
            {
                if (checkControl.Fee.HasValue)
                {
                    bookmarkFine4.Text = checkControl.Fee.Value.ToString("##");
                }
            }
            Bookmark bookmarkCheckMan = doc.Range.Bookmarks["CheckMan"];
            if (bookmarkCheckMan != null)
            {
                var user = UserService.GetUserByUserId(checkControl.CheckMan);
                if (user != null)
                {
                    bookmarkCheckMan.Text = user.UserName;
                }
            }
            IList sourlist = AttachFileService.GetBeforeFileList(checkControl.CheckFineId, BLL.Const.CheckFineListMenuId);
            if (sourlist != null && sourlist.Count > 0)
            {
                int indexPic = 1;
                string AttachUrl = "";
                foreach (var item in sourlist)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl) && item.AttachUrl.ToLower().EndsWith(".jpg") || item.AttachUrl.ToLower().EndsWith(".jpeg") || item.AttachUrl.ToLower().EndsWith(".png"))
                    {
                        AttachUrl += item.AttachUrl.TrimEnd(',') + ",";
                    }
                }
                string[] pics = AttachUrl.Split(',');
                foreach (string item in pics)
                {
                    switch (indexPic)
                    {
                        case 1:
                            {
                                string url = rootPath + item.TrimEnd(',');
                                //查找书签
                                DocumentBuilder builder = new DocumentBuilder(doc);
                                builder.MoveToBookmark("Pic1");
                                if (!string.IsNullOrEmpty(url))
                                {
                                    System.Drawing.Size JpgSize;
                                    float Wpx;
                                    float Hpx;
                                    UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                    double i = 1;
                                    i = JpgSize.Width / 180.0;
                                    if (File.Exists(url))
                                    {
                                        builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                    }
                                }
                                indexPic++;
                            }
                            break;
                        case 2:
                            {
                                string url = rootPath + item.TrimEnd(',');
                                //查找书签
                                DocumentBuilder builder = new DocumentBuilder(doc);
                                builder.MoveToBookmark("Pic2");
                                if (!string.IsNullOrEmpty(url))
                                {
                                    System.Drawing.Size JpgSize;
                                    float Wpx;
                                    float Hpx;
                                    UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                    double i = 1;
                                    i = JpgSize.Width / 180.0;
                                    if (File.Exists(url))
                                    {
                                        builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                    }
                                }
                                indexPic++;
                            }
                            break;
                        case 3:
                            {
                                string url = rootPath + item.TrimEnd(',');
                                //查找书签
                                DocumentBuilder builder = new DocumentBuilder(doc);
                                builder.MoveToBookmark("Pic3");
                                if (!string.IsNullOrEmpty(url))
                                {
                                    System.Drawing.Size JpgSize;
                                    float Wpx;
                                    float Hpx;
                                    UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                    double i = 1;
                                    i = JpgSize.Width / 180.0;
                                    if (File.Exists(url))
                                    {
                                        builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                    }
                                }
                                indexPic++;
                            }
                            break;
                        case 4:
                            {
                                string url = rootPath + item.TrimEnd(',');
                                //查找书签
                                DocumentBuilder builder = new DocumentBuilder(doc);
                                builder.MoveToBookmark("Pic4");
                                if (!string.IsNullOrEmpty(url))
                                {
                                    System.Drawing.Size JpgSize;
                                    float Wpx;
                                    float Hpx;
                                    UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                    double i = 1;
                                    i = JpgSize.Width / 180.0;
                                    if (File.Exists(url))
                                    {
                                        builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                    }
                                }
                                indexPic++;
                            }
                            break;
                    }
                }
            }
            doc.Save(newUrl);
            Document doc1 = new Aspose.Words.Document(newUrl);
            //验证参数
            if (doc1 == null) { throw new Exception("Word文件无效"); }
            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);
        }
        protected void btnMenuReNotice_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string codes = Grid1.SelectedRowID.Split(',')[0];
            var checks = BLL.CheckControlService.GetCheckControl(codes);
            if (checks != null)
            {
                string rootPath = Server.MapPath("~/");
                string initTemplatePath = string.Empty;
                string uploadfilepath = string.Empty;
                string newUrl = string.Empty;
                initTemplatePath = Const.CheckReNoticeTemplateUrl;
                uploadfilepath = rootPath + initTemplatePath;
                newUrl = uploadfilepath.Replace(".doc", checks.DocCode + ".doc");
                if (File.Exists(newUrl))
                {
                    File.Delete(newUrl);
                }
                File.Copy(uploadfilepath, newUrl);
                Document doc = new Aspose.Words.Document(newUrl);
                Bookmark bookmarkProjectCode = doc.Range.Bookmarks["ProjectNum"];
                if (bookmarkProjectCode != null)
                {
                    var project = ProjectService.GetProjectByProjectId(checks.ProjectId);
                    if (project != null)
                    {
                        bookmarkProjectCode.Text = project.ProjectCode;
                    }
                }
                Bookmark bookmarkSendDate = doc.Range.Bookmarks["SendDate"];
                if (bookmarkSendDate != null)
                {
                   
                    if (checks.CheckDate.HasValue != null)
                    {
                        bookmarkSendDate.Text = checks.CheckDate.Value.ToString("yyyy年MM月dd日");
                    }
                }
                Bookmark bookmarkNoticeNum = doc.Range.Bookmarks["NoticeNum"];
                if (bookmarkNoticeNum != null)
                {
                    bookmarkNoticeNum.Text = checks.DocCode;
                }
               
                Bookmark bookmarkUnit = doc.Range.Bookmarks["Unit"];
                if (bookmarkUnit != null)
                {
                    var unit = UnitService.GetUnitByUnitId(checks.UnitId);
                    if (unit != null)
                    {
                        bookmarkUnit.Text = unit.UnitName;
                    }
                }
                Bookmark bookmarkWorkArea = doc.Range.Bookmarks["UnitWork"];
                if (bookmarkWorkArea != null)
                {
                    string option = "";
                    var unitWork = UnitWorkService.GetUnitWorkByUnitWorkId(checks.UnitWorkId);
                    if (unitWork != null)
                    {
                        bookmarkWorkArea.Text = unitWork.UnitWorkCode + "-" + unitWork.UnitWorkName;
                    }
                }
                Bookmark bookmarkProblemType = doc.Range.Bookmarks["QuestionType"];
                if (bookmarkProblemType != null)
                {
                    string option = "";
                    var questionType = QualityQuestionTypeService.GetQualityQuestionType(checks.QuestionType);
                    if (questionType != null)
                    {
                        bookmarkProblemType.Text = questionType.QualityQuestionType;
                    }
                }
                Bookmark bookmarkChangeDate = doc.Range.Bookmarks["ChangeDate"];
                if (bookmarkChangeDate != null)
                {
                    if (checks.LimitDate.HasValue)
                    {
                        bookmarkChangeDate.Text = checks.LimitDate.Value.ToString("yyyy年MM月dd日");
                    }
                }
                Bookmark bookmarkProposeUnit = doc.Range.Bookmarks["ProposeUnit"];
                if (bookmarkProposeUnit != null)
                {
                    var unit = UnitService.GetUnitByUnitId(checks.ProposeUnitId);
                    if (unit != null)
                    {
                        bookmarkProposeUnit.Text = unit.UnitName;
                    }
                }
                Bookmark bookmarkCheckDate = doc.Range.Bookmarks["CheckDate"];
                
                if (bookmarkCheckDate != null)
                {
                    if (checks.CheckDate.HasValue != null)
                    {
                        bookmarkCheckDate.Text = checks.CheckDate.Value.ToString("yyyy年MM月dd日");
                    }
                }
                Bookmark bookmarkNoticeNum2 = doc.Range.Bookmarks["NoticeNum2"];
                if (bookmarkNoticeNum2 != null)
                {
                    bookmarkNoticeNum2.Text = checks.DocCode;
                }
                Bookmark bookmarkHandleWay = doc.Range.Bookmarks["HandleWay"];
                if (bookmarkHandleWay != null)
                {
                    if (!string.IsNullOrEmpty(checks.HandleWay))
                        bookmarkHandleWay.Text = checks.HandleWay;
                }
                Bookmark bookmarkCheckMan = doc.Range.Bookmarks["CheckMan"];
                if (bookmarkCheckMan != null)
                {
                    if (!string.IsNullOrEmpty(checks.CheckMan))
                    {
                        var sysUser = UserService.GetUserByUserId(checks.CheckMan);
                        bookmarkCheckMan.Text = sysUser.UserName;
                    }
                }
                
                Bookmark bookmarkResponseMan = doc.Range.Bookmarks["ResponseMan"];
                Bookmark bookmarkResponseDate = doc.Range.Bookmarks["ResponseDate"];
                if (bookmarkResponseMan != null)
                {
                    var approve = Funs.DB.Check_CheckControlApprove.Where(x => x.CheckControlCode == checks.CheckControlCode && x.ApproveType == BLL.Const.CheckControl_Audit2).FirstOrDefault();
                    if (approve != null)
                    {
                        var sysUser = UserService.GetUserByUserId(approve.ApproveMan);
                        if (sysUser != null)
                        {
                            bookmarkResponseMan.Text = sysUser.UserName;
                        }
                        if (approve.ApproveDate.HasValue)
                        {
                            bookmarkResponseDate.Text = approve.ApproveDate.Value.ToString("yyyy年MM月dd日");
                        }
                    }
                }
                Bookmark bookmarkReCheckMan = doc.Range.Bookmarks["ReCheckMan"];
                Bookmark bookmarkReCheckDate = doc.Range.Bookmarks["ReCheckDate"];
                if (bookmarkResponseMan != null)
                {
                    var approve = Funs.DB.Check_CheckControlApprove.Where(x => x.CheckControlCode == checks.CheckControlCode && x.ApproveType == BLL.Const.CheckControl_Audit4).FirstOrDefault();
                    if (approve != null)
                    {
                        var sysUser = UserService.GetUserByUserId(approve.ApproveMan);
                        if (sysUser != null)
                        {
                            bookmarkReCheckMan.Text = sysUser.UserName;
                        }
                        if (approve.ApproveDate.HasValue)
                        {
                            bookmarkReCheckDate.Text = approve.ApproveDate.Value.ToString("yyyy年MM月dd日");
                        }
                    }
                }
                IList sourlist = AttachFileService.GetBeforeFileList(checks.CheckControlCode, BLL.Const.CheckListMenuId);
                if (sourlist != null && sourlist.Count > 0)
                {
                    int indexPic = 1;
                    string AttachUrl = "";
                    foreach (var item in sourlist)
                    {
                        if (!string.IsNullOrEmpty(item.AttachUrl) && item.AttachUrl.ToLower().EndsWith(".jpg") || item.AttachUrl.ToLower().EndsWith(".jpeg") || item.AttachUrl.ToLower().EndsWith(".png"))
                        {
                            AttachUrl += item.AttachUrl.TrimEnd(',') + ",";
                        }
                    }
                    string[] pics = AttachUrl.Split(',');
                    foreach (string item in pics)
                    {
                        switch (indexPic)
                        {
                            case 1:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("Pic1");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                            case 2:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("Pic2");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                            case 3:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("Pic3");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                            case 4:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("Pic4");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                        }
                    }
                }
                IList reSourlist = AttachFileService.GetBeforeFileList(checks.CheckControlCode+"r", BLL.Const.CheckListMenuId);
                if (reSourlist != null && reSourlist.Count > 0)
                {
                    int indexPic = 1;
                    string AttachUrl = "";
                    foreach (var item in reSourlist)
                    {
                        if (!string.IsNullOrEmpty(item.AttachUrl) && item.AttachUrl.ToLower().EndsWith(".jpg") || item.AttachUrl.ToLower().EndsWith(".jpeg") || item.AttachUrl.ToLower().EndsWith(".png"))
                        {
                            AttachUrl += item.AttachUrl.TrimEnd(',') + ",";
                        }
                    }
                    string[] pics = AttachUrl.Split(',');
                    foreach (string item in pics)
                    {
                        switch (indexPic)
                        {
                            case 1:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("RPic1");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                            case 2:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("RPic2");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                            case 3:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("RPic3");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                            case 4:
                                {
                                    string url = rootPath + item.TrimEnd(',');
                                    //查找书签
                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                    builder.MoveToBookmark("RPic4");
                                    if (!string.IsNullOrEmpty(url))
                                    {
                                        System.Drawing.Size JpgSize;
                                        float Wpx;
                                        float Hpx;
                                        UploadAttachmentService.getJpgSize(url, out JpgSize, out Wpx, out Hpx);
                                        double i = 1;
                                        i = JpgSize.Width / 50.0;
                                        if (File.Exists(url))
                                        {
                                            builder.InsertImage(url, JpgSize.Width / i, JpgSize.Height / i);
                                        }
                                    }
                                    indexPic++;
                                }
                                break;
                        }
                    }
                }
                doc.Save(newUrl);
                Document doc1 = new Aspose.Words.Document(newUrl);
                //验证参数
                if (doc1 == null) { throw new Exception("Word文件无效"); }
                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);
            }
        }
        protected void btnMenuReplay_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string codes = Grid1.SelectedRowID.Split(',')[0];
            var checks = BLL.CheckControlService.GetCheckControl(codes);
            if (checks != null)
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("CheckListView.aspx?CheckFineId={0}", codes, "查看 - ")));
            }
        }
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        protected void btnRset_Click(object sender, EventArgs e)
        {
            drpSponsorUnit.SelectedIndex = 0;
            drpUnitWork.SelectedIndex = 0;
            txtStartTime.Text = "";
            txtEndTime.Text = "";
            BindGrid();
        }
    }
}