using System;
using System.Web;
using System.IO;
using System.Collections;
using xabaraCOM;

/// <summary>
/// UEditor编辑器通用上传类
/// </summary>
public class Uploader
{
    fileDocument f = new fileDocument();
    sqlServer sql = new sqlServer();

    string state = "SUCCESS";

    string URL = null;
    string currentType = null;
    string filename = null;
    string originalName = null;
    string dt = DateTime.Now.ToString("yyyyMMdd");
    HttpPostedFile uploadFile = null;

    /**
      * 上传文件的主处理方法
      * @param HttpContext
      * @param string
      * @param  string[]
      *@param int
      * @return Hashtable
      */   
    public Hashtable upFile(HttpContext cxt, bool isImg, string[] filetype, int size)
    {
        if (String.IsNullOrEmpty(cxt.Session["AdminRndNums"] as string)) //基本session验证
        {
            state = "Logon failure";
            URL = "";
        }
        else
        {
            try
            {
                uploadFile = cxt.Request.Files[0];
                originalName = uploadFile.FileName;

                //格式验证
                if (checkType(filetype))
                {
                    state = "不允许的文件类型";
                }
                //大小验证
                if (checkSize(size))
                {
                    state = "文件大小超出网站限制";
                }
                //保存图片
                if (state == "SUCCESS")
                {
                    filename = reName();
                    uploadFile.SaveAs(this.getFolder() + filename);                    

                    if (isImg)
                    {
                        //加水印
                        string waterMarkText = xml.read("xabara.config", "waterMark", 180);
                        if (waterMarkText.Equals("xabara.com"))
                        {
                            f.addWaterPic(filename, true);
                        }
                        else
                        {
                            f.addTextWater(filename, true);
                        }
                        filename = cxt.Session["NewFile"].ToString();
                        //缩略图
                        f.MakeThumbnail(filename, 300, 0, "W");
                    }

                    //插入数据库
                    if (isImg)
                    {
                        sql.imgFileTable("news", "Img", filename, "", "news");
                    }
                    else
                    {
                        sql.imgFileTable("news", "File", filename, "", "news");
                    }

                    URL = f.filePath(filename);
                }
            }
            catch (Exception e)
            {
                state = "文件夹权限";
                URL = "";
            }
        }

        return getUploadInfo();
    }

    /**
     * 上传涂鸦的主处理方法
      * @param HttpContext
      * @param string
      * @param  string[]
      *@param string
      * @return Hashtable
     */
    public Hashtable upScrawl(HttpContext cxt, string base64Data)
    {
        if (String.IsNullOrEmpty(cxt.Session["AdminRndNums"] as string)) //基本session验证
        {
            state = "Logon failure";
            URL = "";
        }
        else
        {
            FileStream fs = null;
            try
            {
                filename = xabara.rnd("abc123", 5) + dt + DateTime.Now.ToString("HHmmss") + ".png";
                fs = File.Create(this.getFolder() + filename);

                byte[] bytes = Convert.FromBase64String(base64Data);
                fs.Write(bytes, 0, bytes.Length);

                URL = f.filePath(filename);
            }
            catch (Exception e)
            {
                state = "未知错误";
                URL = "";
            }
            finally
            {
                fs.Close();
                f.del(filename);
            }
        }

        return getUploadInfo();
    }

    /**
    * 获取文件信息
    * @param context
    * @param string
    * @return string
    */
    public string getOtherInfo(HttpContext cxt, string field)
    {
        string info = null;
        if (cxt.Request.Form[field] != null && !String.IsNullOrEmpty(cxt.Request.Form[field]))
        {
            info = field == "fileName" ? cxt.Request.Form[field].Split(',')[1] : cxt.Request.Form[field];
        }
        return info;
    }

    /**
     * 获取上传信息
     * @return Hashtable
     */
    private Hashtable getUploadInfo()
    {
        Hashtable infoList = new Hashtable();

        infoList.Add("state", state);
        infoList.Add("url", URL);

        if (currentType != null)
            infoList.Add("currentType", currentType);
        if (originalName != null)
            infoList.Add("originalName", originalName);
        return infoList;
    }

    /**
     * 重命名文件
     * @return string
     */
    private string reName()
    {
        return xabara.rnd("abc123", 5) + dt + DateTime.Now.ToString("HHmmss") + getFileExt();
    }

    /**
     * 文件类型检测
     * @return bool
     */
    private bool checkType(string[] filetype)
    {
        currentType = getFileExt();
        return Array.IndexOf(filetype, currentType) == -1;
    }

    /**
     * 文件大小检测
     * @param int
     * @return bool
     */
    private bool checkSize(int size)
    {
        return uploadFile.ContentLength >= (size * 1024 * 1024);
    }

    /**
     * 获取文件扩展名
     * @return string
     */
    private string getFileExt()
    {
        string[] temp = uploadFile.FileName.Split('.');
        return "." + temp[temp.Length - 1].ToLower();
    }

    /**
     * 按照日期自动创建存储文件夹
     */
    private string getFolder()
    {
        string uploadpath = HttpContext.Current.Server.MapPath(f.uploadFolder + dt + "/");
        if (!Directory.Exists(uploadpath))
        {
            Directory.CreateDirectory(uploadpath);
        }

        return uploadpath;
    }
}