using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Linq;
namespace FineUIPro.Web.AttachFile
{
    /// 
    /// fileupload 的摘要说明
    /// 
    public class fileupload : PageBase, IHttpHandler, IRequiresSessionState
    {
        private void ResponseError(HttpContext context)
        {
            // 出错了
            context.Response.StatusCode = 500;
            context.Response.Write("No file");
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string owner = context.Request.Form["owner"];
            string sessionName = owner.Split('|')[0];
            string attachPath = owner.Split('|')[1] + "/" + DateTime.Now.ToString("yyyy-MM");
            string initFullPath = BLL.Funs.RootPath + attachPath;
            if (!Directory.Exists(initFullPath))
            {
                Directory.CreateDirectory(initFullPath);
            }
            if (context.Request.Files.Count == 0)
            {
                ResponseError(context);
                return;
            }
            if (String.IsNullOrEmpty(owner))
            {
                ResponseError(context);
                return;
            }
            // 定义允许上传的文件类型列表
            List allowExtensions = BLL.DropListService.allowExtensions;
            HttpPostedFile postedFile = context.Request.Files[0];
            // 文件名完整路径
            string fileName = postedFile.FileName;
            // 文件名保存的服务器路径
            string savedFileName = GetSavedFileName(fileName);
            postedFile.SaveAs(context.Server.MapPath("~/" + attachPath + "/" + savedFileName));
            if (owner.Contains("DriverRunPlanK"))
            {
                ImportXlsToData(context.Server.MapPath("~/" + attachPath + "/" + savedFileName));
            }
            string shortFileName = GetFileName(fileName);
            string fileType = GetFileType(fileName);
            if (!allowExtensions.Contains("." + fileType))
            {
                // 出错了
                context.Response.StatusCode = 415;
                context.Response.Write("不支持的文件类型");
                // ResponseError(context);
                return;
            }
            int fileSize = postedFile.ContentLength;
            JObject fileObj = new JObject();
            string fileId = Guid.NewGuid().ToString();
            fileObj.Add("name", shortFileName);
            fileObj.Add("type", fileType);
            fileObj.Add("savedName", savedFileName);
            fileObj.Add("size", fileSize);
            fileObj.Add("id", fileId);
            string attachUrl = (attachPath + "/" + savedFileName).Replace('/', '\\');
            int strInt = attachUrl.LastIndexOf("~");
            if (strInt < 0)
            {
                strInt = attachUrl.LastIndexOf("\\");
            }
            string folder = attachUrl.Substring(0, strInt + 1).Replace('\\', '/');
            fileObj.Add("folder", folder);
            SaveToDatabase(context, sessionName, fileObj);
            context.Response.Write("Success");
        }
        private void SaveToDatabase(HttpContext context, string sessionName, JObject fileObj)
        {
            if (context.Session[sessionName] == null)
            {
                context.Session[sessionName] = new JArray();
            }
            JArray source = context.Session[sessionName] as JArray;
            source.Add(fileObj);
            context.Session[sessionName] = source;
        }
        private string GetFileType(string fileName)
        {
            string fileType = String.Empty;
            int lastDotIndex = fileName.LastIndexOf(".");
            if (lastDotIndex >= 0)
            {
                fileType = fileName.Substring(lastDotIndex + 1).ToLower();
            }
            return fileType;
        }
        private string GetFileName(string fileName)
        {
            string shortFileName = fileName;
            int lastSlashIndex = shortFileName.LastIndexOf("\\");
            if (lastSlashIndex >= 0)
            {
                shortFileName = shortFileName.Substring(lastSlashIndex + 1);
            }
            return shortFileName;
        }
        private string GetSavedFileName(string fileName)
        {
            fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
            fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;
            return fileName;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #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);
                        }
                    }
                    if (driverRunPlan.UsedDays == null)
                    {
                        driverRunPlan.UsedDays = usedDays;
                    }
                    else
                    {
                        driverRunPlan.UsedDays += usedDays;
                    }
                    Funs.DB.SubmitChanges();
                }
            }
            else
            {
            }
            return true;
        }
        #endregion
    }
}