namespace Kesion.NET.WebSite.Admin.Include
{
    using System;
    using System.IO;
    using System.Xml;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Services;
    using Kesion.APPCode;
    using Kesion.BLL;
    using Kesion.Cache;
    using Kesion.Components;
    using Kesion.Publics;
    using Kesion.XML;
    using Kesion.Config;
    using System.Web.SessionState;

    /// <summary>
    /// 考试的channelid定为101
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Upload : IHttpHandler, IRequiresSessionState
    {
        public int ChannelID = 0;
        public string FieldID;
        private int upBySwf = 0;
        public string CurrPath = string.Empty;
        public string UpFilesDir = string.Empty;
        public ModelInfo __info;
        public string module = string.Empty;
        XmlNode xn = null;
        public string thumbarr = string.Empty; //XML文件配置上传，自动生成的小图集
        public int thumbwidth = 0;   //XML文件配置上传里的缩略图宽度
        public int thumbheight = 0;  //XML文件配置上传里的缩略图高度
        private static string myUploadDir = "/UploadFiles/";  //当前上传用户的登录目录

        //管理员登录检测
        public static bool chkLogin()
        {
            #region 管理员登录检测
            if (string.IsNullOrEmpty(KSCMS.S("AdminUser")) || string.IsNullOrEmpty(KSCMS.S("AdminPass")))
                return false;
            else
            {
                string UserName = Utils.ChkSQL(KSCMS.S("AdminUser"));
                if (DataFactory.Exists("KS_Admin","username='" + UserName + "' and password='" + Utils.ChkSQL(KSCMS.S("AdminPass")) + "'"))
                {

                    #region 记录cookies
                    AdminInfo __info = AdminManage.GetAdminInfo(UserName);
                    myUploadDir = string.Concat(MyCache.GetCacheConfig(0), MyCache.GetCacheConfig(22), "/", DateTime.Now.Year, "-", DateTime.Now.Month, "/", __info.ID, "/");
                    
                    /*
                    HttpCookie ck = new HttpCookie("Admin");
                    if (BaseConfigManage.AllowSubDomain.ToLower().Equals("true")) //启用二级域名
                    {
                        ck.Domain = BaseConfigManage.RootDomain;
                    }

                    ck.Values.Add("AdminID", __info.ID.ToString());
                    ck.Values.Add("AdminUser", __info.UserName);
                    ck.Values.Add("AdminPass", __info.PassWord);
                    ck.Values.Add("UserType", __info.UserType.ToString());
                    ck.Values.Add("PowerList", __info.PowerList);
                    ck.Values.Add("DocPower", __info.DocPower.ToString());
                    ck.Values.Add("AdminLoginCode", ConfigManage.GetConfig().SiteManageCode);
                    HttpContext.Current.Response.AppendCookie(ck);
                    ck.Expires = DateTime.Now.AddMinutes(Utils.StrToInt(MyCache.GetCacheConfig(20)));
                    HttpContext.Current.Session.Add("adminName", UserName);
                     */
                    #endregion
                   
                    return true;
                }
                else
                    return false;

            }
            #endregion
        }
        //认证码检测
        public static bool chkCode()
        {
            #region 认证码检测
            if (ConfigManage.GetConfig().EnableSiteManageCode == 0)
                return true;
            else
            {

                if (KSCMS.S("AdminLoginCode") != ConfigManage.GetConfig().SiteManageCode)
                    return false;
                else
                    return true;

            }
            #endregion
        }
        /// <summary>
        /// 检查上传权限
        /// </summary>
        /// <returns></returns>
        public static bool CheckPurview()
        {
            #region 检查上传权限
            if (KSCMS.S("UserType") == "1")   //超级管理员拥有所有权限
            {
                return true;
            }
            else
            {
                string powerList = KSCMS.S("PowerList").ToLower();
                if (!string.IsNullOrEmpty(KSSecurity.PowerID))
                {
                    if (KSSecurity.ModelID == "0" || KSSecurity.ModelID == string.Empty)
                    {
                        return true;
                    }
                    if (KSSecurity.PowerID == "0")
                    {
                        return true;
                    }
                    else if (!Utils.InArray(KSSecurity.PowerID.ToLower(), powerList))
                    {
                        return false;

                    }
                    else
                    {
                        return true;
                    }

                }

            }
            return false;
            #endregion
        }


        public void ProcessRequest(HttpContext context)
        {

            // context.Response.ContentType = "text/plain";
            // context.Response.Write("Hello World");

            module = KSCMS.S("module");
            ChannelID = Utils.StrToInt(KSCMS.S("channelid"), 0);
            FieldID = KSCMS.S("FieldID");
            upBySwf = Utils.StrToInt(KSCMS.S("upBySwf"));

            KSSecurity.ModelID = "content";                                 //模块ID号
            KSSecurity.PowerID = MyCache.GetCacheModel(ChannelID, 1) + "6";   //子顶权限ID号

            #region 判断上传权限
            if (upBySwf == 1)
            {
                if (chkLogin() == false || chkCode() == false || CheckPurview() == false)
                {
                    KSCMS.Die("error:对不起，您没有上传的权限!");
                    return;
                }
            }
            else
            {
                if (chkLogin() == false || chkCode() == false || CheckPurview() == false)
                {
                    JS.AlertDoFun("对不起，您没有上传的权限!", "history.back();");
                    return;
                }
            }
            #endregion



            string FieldXML = string.Empty;
            if (ChannelID > 0)
            {
                __info = ModelManage.GetModelInfo(ChannelID);
                if (__info == null) return;
                FieldXML = __info.FieldsXML;
            }
            string AllowExtStr = string.Empty;
            int AllowMaxSize = 0;


            #region 得到允许上传的扩展名及文件大小
            if (!string.IsNullOrEmpty(module))
            {
                #region XML配置文件上传
                XmlDocument doc = new XmlDocument();
                doc.Load(Utils.GetMapPath("~/config/uploadsetting.config"));
                xn = doc.SelectSingleNode("//uploadsetting/item[@module='" + module + "']");
                if (xn == null)
                {
                    KSCMS.Die("error:读取配置文件出错!");
                }
                AllowExtStr = xn.SelectSingleNode("@allowext").InnerText;
                AllowMaxSize = Utils.StrToInt(xn.SelectSingleNode("@limitsize").InnerText);
                if (xn.Attributes["thumbarr"] != null)
                {
                    thumbarr = xn.SelectSingleNode("@thumbarr").InnerText;
                }
                if (xn.Attributes["thumbwidth"] != null)
                {
                    thumbwidth = Utils.StrToInt(xn.SelectSingleNode("@thumbwidth").InnerText);
                }
                if (xn.Attributes["thumbheight"] != null)
                {
                    thumbheight = Utils.StrToInt(xn.SelectSingleNode("@thumbheight").InnerText);
                }
                #endregion
            }
            else if (FieldID == "-1")   //按模型上传，不分字段的，如图片系统的批量上传，下载系统的上传软件 ,商品里的上传组图等等
            {
                #region 按模型上传，不分字段的，如图片系统的批量上传，下载系统的上传软件 ,商品里的上传组图等等
                #region 从selectfile.aspx文件来的上传，允许改变上传路径
                CurrPath = KSCMS.S("CurrPath");
                if (!string.IsNullOrEmpty(CurrPath))
                {
                    //正则表达式   
                    string strExp = @"^" + string.Concat(KSCMS.GetInstallDir(), MyCache.GetCacheConfig(22), @"\/");
                    //创建正则表达式对象   
                    Regex myRegex = new Regex(strExp);

                    if (!myRegex.IsMatch(CurrPath))
                    {
                        KSCMS.Die("error:非法上传目录!");
                    }
                }
                #endregion

                if (__info != null)
                {
                    if (KSCMS.S("UpType") == "File")
                    {
                        AllowExtStr = string.Concat(__info.AllowUpFlashType, "|", __info.AllowUpMediaType, "|", __info.AllowUpOtherType, "|", __info.AllowUpPhotoType, "|", __info.AllowUpRealType);
                        AllowMaxSize = __info.AllowUpFilesSize;

                    }
                    else
                    {
                        switch (__info.BasicType)
                        {
                            case 1:
                                AllowExtStr = string.Concat(__info.AllowUpFlashType, "|", __info.AllowUpMediaType, "|", __info.AllowUpOtherType, "|", __info.AllowUpPhotoType, "|", __info.AllowUpRealType);
                                AllowMaxSize = __info.AllowUpFilesSize;
                                break;
                            case 2:
                                AllowExtStr = __info.AllowUpPhotoType;
                                AllowMaxSize = __info.AllowUpFilesSize;
                                break;
                            case 3:
                                AllowExtStr = string.Concat(__info.AllowUpFlashType, "|", __info.AllowUpMediaType, "|", __info.AllowUpOtherType, "|", __info.AllowUpPhotoType, "|", __info.AllowUpRealType);
                                AllowMaxSize = __info.AllowUpFilesSize;
                                break;
                            case 4:
                                thumbwidth = Utils.StrToInt(MyCache.GetCacheShopConfig(5));
                                thumbheight = Utils.StrToInt(MyCache.GetCacheShopConfig(6));
                                AllowExtStr = __info.AllowUpPhotoType;
                                AllowMaxSize = __info.AllowUpFilesSize;
                                break;
                            default:
                                AllowExtStr = string.Empty;
                                AllowMaxSize = 0;
                                break;
                        }
                    }
                }
                else
                {
                    AllowExtStr = MyCache.GetCacheConfig(52);
                    AllowMaxSize = Utils.StrToInt(MyCache.GetCacheConfig(51));
                }
                #endregion
            }
            else if (FieldID.ToLower().Equals("defaultpic"))  //所有模型的默认小图
            {
                #region 所有模型的默认小图
                if (__info != null)
                {
                    AllowExtStr = __info.AllowUpPhotoType;
                    AllowMaxSize = __info.AllowUpFilesSize;
                }
                #endregion
            }
            else if (FieldID.ToLower().Equals("doc"))
            {
                if (__info != null)
                {
                    AllowExtStr = __info.AllowUpOtherType;
                    AllowMaxSize = __info.AllowUpFilesSize;
                }
            }
            else
            {
                AllowExtStr = XmlObject.GetStrXmlNode(FieldXML, string.Format(@"//Model/Field[@Name='{0}']/AllowFileExt", FieldID));
                AllowMaxSize = Utils.StrToInt(XmlObject.GetStrXmlNode(FieldXML, string.Format(@"//Model/Field[@Name='{0}']/MaxFileSize", FieldID)), 0);

            }
            #endregion

            if (!string.IsNullOrEmpty(CurrPath))
            {
                UpFilesDir = CurrPath;
            }
            else
            {
                UpFilesDir = myUploadDir;
            }
            
            HtmlTags.Function.CreateFolders(UpFilesDir);
            int num = 0;

            // try
            {
                string SaveFileName = string.Empty;
                string FileExt = string.Empty;
                HttpPostedFile file;

                #region 检查上传文件合法性
                for (int i = 0; i < context.Request.Files.Count; ++i)
                {

                    file = context.Request.Files[i];
                    if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) continue;
                    num++;
                    if (file.FileName != string.Empty && file != null)
                    {
                        FileExt = System.IO.Path.GetExtension(file.FileName).ToLower();
                    }

                    if (file.FileName.IndexOf(";") != -1)
                    {
                        if (upBySwf == 1)
                            KSCMS.Die("error:对不起,您的文件名不合法!");
                        else
                            JS.AlertDoFun("对不起,您的文件名不合法！", "history.back();");
                        return;
                    }


                    if (!(UploadCheck.CheckAllowUpFiles(AllowExtStr, FileExt)))
                    {

                        if (upBySwf == 1)
                            KSCMS.Die("error:上传的文件的类型不允许，允许上传的类型为：" + AllowExtStr + "!");
                        else
                            JS.AlertDoFun("上传的文件的类型不允许，允许上传的类型为：" + AllowExtStr + "！", "history.back();");
                        return;
                    }


                    if (file.ContentLength / 1024 > AllowMaxSize)
                    {
                        if (upBySwf == 1)
                            KSCMS.Die("error:文件超过允许上传的大小，最大允许上传 " + AllowMaxSize + " KB的文件!");
                        else
                            JS.AlertDoFun("文件超过允许上传的大小，最大允许上传 " + AllowMaxSize + " KB的文件!", "history.back();");
                        return;
                    }

                }


                if (num < 1)
                {
                    if (upBySwf == 1)
                        KSCMS.Die("error:对不起,您没有选择文件!");
                    else
                        JS.AlertDoFun("对不起，您没有选择要上传的文件！", "history.back();");
                    KSCMS.Die("");
                }
                #endregion


                for (int i = 0; i < context.Request.Files.Count; ++i)
                {
                    #region 构构上传文件名并上传
                    file = context.Request.Files[i];
                    if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) continue;
                    if (KSCMS.S("NoReName") == "1")
                    {
                        SaveFileName = UpFilesDir + KSCMS.S("fileNames");
                    }
                    if (string.IsNullOrEmpty(SaveFileName) || (KSCMS.S("NoReName") != "1"))
                    {
                        SaveFileName = Utils.RndNum(1);
                        SaveFileName += Utils.CutString(DateTime.Now.ToFileTimeUtc().ToString(), 0, 15);
                    }

                    if (KSCMS.S("NoReName") != "1")
                    {
                        FileExt = System.IO.Path.GetExtension(file.FileName).ToLower();
                        SaveFileName = UpFilesDir + SaveFileName + FileExt;
                    }
                    FileExt = System.IO.Path.GetExtension(SaveFileName).ToLower();
                    if (UploadCheck.CheckAllowUpFiles(AllowExtStr, FileExt) == false)
                    {
                        if (upBySwf == 1)
                            KSCMS.Die("error:对不起,保存的文件类型不允许!");
                        else
                            KSCMS.Die("<script>jQuery(function(){top.KesionJS.Alert('对不起,保存的文件类型不允许!','history.back();');});</script>");
                    }

                 //   KSCMS.Die("error:" + context.Request.Files.Count +"===="+ file.FileName + "==" + HttpContext.Current.Server.MapPath(SaveFileName));
                    try
                    {
                        file.SaveAs(HttpContext.Current.Server.MapPath(SaveFileName));
                    }
                    catch (Exception ex)
                    {
                        KSCMS.Die("error:" + ex.Message );
                    }
                    
                    #endregion

                    #region 判断图片类型是否合法
                    bool isPic = false;
                    if (FileExt == ".jpeg" || FileExt == ".gif" || FileExt == ".jpg" || FileExt == ".bmp" || FileExt == ".png")
                    {
                        if (UploadCheck.IsImage(HttpContext.Current.Server.MapPath(SaveFileName)) == false)
                        {
                            Kesion.HtmlTags.Function.DelFile(SaveFileName);
                            if (upBySwf == 1)
                            {
                                KSCMS.Die("error:对不起,文件[" + SaveFileName + "]不合法，不是有效的图片!");
                            }
                            else
                            {
                                JS.AlertDoFun("对不起,文件[" + SaveFileName + "]不合法，不是有效的图片！", "history.back();");
                            }
                            continue;
                        }
                        isPic = true;
                    }
                    #endregion


                    #region 远程附件
                    FtpWeb ft = null;
                    if (MyCache.GetCacheConfig(59).ToString() == "1")
                    {
                        ft = new FtpWeb();
                    }
                    #endregion

                    #region 生成缩略图
                    bool thumbRemoteTF = false;
                    if (KSCMS.S("CreateThumbs") == "1" && isPic)
                    {
                        
                        if (thumbwidth > 0 || thumbheight > 0)
                        {
                            WaterMarkThumbs.CreateThumbs(HttpContext.Current.Server.MapPath(SaveFileName), thumbwidth, thumbheight);
                        }
                        else
                        {
                            WaterMarkThumbs.CreateThumbs(HttpContext.Current.Server.MapPath(SaveFileName));
                        }
                        #region 远程附件
                        if (MyCache.GetCacheConfig(59).ToString() == "1")
                        {
                            string ext = Path.GetExtension(SaveFileName);
                            string newfile = Regex.Replace(SaveFileName, ext, "_S" + ext);
                            if (ft.Upload(newfile) == "success")
                            {
                                thumbRemoteTF = true;
                                if (MyCache.GetCacheConfig(67) == "1") HtmlTags.Function.DelFile(newfile);
                            }
                        }
                        #endregion
                    }
                    #endregion

                    #region 加水印
                    if (KSCMS.S("addwatermark").Equals("1") && isPic)
                    {
                        try
                        {
                            WaterMarkThumbs.AddWaterMark(HttpContext.Current.Server.MapPath(SaveFileName));
                        }
                        catch
                        { }
                    }
                    #endregion

                    #region 远程附件
                    if (MyCache.GetCacheConfig(59).ToString() == "1")
                    {
                        if (ft.Upload(SaveFileName) == "success")
                        {
                            if (MyCache.GetCacheConfig(67) == "1") HtmlTags.Function.DelFile(SaveFileName);
                            SaveFileName = MyCache.GetCacheConfig(65) + SaveFileName;
                        }
                    }
                    ft = null;
                    #endregion


                    if (!string.IsNullOrEmpty(module))
                    {
                        #region XML配置上传
                        if (!string.IsNullOrEmpty(thumbarr))
                        {
                            string temp = SaveFileName;
                            string[] tarr = thumbarr.Split(',');
                            foreach (string pic in tarr)
                            {
                                if (pic.IndexOf("x") != -1)
                                {
                                    string ext = Path.GetExtension(SaveFileName);
                                    string newfile = Regex.Replace(SaveFileName, ext, "_" + pic + ext);
                                    WaterMarkThumbs.CreateThumbs(HttpContext.Current.Server.MapPath(SaveFileName), Utils.StrToInt(pic.Split('x')[0]), Utils.StrToInt(pic.Split('x')[1]), "_" + pic);
                                    temp += "@" + newfile;
                                }
                            }
                            KSCMS.Die(temp);
                        }
                        else if (KSCMS.S("CreateThumbs") == "1")
                        {
                            string ext = Path.GetExtension(SaveFileName);
                            string thumbFile = Regex.Replace(SaveFileName, ext, "_S" + ext);
                            KSCMS.Die(SaveFileName + "@" + thumbFile);
                        }
                        else
                        {
                            KSCMS.Die(SaveFileName);
                        }
                        #endregion
                    }
                    else if (FieldID == "-1")
                    {
                        #region 按模型上传，不分字段的，如图片系统的批量上传，下载系统的上传软件 ,商品里的上传组图等等
                        if (__info != null)
                        {
                            if (KSCMS.S("UpType") == "File")
                            {
                                string maxId = Public.AddAffixFile(SaveFileName, KSCMS.S("aliasName"), Utils.StrToInt(KSCMS.S("dSize")), ChannelID, 0);
                                KSCMS.Die(SaveFileName + "|" + maxId + "|" + KSCMS.S("EditorID"));
                            }
                            else
                            {
                                #region 按模型上传
                                if (__info.BasicType == 2 || __info.BasicType == 4)
                                {
                                    string thumbFile = SaveFileName;
                                    if (KSCMS.S("CreateThumbs") == "1")
                                    {
                                        string ext = System.IO.Path.GetExtension(SaveFileName);
                                        thumbFile = System.Text.RegularExpressions.Regex.Replace(SaveFileName, ext, "_S" + ext);
                                    }
                                   
                                    if (__info.BasicType == 4) //商城模型上传组图，大图处理
                                    {
                                        int pictureWidth = Utils.StrToInt(MyCache.GetCacheShopConfig(7));
                                        int pictureHeight = Utils.StrToInt(MyCache.GetCacheShopConfig(8));
                                        if (pictureWidth != 0)
                                        {
                                            WaterMarkThumbs.CreateThumbs(Utils.GetMapPath(SaveFileName), pictureWidth, pictureHeight, true);
                                        }
                                    }
                                    KSCMS.Die(SaveFileName + "@" + thumbFile + "@" + file.FileName.Substring(0, file.FileName.LastIndexOf(".")));

                                }
                                else if (__info.BasicType == 3)
                                {
                                    if (upBySwf == 1)
                                        KSCMS.Die(SaveFileName);
                                    else
                                        JS.AlertDoFun("恭喜，上传成功！", string.Format(@"parent.SetDownUrlByUpLoad('{0}');", SaveFileName));
                                }
                                #endregion
                            }

                        }
                        else
                        {
                            if (upBySwf == 1) KSCMS.Die(SaveFileName);
                        }
                        #endregion
                    }
                    else
                    {
          
                        string ThumbPathFileName = string.Empty;
                        if (KSCMS.S("CreateThumbs") == "1" && isPic)
                        {
                            string ext = System.IO.Path.GetExtension(SaveFileName);
                            ThumbPathFileName = Regex.Replace(SaveFileName, ext, "_S" + ext);

                            if (FieldID.ToLower() != "defaultpic")
                            {
                                if (SaveFileName.ToLower().IndexOf("http://") != -1)
                                {
                                    SaveFileName = Utils.ReplaceString(SaveFileName, MyCache.GetCacheConfig(65), string.Empty, true);
                                }
                                (new FtpWeb()).Delete(SaveFileName);
                                HtmlTags.Function.DelFile(SaveFileName);
                                KSCMS.Die(ThumbPathFileName);
                            }

                            //远程附件
                            if (thumbRemoteTF == true && MyCache.GetCacheConfig(59) == "1" && ThumbPathFileName.ToLower().IndexOf(MyCache.GetCacheConfig(65).ToLower()) == -1)
                            {
                                ThumbPathFileName = MyCache.GetCacheConfig(65) + ThumbPathFileName;
                            }


                        }
                        else
                        {
                            ThumbPathFileName = SaveFileName;
                        }
                        if (string.IsNullOrEmpty(ThumbPathFileName)) ThumbPathFileName = SaveFileName;



                        if (upBySwf == 1)  //swfupload上传的
                        {
                            if (FieldID.ToLower() == "defaultpic")
                                KSCMS.Die(SaveFileName + "@" + ThumbPathFileName); //格式原图+小图
                            else
                                KSCMS.Die(SaveFileName);    //自定义字段
                        }
                        else
                        {
                            if (FieldID.ToLower() != "defaultpic")
                                JS.AlertDoFun("恭喜，文件上传成功！", string.Format("parent.document.getElementById('{0}').value='{1}';history.back();", FieldID, SaveFileName));
                            else
                                KSCMS.Die(string.Format("<script>parent.document.getElementById('{0}').value='{1}';{2};history.back();</script>", FieldID, ThumbPathFileName, MyCache.GetCacheModel(ChannelID, 4).Equals("1") ? string.Format(@"parent.insertHTMLToEditor('<img src=""{0}"" />');", SaveFileName) : ""));

                        }
                    }



                    // file.SaveAs(HttpContext.Current.Server.MapPath("/swfupload/file/" + Path.GetFileName(file.FileName)));
                }
            }
            //  catch (Exception ex)
            {
                //       context.Response.StatusCode = 500;
                //       context.Response.Write(ex.Message);
                //       context.Response.End();
            }
            //   finally
            //   {
            //       context.Response.End();
            //   }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
