using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using EKETEAM.Data;
using EKETEAM.FrameWork;

namespace eFrameWork.Customs
{
    public partial class Accessorys : System.Web.UI.Page
    {
        public string UserArea = "Application";
        private string parentID = "";//主模块添加或编辑数据的主键
        public string modelid = "98108774-e727-4ace-9fb3-96941adc4c2c";//定义一个唯一的模块编号
        public string act = "";//动作
        public eParentModel pmodel;//父模块对象
        /// <summary>
        /// 本模块相关数据
        /// </summary>
        private DataTable _data;
        public DataTable Data
        {
            get
            {
                if (_data == null)
                {
                    string sql = "SELECT * FROM Accessorys where DataID='" + parentID + "' and delTag=0";
                    sql += pmodel.ApplicationItemID.Length > 0 ? " and ApplicationItemID='" + pmodel.ApplicationItemID + "'" : " and ModelID='" + pmodel.ModelID + "'";
                    sql += " order by addTime";
   
                    _data = eOleDB.getDataTable(sql);
                }
                return _data;
            }
        }
        private string _json = null;
        public string getJson
        {
            get
            {
                if (_json == null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("{\"eformdata_" + modelid + "\":[");
                    int i = 0;
                    foreach (DataRow dr in Data.Rows)
                    {
                        if (i > 0) sb.Append(",");
                        sb.Append("{\"ID\":\"" + dr["AccessoryID"].ToString() + "\",\"Delete\":\"false\",\"m1_f1\":\"" + eBase.encode(dr["MC"].ToString()) + "\",\"m1_f2\":\"" + dr["ext"].ToString() + "\",\"m1_f3\":\"" + dr["size"].ToString() + "\",\"m1_f4\":\"" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["addTime"]) + "\",\"m1_f5\":\"" + eBase.getVirtualPath() + dr["path"].ToString() + "\"}");
                        i++;
                    }
                    sb.Append("]}");
                    _json = sb.ToString();
                }
                return _json;
            }
        }
        public string aspxfile = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            //return;
            eUser user = new eUser(eBase.getUserArea(UserArea));
            aspxfile = Request.CurrentExecutionFilePath;// eBase.getAspxFileName();

            parentID = eParameters.QueryString("id");
            pmodel = new eParentModel();
            act = eParameters.QueryString("act");
            if (act.Length == 0) act = eParameters.Request("act").ToLower();
            eTable etb;
            switch (act)
            {
                case "down":

                    string str = eParameters.QueryString("path");
                    string path = Server.MapPath( str);
                    if (System.IO.File.Exists(path))
                    {
                        eFileInfo efi = new eFileInfo(path);
                        Response.ContentType = "application/octet-stream";
                        Response.AddHeader("Content-Disposition", "attachment;filename=" + efi.FullName);
                        Response.TransmitFile(path);
                    }
                    else
                    {
                        Response.Write("附件不存在!");
                        Response.End();
                    }
                    break;
                case "save":
                    #region 保存
                    eJson data = pmodel.getData(modelid);
                    int t = 0;
                    foreach (eJson jrow in data.GetCollection())
                    {
                        string ID = jrow.GetValue("ID");
                        string Delete = jrow.GetValue("Delete");
                        etb = new eTable("Accessorys", user);
                        if (Delete.ToLower() == "true")
                        {
                            etb.Where.Add("AccessoryID='" + ID + "'");
                            string filepath = jrow.GetValue("m1_f5");
                            filepath = Regex.Replace(filepath, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                            filepath = filepath.Replace("../", "").Replace("/", "\\");

                            string _path = Server.MapPath("~/") + filepath;
                            if (_path.ToLower().IndexOf("/filemanage/") == -1 && _path.ToLower().IndexOf("/templates/") == -1)
                            {
                                if (File.Exists(_path)) { try { System.IO.File.Delete(_path); } catch { } }
                            }

                            etb.Delete();
                        }
                        else
                        {
                            etb.Fields.Add("MC", jrow.GetValue("m1_f1"));
                            etb.Fields.Add("Ext", jrow.GetValue("m1_f2"));
                            etb.Fields.Add("Size", jrow.GetValue("m1_f3"));
                            etb.Fields.Add("addTime", jrow.GetValue("m1_f4"));



                            string filepath = jrow.GetValue("m1_f5");
                            filepath = eBase.ConvertFilePath(filepath); //如果是临时文件，保存到正式目录下并返回新路径

                            etb.Fields.Add("Path", filepath);

                            if (ID.Length == 0) //添加
                            {
                                etb.Fields.Add("DataID", parentID);

                                if (pmodel.ApplicationItemID.Length > 0)
                                {
                                    etb.Fields.Add("ApplicationItemID", pmodel.ApplicationItemID);
                                }
                                else
                                {
                                    etb.Fields.Add("ModelID", pmodel.ModelID);
                                }
                                etb.Fields.Add("addTime", DateTime.Now.ToString() + "." + t.ToString().PadLeft(3, '0'));
                                if (eBase.Right(t.ToString(), 1) == "3") t += 1;
                                t += 3; 
                                etb.Add();
                            }
                            else //修改
                            {
                                etb.Where.Add("AccessoryID='" + ID + "'");
                                etb.Update();
                            }
                        }
                    }
                    #endregion
                    break;
                case "del":
                    #region 删除
                    etb = new eTable("Accessorys", user);
                    etb.Where.Add("DataID='" + parentID + "'");
                    etb.Delete();
                    #endregion
                    break;
            }
        }
    }
}