using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using WIA;
namespace FineUIPro.Web.AttachFile
{
    public partial class webuploader : PageBase
    {
        private static readonly string sessionName = "AttachFile.webuploader";
        protected string ParamStr;
        #region 定义项
        public string ToKeyId
        {
            get
            {
                return (string)ViewState["ToKeyId"];
            }
            set
            {
                ViewState["ToKeyId"] = value;
            }
        }
        public string AttachPath
        {
            get
            {
                return (string)ViewState["AttachPath"];
            }
            set
            {
                ViewState["AttachPath"] = value;
            }
        }
        public string MenuId
        {
            get
            {
                return (string)ViewState["MenuId"];
            }
            set
            {
                ViewState["MenuId"] = value;
            }
        }
        public string Type
        {
            get
            {
                return (string)ViewState["Type"];
            }
            set
            {
                ViewState["Type"] = value;
            }
        }
        public string Source
        {
            get
            {
                return (string)ViewState["Source"];
            }
            set
            {
                ViewState["Source"] = value;
            }
        }
        public string JointCheck
        {
            get
            {
                return (string)ViewState["JointCheck"];
            }
            set
            {
                ViewState["JointCheck"] = value;
            }
        }
        public string editorMode
        {
            get
            {
                return (string)ViewState["editorMode"];
            }
            set
            {
                ViewState["editorMode"] = value;
            }
        }
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 删除选中行
                this.btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项!");
                this.btnDelete.ConfirmText = String.Format("你确定要删除选中的  个文件吗?", Grid1.GetSelectedCountReference());
                Session[sessionName] = null;
                this.ToKeyId = Request.QueryString["toKeyId"];
                if (!string.IsNullOrEmpty(Request.QueryString["strParam"]))
                {
                    this.ToKeyId = this.ToKeyId + "#" + Request.QueryString["strParam"];
                }
                this.AttachPath = Request.QueryString["path"];
                this.ParamStr = sessionName + "|" + AttachPath;
                this.MenuId = Request.QueryString["menuId"];
                this.Type = Request.Params["type"];
                JointCheck = Request.Params["JointCheck"];//是否共检页面
                Source = Request.QueryString["source"];//如果等于1则是文件柜
                editorMode = Request.Params["editorMode"];
                if (string.IsNullOrEmpty(editorMode))
                {
                    editorMode = "edit";
                }
                //Request.QueryString["type"]; ////类型:0时是上传资源页面,附件权限不需要判断 -1时只查看权限 -2查看集团公司
                this.GetButtonPower();
                this.BindGrid();
                //用于开车总结签字版附件,不可编辑
                if (Request.QueryString["strParam"] == "2" && (this.MenuId == BLL.Const.SpecialSummaryMenuId || this.MenuId == BLL.Const.PersonalSummaryMenuId || this.MenuId == BLL.Const.CompleteSummaryMenuId))
                {
                    btnOnlineEdit.Hidden = true;
                }
            }
            else
            {
                if (GetRequestEventArgument() == "RebindGrid")
                {
                    this.BindGrid();
                }
            }
        }
        #endregion
        #region BindGrid
        /// 
        /// 绑定GV
        /// 
        private void BindGrid()
        {
            if (Source == "1")  //文件柜
            {
                if (!string.IsNullOrWhiteSpace(JointCheck))
                {
                    if (JointCheck.Equals("JointCheck"))
                    {
                        Grid1.DataSource = JointData();
                    }
                }
                else
                {
                    Grid1.DataSource = SourceData();
                }
            }
            else
            {
                Grid1.DataSource = GetSourceData();
            }
            Grid1.DataBind();
        }
        #endregion
        private JArray JointData()
        {
            if (Session[sessionName] == null && !string.IsNullOrEmpty(ToKeyId))
            {
                //Session[sessionName] = new JArray();
                StringBuilder stxt = new StringBuilder();
                var jointChecks = JointCheckDetailService.GetViewLists(ToKeyId);
                var liststr = new List();
                if (jointChecks.Count > 0)
                {
                    foreach (var itemjointChecks in jointChecks)
                    {
                        liststr.Add(itemjointChecks.JointCheckDetailId);
                        liststr.Add(itemjointChecks.JointCheckDetailId + "r");
                    }
                }
                var sourlist = AttachFileService.GetfileDetaillist(liststr, MenuId);
                if (sourlist.Count > 0)
                {
                    stxt.Append("[");
                    foreach (var sour in sourlist)
                    {
                        int index = sourlist.IndexOf(sour);
                        string str = string.Empty;
                        if (sour != null)
                        {
                            string url = sour.AttachUrl.Replace('\\', '/');
                            List list = Funs.GetStrListByStr(url, ',');
                            if (list.Count() > 0)
                            {
                                int i = 0;
                                foreach (var item in list)
                                {
                                    string atturl = Funs.RootPath + item.Replace(';', ' ').Trim();
                                    if (File.Exists(atturl))
                                    {
                                        i += 1;
                                        break;
                                    }
                                }
                                if (i > 0)
                                {
                                    if (sourlist.Count == 1)
                                    {
                                        str = sour.AttachSource.Substring(0, sour.AttachSource.Length - 1);
                                        str = str.Substring(1);
                                    }
                                    else if (sourlist.Count > 1)
                                    {
                                        var st = sour.AttachSource.Substring(0, sour.AttachSource.Length - 1);
                                        st = st.Substring(1);
                                        if (sourlist.Count - 1 != index)
                                        {
                                            st += ",";
                                        }
                                        str += st;
                                    }
                                }
                            }
                            stxt.Append(str);
                        }
                    }
                    stxt.Append("]");
                    Session[sessionName] = JArray.Parse(stxt.ToString());
                }
            }
            return (JArray)Session[sessionName];
        }
        /// 
        /// 文件柜专用
        /// 
        /// 
        private JArray SourceData()
        {
            if (Session[sessionName] == null && !string.IsNullOrEmpty(ToKeyId))
            {
                //Session[sessionName] = new JArray();
                StringBuilder stxt = new StringBuilder();
                IList sourlist = AttachFileService.Getfilelist(ToKeyId, MenuId);
                if (sourlist.Count > 0)
                {
                    stxt.Append("[");
                    foreach (var sour in sourlist)
                    {
                        int index = sourlist.IndexOf(sour);
                        string str = string.Empty;
                        if (sour != null)
                        {
                            string url = sour.AttachUrl.Replace('\\', '/');
                            List list = Funs.GetStrListByStr(url, ',');
                            if (list.Count() > 0)
                            {
                                int i = 0;
                                foreach (var item in list)
                                {
                                    string atturl = Funs.RootPath + item.Replace(';', ' ').Trim();
                                    if (File.Exists(atturl))
                                    {
                                        i += 1;
                                        break;
                                    }
                                }
                                if (i > 0)
                                {
                                    if (sourlist.Count == 1)
                                    {
                                        str = sour.AttachSource.Substring(0, sour.AttachSource.Length - 1);
                                        str = str.Substring(1);
                                    }
                                    else if (sourlist.Count > 1)
                                    {
                                        var st = sour.AttachSource.Substring(0, sour.AttachSource.Length - 1);
                                        st = st.Substring(1);
                                        if (sourlist.Count - 1 != index)
                                        {
                                            st += ",";
                                        }
                                        str += st;
                                    }
                                }
                            }
                            stxt.Append(str);
                        }
                    }
                    stxt.Append("]");
                    Session[sessionName] = JArray.Parse(stxt.ToString());
                }
            }
            return (JArray)Session[sessionName];
        }
        #region Events
        /// 
        /// 删除按钮
        /// 
        /// 
        /// 
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (string rowId in Grid1.SelectedRowIDArray)
            {
                DeleteRow(rowId);
            }
            BindGrid();
        }
        /// 
        /// 行事件
        /// 
        /// 
        /// 
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                DeleteRow(e.RowID);
                BindGrid();
            }
            if (e.CommandName == "Preview")
            {
                JArray source = GetSourceData();
                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;
                    if (item.Value("id") == e.RowID)
                    {
                        try
                        {
                            string savedName = item.Value("savedName");
                            string folder = item.Value("folder");
                            string xnUrl = AttachPath + "\\" + savedName;
                            if (!string.IsNullOrEmpty(folder))
                            {
                                xnUrl = folder + savedName;
                            }
                            string url = Funs.RootPath + xnUrl;
                            if (savedName.Contains("FileUpLoad"))
                            {
                                url = Funs.RootPath + savedName.Replace('/', '\\');
                            }
                            FileInfo info = new FileInfo(url);
                            if (!info.Exists || string.IsNullOrEmpty(savedName))
                            {
                                url = Funs.RootPath + "Images//Null.jpg";
                                info = new FileInfo(url);
                            }
                            var FiletExtension = Path.GetExtension(savedName);
                            bool isSupportType = AttachFileService.IsSupportFileType(FiletExtension);
                            if (isSupportType)
                            {
                                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/Look.aspx?fileUrl={0}", url, "查看  -")));
                            }
                            else
                            {
                                ShowNotify("不支持预览", MessageBoxIcon.Warning);
                            }
                            //if (FiletExtension == ".docx" || FiletExtension == ".pdf")
                            //{
                            //    string httpUrl = BLL.AsposeWordHelper.WordToHtml(url);
                            //    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/Look.aspx?fileUrl={0}", httpUrl, "查看  -")));
                            //}
                            //else if (FiletExtension == ".txt")
                            //{
                            //    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/Look.aspx?fileUrl={0}", url, "查看  -")));
                            //}
                            //else if (FiletExtension == ".xls")
                            //{
                            //    string httpUrl = BLL.AsposeWordHelper.PriviewExcel(url);
                            //    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/Look.aspx?fileUrl={0}", httpUrl, "查看  -")));
                            //}
                            //else
                            //{
                            //    ShowNotify("不支持预览", MessageBoxIcon.Warning);
                            //}
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            if (e.CommandName == "Attach")
            {
                JArray source = GetSourceData();
                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;
                    if (item.Value("id") == e.RowID)
                    {
                        try
                        {
                            string savedName = item.Value("savedName");
                            string folder = item.Value("folder");
                            string xnUrl = AttachPath + "\\" + savedName;
                            if (!string.IsNullOrEmpty(folder))
                            {
                                xnUrl = folder + savedName;
                            }
                            string url = Funs.RootPath + xnUrl;
                            if (savedName.Contains("FileUpLoad"))
                            {
                                url = Funs.RootPath + savedName.Replace('/', '\\');
                            }
                            FileInfo info = new FileInfo(url);
                            if (!info.Exists || string.IsNullOrEmpty(savedName))
                            {
                                url = Funs.RootPath + "Images//Null.jpg";
                                info = new FileInfo(url);
                            }
                            if (Path.GetExtension(savedName) == ".mp4" || Path.GetExtension(savedName).ToLower() == ".mp4" || Path.GetExtension(savedName) == ".m4v")
                            {
                                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/player.aspx?url={0}", xnUrl.Replace('\\', '/'), "播放 - ")));
                            }
                            else
                            {
                                if (Path.GetExtension(savedName) == ".gif" || Path.GetExtension(savedName) == ".jpg" || Path.GetExtension(savedName) == ".jpeg" || Path.GetExtension(savedName) == ".bmp" || Path.GetExtension(savedName) == ".png")
                                {
                                    string httpUrl = Funs.SGGLUrl + xnUrl;
                                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "");
                                }
                                else
                                {
                                    string fileName = Path.GetFileName(url);
                                    long fileSize = info.Length;
                                    System.Web.HttpContext.Current.Response.Clear();
                                    //System.Web.HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                                    System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                                    System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                                    System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
                                    System.Web.HttpContext.Current.Response.TransmitFile(url, 0, fileSize);
                                    System.Web.HttpContext.Current.Response.Flush();
                                    System.Web.HttpContext.Current.Response.End();
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
        }
        #endregion
        #region GetSourceData
        /// 
        /// 得到Session
        /// 
        /// 
        private JArray GetSourceData()
        {
            if (Session[sessionName] == null && !string.IsNullOrEmpty(ToKeyId))
            {
                Session[sessionName] = new JArray();
                Model.AttachFile sour = new Model.AttachFile();
                if (this.MenuId == Const.ProjectPunishNoticeMenuId || this.MenuId == Const.ProjectPunishNoticeStatisticsMenuId)
                {
                    sour = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == ToKeyId && x.MenuId == this.MenuId);
                }
                else
                {
                    sour = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == ToKeyId);
                }
                if (sour != null)
                {
                    string url = sour.AttachUrl.Replace('\\', '/');
                    List list = Funs.GetStrListByStr(url, ',');
                    if (list.Count() > 0)
                    {
                        int i = 0;
                        foreach (var item in list)
                        {
                            string atturl = Funs.RootPath + item.Replace(';', ' ').Trim();
                            if (File.Exists(atturl))
                            {
                                i += 1;
                                break;
                            }
                        }
                        if (i > 0)
                        {
                            Session[sessionName] = JArray.Parse(sour.AttachSource);
                        }
                    }
                }
            }
            return (JArray)Session[sessionName];
        }
        /// 
        /// 
        /// 
        /// 
        private void DeleteRow(string rowId)
        {
            JArray source = GetSourceData();
            for (int i = 0, count = source.Count; i < count; i++)
            {
                JObject item = source[i] as JObject;
                if (item.Value("id") == rowId)
                {
                    try
                    {
                        string savedName = item.Value("savedName");
                        string attachUrl = AttachPath + "\\" + savedName;
                        if (!string.IsNullOrEmpty(item.Value("folder")))
                        {
                            attachUrl = item.Value("folder") + savedName;
                        }
                        if (this.AttachPath.Contains("DriverRunPlanK"))
                        {
                            ImportXlsToData(Server.MapPath("~/" + attachUrl));
                        }
                        File.Delete(Server.MapPath("~/" + attachUrl));
                        BLL.LogService.AddSys_Log(this.CurrUser, "删除附件!", null, this.MenuId, BLL.Const.BtnDelete);
                    }
                    catch (Exception)
                    {
                        // 尝试删除物理文件失败,不做处理
                    }
                    source.RemoveAt(i);
                    break;
                }
            }
            Session[sessionName] = source;
            //删除附件后,修改附件表数据
            string attachUrlNew = string.Empty;
            for (int i = 0, count = source.Count; i < count; i++)
            {
                JObject item = source[i] as JObject;
                if (!string.IsNullOrEmpty(item.Value("folder")))
                {
                    attachUrlNew += item.Value("folder") + item.Value("savedName") + ",";
                }
                else
                {
                    attachUrlNew += AttachPath + "/" + DateTime.Now.ToString("yyyy-MM") + "/" + item.Value("savedName") + ",";
                }
            }
            if (!string.IsNullOrEmpty(attachUrlNew))
            {
                attachUrlNew = attachUrlNew.Substring(0, attachUrlNew.LastIndexOf(",")).Replace('\\', '/');
            }
            ///保存方法
            this.SaveData(source.ToString(), attachUrlNew);
        }
        #region 读Excel提取数据
        /// 
        /// 从Excel提取数据--》Dataset
        /// 
        /// Excel文件路径名
        private void ImportXlsToData(string fileName)
        {
            try
            {
                string oleDBConnString = String.Empty;
                oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                oleDBConnString += "Data Source=";
                oleDBConnString += fileName;
                oleDBConnString += ";Extended Properties=Excel 8.0;";
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString().Trim();
                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                AddDatasetToSQL(ds.Tables[0], 35);
            }
            catch (Exception exc)
            {
                //return null;
                // return dt;
            }
            finally
            {
            }
        }
        #endregion
        #region 将Dataset的数据导入数据库
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集行数
        /// 
        private bool AddDatasetToSQL(DataTable pds, int Cols)
        {
            string result = string.Empty;
            int ic, ir;
            ic = pds.Columns.Count;
            if (ic < Cols)
            {
                return false;
            }
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                var driverRunPlan = (from x in Funs.DB.DriverRun_DriverRunPlan
                                     where x.ProjectId == this.CurrUser.LoginProjectId
                                     select x).FirstOrDefault();
                int usedDays = 0;
                if (driverRunPlan != null)
                {
                    for (int i = 0; i < ir; i++)
                    {
                        string row34 = pds.Rows[i][34].ToString().Trim();
                        if (!string.IsNullOrEmpty(row34))
                        {
                            usedDays += Funs.GetNewIntOrZero(row34);
                        }
                    }
                    driverRunPlan.UsedDays -= usedDays;
                    Funs.DB.SubmitChanges();
                }
            }
            else
            {
            }
            return true;
        }
        #endregion
        #endregion
        #region 保存按钮事件
        /// 
        /// 保存按钮事件
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            JArray source = GetSourceData();
            if (!string.IsNullOrEmpty(source.ToString()))
            {
                string attachUrl = string.Empty;
                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;
                    if (!string.IsNullOrEmpty(item.Value("folder")))
                    {
                        attachUrl += item.Value("folder") + item.Value("savedName") + ",";
                    }
                    else
                    {
                        attachUrl += AttachPath + "/" + DateTime.Now.ToString("yyyy-MM") + "/" + item.Value("savedName") + ",";
                    }
                }
                if (!string.IsNullOrEmpty(attachUrl))
                {
                    attachUrl = attachUrl.Substring(0, attachUrl.LastIndexOf(",")).Replace('\\', '/');
                }
                ///保存方法
                this.SaveData(source.ToString(), attachUrl);
                ShowNotify("保存成功!", MessageBoxIcon.Success);
                #region 统一人员资质上传功能2024-7-1
                if (MenuId== BLL.Const.PersonListMenuId && Request.QueryString["strParam"]=="4")
                {
                    //如果是人员信息修改安全生产考核合格证书/特种作业操作证(同步 特种作业人员资质、安管人员资质)
                    var personId = ToKeyId.Split('#')[0].ToString();
                    var PersonQualityModel = Funs.DB.QualityAudit_PersonQuality.FirstOrDefault(x => x.PersonId == personId);
                    if (PersonQualityModel!=null)
                    {
                        UploadFileService.SaveAttachUrl(source.ToString(), attachUrl, 
                            BLL.Const.PersonQualityMenuId, PersonQualityModel.PersonQualityId);
                    }
                    var SafePersonQualityModel = Funs.DB.QualityAudit_SafePersonQuality.FirstOrDefault(x => x.PersonId == personId);
                    if (SafePersonQualityModel != null)
                    {
                        UploadFileService.SaveAttachUrl(source.ToString(), attachUrl,
                            BLL.Const.SafePersonQualityMenuId, SafePersonQualityModel.SafePersonQualityId);
                    }
                }
                if (MenuId== BLL.Const.PersonQualityMenuId)
                {
                    var PersonQualityModel = Funs.DB.QualityAudit_PersonQuality.FirstOrDefault(x => x.PersonQualityId == ToKeyId);
                    if (PersonQualityModel!=null)
                    {
                        var personId = PersonQualityModel.PersonId;
                        var SafePersonQualityModel = Funs.DB.QualityAudit_SafePersonQuality.FirstOrDefault(x => x.PersonId == personId);
                        if (SafePersonQualityModel != null)
                        {
                            UploadFileService.SaveAttachUrl(source.ToString(), attachUrl,
                                BLL.Const.SafePersonQualityMenuId, SafePersonQualityModel.SafePersonQualityId);
                        }
                        var SitepersonModel = Funs.DB.SitePerson_Person.FirstOrDefault(x => x.PersonId == personId);
                        if (SitepersonModel!=null)
                        {
                            UploadFileService.SaveAttachUrl(source.ToString(), attachUrl,
                               BLL.Const.PersonListMenuId, SitepersonModel.PersonId+"#4");
                        }
                    }
                }
                if (MenuId== BLL.Const.SafePersonQualityMenuId)
                {
                    var SafePersonQualityModel = Funs.DB.QualityAudit_SafePersonQuality.FirstOrDefault(x => x.SafePersonQualityId == ToKeyId);
                    if (SafePersonQualityModel!=null)
                    {
                        var personId = SafePersonQualityModel.PersonId;
                        var PersonQualityModel = Funs.DB.QualityAudit_PersonQuality.FirstOrDefault(x => x.PersonId == personId);
                        if (PersonQualityModel != null)
                        {
                            UploadFileService.SaveAttachUrl(source.ToString(), attachUrl,
                                BLL.Const.PersonQualityMenuId, PersonQualityModel.PersonQualityId);
                        }
                        var SitepersonModel = Funs.DB.SitePerson_Person.FirstOrDefault(x => x.PersonId == personId);
                        if (SitepersonModel != null)
                        {
                            UploadFileService.SaveAttachUrl(source.ToString(), attachUrl,
                               BLL.Const.PersonListMenuId, SitepersonModel.PersonId + "#4");
                        }
                    }
                }
                #endregion
                //#region PunchlistFrom附件保存成功后处理事件
                //if (MenuId == BLL.Const.PunchlistFromMenuId)
                //{
                //    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                //}
                //#endregion
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
        }
        #endregion
        /// 
        ///  保存附件
        /// 
        /// 
        /// 
        private void SaveData(string source, string attachUrl)
        {
            UploadFileService.SaveAttachUrl(source, attachUrl, MenuId, ToKeyId);
        }
        /// 
        /// 扫描文件
        /// 
        /// 
        /// 
        protected void btnImageMagnify_Click(object sender, EventArgs e)
        {
            try
            {
                DeviceManager manager = new DeviceManagerClass();
                Device device = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.Type != WiaDeviceType.ScannerDeviceType)
                        continue;
                    device = info.Connect();
                    break;
                }
                Item item = device.Items[1];
                CommonDialogClass cdc = new WIA.CommonDialogClass();
                ImageFile imageFile = null;
                imageFile = cdc.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType,
                                                 WIA.WiaImageIntent.TextIntent,
                                                 WIA.WiaImageBias.MaximizeQuality,
                                                 "{00000000-0000-0000-0000-000000000000}",
                                                 true,
                                                 true,
                                                 false);
                if (imageFile != null)
                {
                    var buffer = imageFile.FileData.get_BinaryData() as byte[];
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ms.Write(buffer, 0, buffer.Length);
                        string filePath = Server.MapPath("~/") + AttachPath;  ///文件夹
                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }
                        string name = "\\";
                        var menu = BLL.SysMenuService.GetSysMenuByMenuId(this.MenuId);
                        if (menu != null)
                        {
                            name += menu.MenuName;
                        }
                        name += Funs.GetNewFileName() + ".jpg";
                        string url = filePath + name;
                        if (!string.IsNullOrEmpty(url))
                        {
                            using (FileStream fs = new FileStream(url, FileMode.Create, FileAccess.Write))
                            {
                                ms.WriteTo(fs);
                                string attachUrl = AttachPath + name;
                                if (!string.IsNullOrEmpty(attachUrl))
                                {
                                    attachUrl = attachUrl.Replace('/', '\\');
                                }
                                string oldSrouce = string.Empty;
                                string FullPath = string.Empty;
                                Model.AttachFile att = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == this.ToKeyId);
                                if (att != null && !string.IsNullOrEmpty(att.AttachUrl))
                                {
                                    FullPath = att.AttachUrl + "," + attachUrl;
                                    oldSrouce = att.AttachSource;
                                }
                                else
                                {
                                    FullPath = attachUrl;
                                }
                                string source = BLL.UploadFileService.GetSourceByAttachUrl(attachUrl, buffer.Length, oldSrouce);
                                //this.SaveData(source, FullPath); ///保存方法
                                Session[sessionName] = JArray.Parse(source);
                            }
                            this.BindGrid();
                            ShowNotify("扫描完成!", MessageBoxIcon.Success);
                        }
                    }
                }
            }
            catch
            {
                ShowNotify("请检查扫描仪是否连接正确!", MessageBoxIcon.Warning);
            }
        }
        #region 获取权限按钮
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (this.Type == "0")
            {
                this.toolBar.Hidden = false;
            }
            else if (this.Type == "-1")
            {
                this.toolBar.Hidden = true;
            }
            else if (this.Type == "-2")  //方案审核只保留文档编辑
            {
                this.toolBar.Hidden = false;
                btnImageMagnify.Hidden = true;
                btnSelectFiles.Hidden = true;
                btnDelete.Hidden = true;
                btnSave.Hidden = true;
            }
            else
            {
                if (this.CurrUser != null && this.MenuId != Const.ProjectPunishNoticeStatisticsMenuId)
                {
                    var buttonList = CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, MenuId);
                    if (buttonList.Count > 0)
                    {
                        if (buttonList.Contains(Const.BtnSave) || buttonList.Contains(Const.BtnAuditing))
                        {
                            this.toolBar.Hidden = false;
                        }
                    }
                }
            }
        }
        #endregion
        protected void btnPlay_Click(object sender, EventArgs e)
        {
        }
        protected void btnOnlineEdit_OnClick(object sender, EventArgs e)
        {
            JArray source = GetSourceData();
            for (int i = 0, count = source.Count; i < count; i++)
            {
                JObject item = source[i] as JObject;
                if (item.Value("id") == Grid1.SelectedRowID)
                {
                    try
                    {
                        string savedName = item.Value("savedName");
                        string folder = item.Value("folder");
                        string xnUrl = AttachPath + "\\" + savedName;
                        if (!string.IsNullOrEmpty(folder))
                        {
                            xnUrl = folder + savedName;
                        }
                        string url = Funs.RootPath + xnUrl;
                        if (savedName.Contains("FileUpLoad"))
                        {
                            url = Funs.RootPath + savedName.Replace('/', '\\');
                        }
                        FileInfo info = new FileInfo(url);
                        if (!info.Exists || string.IsNullOrEmpty(savedName))
                        {
                            url = Funs.RootPath + "Images//Null.jpg";
                            info = new FileInfo(url);
                        }
                        var FiletExtension = Path.GetExtension(savedName);
                        bool isSupportType = FiletExtension.Equals(".docx");
                        if (isSupportType)
                        {
                            url = url.Replace(Funs.RootPath, "");
                            var sysSet4 = (from x in Funs.DB.Sys_Const where x.ConstText == "IsUseLoaclService" select x).ToList().FirstOrDefault();
                            if (sysSet4!=null&& sysSet4.ConstValue=="1")
                            {
                                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/OnlineEditingPrivate.aspx?fileUrl={0}&&editorMode={1}", url, editorMode, "编辑  -")));
                            }
                            else
                            {
                                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("../AttachFile/OnlineEditing.aspx?fileUrl={0}&&editorMode={1}", url, editorMode, "编辑  -")));
                            }
                        }
                        else
                        {
                            ShowNotify("不支持在线编辑", MessageBoxIcon.Warning);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
    }
}