using System;
using System.Collections;
using System.IO;
using Common;
using LogisticsSystem.Control;
using LogisticsSystem.Control.Helper;

namespace LogisticsSystem.SysMain.FileFlow
{
    public partial class Upload : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogin();
            if (IsPostBack) return;
            LogHelper.Log("用户:" + Session["Username"] + " 进入文件上传");
            files.InnerHtml = new FileHelper().GetUploadfiles((Hashtable) Session["upload"]);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!FileUpload1.HasFile)
            {
                Alert("请选择文件");
                return;
            }
            if (((Hashtable) Session["upload"]).ContainsKey(FileUpload1.PostedFile.FileName))
            {
                Alert("文件已存在");
                return;
            }
            if (!UploadFile())
            {
                Alert("上传失败");
            }
        }


        private bool UploadFile()
        {
            string uploadUrl = Server.MapPath("~/upload/" + Session["Userid"] + "/");//上传的目录

            string savePath = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/upload/" + Session["Userid"] +"/"; //保存在数据库的路径

            try
            {
                if (!Directory.Exists(uploadUrl))//判断文件夹是否已经存在
                {
                    Directory.CreateDirectory(uploadUrl);//创建文件夹
                }
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + FileUpload1.PostedFile.FileName.Split('.')[1];

                FileUpload1.PostedFile.SaveAs(uploadUrl + fileName);
                SetSession(FileUpload1.PostedFile.FileName, savePath + fileName);
                files.InnerHtml = new FileHelper().GetUploadfiles((Hashtable) Session["upload"]);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void SetSession(string fileNmae ,string path)
        {
            var hash = (Hashtable)Session["upload"];
            hash[fileNmae] = path;
            Session["upload"] = hash;
        }

     
    }
}
