using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

namespace FineUIPro.Web.AttachFile
{
    public partial class webuploader3 : PageBase
    {
        private static readonly string sessionName = "AttachFile.webuploader";
        protected string ParamStr;

        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;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 删除选中行
                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项!");
                btnDelete.ConfirmText = String.Format("你确定要删除选中的&nbsp;<b><script>{0}</script></b>&nbsp;个文件吗?", Grid1.GetSelectedCountReference());
                
                Session[sessionName] = null;
                ToKeyId = Request.QueryString["toKeyId"];
                AttachPath = Request.QueryString["path"];
                ParamStr = sessionName + "|" + AttachPath;
                MenuId = Request.QueryString["menuId"];
                BindGrid();
            }
            else
            {
                if (GetRequestEventArgument() == "RebindGrid")
                {
                    BindGrid();
                }
            }
        }

        #region BindGrid

        private void BindGrid()
        {
            Grid1.DataSource = GetSourceData();
            Grid1.DataBind();
        }

        #endregion

        #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 == "Attach")
            {
                JArray source = GetSourceData();

                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;

                    if (item.Value<string>("id") == e.RowID)
                    {

                        try
                        {
                            string savedName = item.Value<string>("savedName");

                            string url = BLL.Funs.RootPath + AttachPath + "\\" + savedName;
                            FileInfo info = new FileInfo(url);
                            if (!info.Exists || string.IsNullOrEmpty(savedName))
                            {
                                url = BLL.Funs.RootPath + "Images//Null.jpg";
                                info = new FileInfo(url);
                            }

                            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.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.Close();
                            
                        }
                        catch (Exception)
                        {
                           
                        }
                    }
                }

               
            }
        }
        #endregion

        #region GetSourceData

        private JArray GetSourceData()
        {
            
            if (Session[sessionName] == null)
            {
                var sour = from x in BLL.Funs.DB.AttachFile where x.ToKeyId == ToKeyId select x;

                if (sour.Count() > 0)
                {
                    Session[sessionName] = JArray.Parse(sour.First().AttachSource);
                }
                else
                {
                    Session[sessionName] = new JArray();
                }
            }

            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<string>("id") == rowId)
                {

                    try
                    {
                        string savedName = item.Value<string>("savedName");
                        System.IO.File.Delete(Server.MapPath("~/" + AttachPath + "\\" + savedName));
                    }
                    catch (Exception)
                    {
                        // 尝试删除物理文件失败,不做处理
                    }

                    source.RemoveAt(i);
                    break;
                }
            }

             Session[sessionName] = source;
        }

        #endregion

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Model.FCLDB db = Funs.DB;
            JArray source = GetSourceData();
            string type = Request.QueryString["type"];
            string mainTableId = Request.QueryString["mainTableId"];

            if (type == "add")
            {
                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;
                    if (item.Value<string>("savedName").Contains("&") || item.Value<string>("savedName").Contains(">")
                        || item.Value<string>("savedName").Contains("<") || item.Value<string>("savedName").Contains("%") 
                        || item.Value<string>("savedName").Contains("?") 
                        || item.Value<string>("savedName").Contains(":") || item.Value<string>("savedName").Contains("/"))
                    {
                        Alert.ShowInParent("文件名不能包含 &,>,<,%,?,:,/ 等字符");
                        return;
                    }
                }
                for (int i = 0, count = source.Count; i < count; i++)
                {
                    JObject item = source[i] as JObject;
                    string attachUrl = AttachPath + "\\" + item.Value<string>("savedName").Replace('/', '\\');
                    string fileName = item.Value<string>("name");
                    string name = fileName.Substring(0, fileName.LastIndexOf("."));
                    string Id = string.Empty;
                    if (MenuId == BLL.Const.StandardTemplateMenuId)
                    {
                        Model.StandardTemplate temp = new Model.StandardTemplate();
                        Id = SQLHelper.GetNewID(typeof(Model.StandardTemplate));
                        temp.TemplateId = Id;
                        temp.TemplateTypeId = ToKeyId;
                        temp.UploadDate = DateTime.Now;
                        temp.UploadMan = this.CurrUser.UserId;
                        temp.AttachUrl = attachUrl;
                        BLL.StandardTemplateService.AddStandardTemplate(temp);
                        BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add Standard Template!");
                    }
                    if (MenuId == BLL.Const.SESRelatedDateMenuId)
                    {
                        if (AttachPath.Contains("SignedContracts"))
                        {
                            Model.FC_SignedContracts newSignedContracts = new Model.FC_SignedContracts();
                            Id = SQLHelper.GetNewID(typeof(Model.FC_SignedContracts));
                            newSignedContracts.FileId = Id;
                            newSignedContracts.FC_ID = Convert.ToInt32(mainTableId);
                            newSignedContracts.FileName = fileName;
                            newSignedContracts.FileType = ToKeyId;
                            newSignedContracts.UploadMan = this.CurrUser.UserId;
                            newSignedContracts.UploadDate = DateTime.Now;
                            newSignedContracts.AttachUrl = attachUrl;
                            BLL.SignedContractsService.AddSignedContracts(newSignedContracts);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add FC Signed Contracts!");
                        }
                        else
                        {
                            Model.FC_ContractManagement newContract = new Model.FC_ContractManagement();
                            Id = SQLHelper.GetNewID(typeof(Model.FC_ContractManagement));
                            newContract.FileId = Id;
                            newContract.FC_ID = Convert.ToInt32(mainTableId);
                            newContract.FileName = fileName;
                            newContract.FileTypeId = ToKeyId;
                            newContract.UploadMan = this.CurrUser.UserId;
                            newContract.UploadDate = DateTime.Now;
                            newContract.AttachUrl = attachUrl;
                            BLL.ContractManagementService.AddContractManagement(newContract);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add FC Contract Management!");
                        }
                    }
                    if (MenuId == BLL.Const.OneTimeContractsMenuId)
                    {
                        if (AttachPath.Contains("SignedContracts"))
                        {
                            Model.EMC_OneTimeSignedContracts newSignedContracts = new Model.EMC_OneTimeSignedContracts();
                            Id = SQLHelper.GetNewID(typeof(Model.EMC_OneTimeSignedContracts));
                            newSignedContracts.FileId = Id;
                            newSignedContracts.OneTimeContractsId = mainTableId;
                            newSignedContracts.FileName = fileName;
                            newSignedContracts.FileType = ToKeyId;
                            newSignedContracts.UploadMan = this.CurrUser.UserId;
                            newSignedContracts.UploadDate = DateTime.Now;
                            newSignedContracts.AttachUrl = attachUrl;
                            BLL.OneTimeSignedContractsService.AddOneTimeSignedContracts(newSignedContracts);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add One Time Contracts Signed Contracts!");
                        }
                        else
                        {
                            Model.EMC_OneTimeContractManagement newContract = new Model.EMC_OneTimeContractManagement();
                            Id = SQLHelper.GetNewID(typeof(Model.EMC_OneTimeContractManagement));
                            newContract.FileId = Id;
                            newContract.OneTimeContractsId = mainTableId;
                            newContract.FileName = fileName;
                            newContract.FileTypeId = ToKeyId;
                            newContract.UploadMan = this.CurrUser.UserId;
                            newContract.UploadDate = DateTime.Now;
                            newContract.AttachUrl = attachUrl;
                            BLL.OneTimeContractManagementService.AddOneTimeContractManagement(newContract);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add One Time Contracts Contract Management!");
                        }
                    }
                    if (MenuId == BLL.Const.CTSalesContractsMenuId)
                    {
                        if (AttachPath.Contains("SignedContracts"))
                        {
                            Model.EMC_CTSalesSignedContracts newSignedContracts = new Model.EMC_CTSalesSignedContracts();
                            Id = SQLHelper.GetNewID(typeof(Model.EMC_CTSalesSignedContracts));
                            newSignedContracts.FileId = Id;
                            newSignedContracts.CTSalesContractsId = mainTableId;
                            newSignedContracts.FileName = fileName;
                            newSignedContracts.FileType = ToKeyId;
                            newSignedContracts.UploadMan = this.CurrUser.UserId;
                            newSignedContracts.UploadDate = DateTime.Now;
                            newSignedContracts.AttachUrl = attachUrl;
                            BLL.CTSalesSignedContractsService.AddCTSalesSignedContracts(newSignedContracts);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add CT Sales Contracts Signed Contracts!");
                        }
                        else
                        {
                            Model.EMC_CTSalesContractManagement newContract = new Model.EMC_CTSalesContractManagement();
                            Id = SQLHelper.GetNewID(typeof(Model.EMC_CTSalesContractManagement));
                            newContract.FileId = Id;
                            newContract.CTSalesContractsId = mainTableId;
                            newContract.FileName = fileName;
                            newContract.FileTypeId = ToKeyId;
                            newContract.UploadMan = this.CurrUser.UserId;
                            newContract.UploadDate = DateTime.Now;
                            newContract.AttachUrl = attachUrl;
                            BLL.CTSalesContractManagementService.AddCTSalesContractManagement(newContract);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add CT Sales Contracts Signed Contract Management!");
                        }
                    }
                    if (MenuId==BLL.Const.TemplateMenuId)
                    {
                        Model.SupportDocument_Template temp = new Model.SupportDocument_Template();
                        Id = ToKeyId;
                        temp.TemplateId = Id;
                        temp.Template = name;
                        temp.UploadDate = DateTime.Now;
                        temp.UploadBy = this.CurrUser.UserId;
                        temp.AttachUrl = attachUrl;
                        BLL.TemplateService.AddTemplate(temp);
                        BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add Template!");
                    }
                    if (MenuId==BLL.Const.GuideManualMenuId)
                    {
                        Model.SupportDocument_GuideManual temp = new Model.SupportDocument_GuideManual();
                        Id = ToKeyId;
                        temp.GuideManualId = Id;
                        temp.GuideManual = name;
                        temp.UploadDate = DateTime.Now;
                        temp.UploadBy = this.CurrUser.UserId;
                        temp.AttachUrl = attachUrl;
                        BLL.GuideManualService.AddGuideManual(temp);
                        BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Add Guide Manual!");
                    }

                    Model.AttachFile att = new Model.AttachFile();
                    att.AttachFileId = BLL.SQLHelper.GetNewID(typeof(Model.AttachFile));
                    att.ToKeyId = Id;
                    att.AttachSource = "[" + source[i].ToString() + "]";
                    att.AttachUrl = attachUrl;
                    att.MenuId = MenuId;
                    db.AttachFile.InsertOnSubmit(att);
                    db.SubmitChanges();
                }
            }
            else
            {
                if (source.Count > 1)
                {
                    Alert.ShowInParent("只能对该附件编辑后重新上传!");
                    return;
                }
                if (source.Count() > 0)
                {
                    JObject item = source[0] as JObject;
                    if (item.Value<string>("savedName").Contains("&") || item.Value<string>("savedName").Contains(">")
                       || item.Value<string>("savedName").Contains("<") || item.Value<string>("savedName").Contains("%")
                       || item.Value<string>("savedName").Contains("?")
                       || item.Value<string>("savedName").Contains(":") || item.Value<string>("savedName").Contains("/"))
                    {
                        Alert.ShowInParent("文件名不能包含 &,>,<,%,?,:,/ 等字符");
                        return;
                    }

                    string attachUrl = AttachPath + "\\" + item.Value<string>("savedName").Replace('/', '\\');
                    string fileName = item.Value<string>("name");
                    if (MenuId == BLL.Const.StandardTemplateMenuId)
                    {
                        Model.StandardTemplate temp = new Model.StandardTemplate();
                        temp.TemplateId = ToKeyId;
                        temp.UploadDate = DateTime.Now;
                        temp.AttachUrl = attachUrl;
                        temp.UploadMan = this.CurrUser.UserId;
                        BLL.StandardTemplateService.UpdateStandardTemplate(temp);
                        BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify Standard Template!");
                    }

                    if (MenuId == BLL.Const.SESRelatedDateMenuId)
                    {
                        if (AttachPath.Contains("SignedContracts"))
                        {
                            Model.FC_SignedContracts newSignedContracts = new Model.FC_SignedContracts();
                            newSignedContracts.FileId = ToKeyId;
                            newSignedContracts.FileName = fileName;
                            newSignedContracts.UploadMan = this.CurrUser.UserId;
                            newSignedContracts.UploadDate = DateTime.Now;
                            newSignedContracts.AttachUrl = attachUrl;
                            BLL.SignedContractsService.UpdateSignedContracts(newSignedContracts);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify FC Signed Contracts!");
                        }
                        else
                        {
                            Model.FC_ContractManagement newContract = new Model.FC_ContractManagement();
                            newContract.FileId = ToKeyId;
                            newContract.FileName = fileName;
                            newContract.UploadMan = this.CurrUser.UserId;
                            newContract.UploadDate = DateTime.Now;
                            newContract.AttachUrl = attachUrl;
                            BLL.ContractManagementService.UpdateContractManagement(newContract);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify FC Contract Management!");
                        }
                    }

                    if (MenuId == BLL.Const.OneTimeContractsMenuId)
                    {
                        if (AttachPath.Contains("SignedContracts"))
                        {
                            Model.EMC_OneTimeSignedContracts newSignedContracts = new Model.EMC_OneTimeSignedContracts();
                            newSignedContracts.FileId = ToKeyId;
                            newSignedContracts.FileName = fileName;
                            newSignedContracts.UploadMan = this.CurrUser.UserId;
                            newSignedContracts.UploadDate = DateTime.Now;
                            newSignedContracts.AttachUrl = attachUrl;
                            BLL.OneTimeSignedContractsService.UpdateOneTimeSignedContracts(newSignedContracts);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify One Time Contracts Signed Contracts!");
                        }
                        else
                        {
                            Model.EMC_OneTimeContractManagement newContract = new Model.EMC_OneTimeContractManagement();
                            newContract.FileId = ToKeyId;
                            newContract.FileName = fileName;
                            newContract.UploadMan = this.CurrUser.UserId;
                            newContract.UploadDate = DateTime.Now;
                            newContract.AttachUrl = attachUrl;
                            BLL.OneTimeContractManagementService.UpdateOneTimeContractManagement(newContract);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify One Time Contracts Contract Management!");
                        }
                    }

                    if (MenuId == BLL.Const.CTSalesContractsMenuId)
                    {
                        if (AttachPath.Contains("SignedContracts"))
                        {
                            Model.EMC_CTSalesSignedContracts newSignedContracts = new Model.EMC_CTSalesSignedContracts();
                            newSignedContracts.FileId = ToKeyId;
                            newSignedContracts.FileName = fileName;
                            newSignedContracts.UploadMan = this.CurrUser.UserId;
                            newSignedContracts.UploadDate = DateTime.Now;
                            newSignedContracts.AttachUrl = attachUrl;
                            BLL.CTSalesSignedContractsService.UpdateCTSalesSignedContracts(newSignedContracts);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify CT Sales Contracts Signed Signed Contracts!");
                        }
                        else
                        {
                            Model.EMC_CTSalesContractManagement newContract = new Model.EMC_CTSalesContractManagement();
                            newContract.FileId = ToKeyId;
                            newContract.FileName = fileName;
                            newContract.UploadMan = this.CurrUser.UserId;
                            newContract.UploadDate = DateTime.Now;
                            newContract.AttachUrl = attachUrl;
                            BLL.CTSalesContractManagementService.UpdateCTSalesContractManagement(newContract);
                            BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify CT Sales Contracts Signed Contract Management!");
                        }
                    }

                    if (MenuId==BLL.Const.TemplateMenuId)
                    {
                        Model.SupportDocument_Template temp = new Model.SupportDocument_Template();
                        temp.TemplateId = ToKeyId;
                        temp.Template = fileName;
                        temp.UploadDate = DateTime.Now;
                        temp.AttachUrl = attachUrl;
                        temp.UploadBy = this.CurrUser.UserId;
                        BLL.TemplateService.UpdateTemplate(temp);
                        BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify Template!");
                    }

                    if (MenuId==BLL.Const.GuideManualMenuId)
                    {
                        Model.SupportDocument_GuideManual temp = new Model.SupportDocument_GuideManual();
                        temp.GuideManualId = ToKeyId;
                        temp.GuideManual = fileName;
                        temp.UploadDate = DateTime.Now;
                        temp.AttachUrl = attachUrl;
                        temp.UploadBy = this.CurrUser.UserId;
                        BLL.GuideManualService.UpdateGuideManual(temp);
                        BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Modify Guide Manual!");
                    }

                    var sour = from x in db.AttachFile where x.ToKeyId == ToKeyId select x;
                    Model.AttachFile att = db.AttachFile.FirstOrDefault(x => x.AttachFileId == sour.First().AttachFileId);
                    if (att != null)
                    {
                        att.ToKeyId = ToKeyId;
                        att.AttachSource = source.ToString();
                        att.AttachUrl = attachUrl;
                        att.MenuId = MenuId;
                        db.SubmitChanges();
                    }
                }
                else
                {
                    Alert.ShowInParent("请上传附件!");
                    return;
                }
            }
            ShowNotify("保存成功!");
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        #region 获取权限按钮
        /// <summary>
        /// 获取按钮权限
        /// </summary>
        /// <param name="button"></param>
        /// <returns></returns>
        private void GetButtonPower()
        {
            //var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, MenuId);
            //if (buttonList.Count > 0)
            //{
            //    if (!buttonList.Contains(BLL.Const.BtnSave))
            //    {
            //        this.btnSelectFiles.Hidden = true;
            //        this.btnDelete.Hidden = true;
            //        this.btnSave.Hidden = true;
            //    }                              
            //}
        }
        #endregion

    }
}