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;
using EKETEAM.UserControl;
using LitJson;

namespace eFrameWork.Customs.Base
{
    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 bool IsMobile = eBase.IsMobile();
        public eModelInfo pmodel;//父模块对象
        /// <summary>
        /// 本模块相关数据
        /// </summary>
        private DataTable _data;
        public DataTable Data
        {
            get
            {
                if (_data == null)
                {
                    if (Context.Items["LogData"] != null)
                    {
                        DataSet ds = Context.Items["LogData"] as DataSet;
                        _data = new DataTable();
                        if (ds.Tables.Contains("Accessorys"))
                        {
                            _data = ds.Tables["Accessorys"];
                        }
                        return _data;
                    }
                    string sql = "SELECT * FROM Accessorys where DataID='" + parentID + "' and delTag=0";
                    sql += user["siteid"].Length > 0 ? " and SiteID='" + user["siteid"] + "'" : "";
                    sql += pmodel.ApplicationItemID.Length > 0 ? " and ApplicationItemID='" + pmodel.ApplicationItemID + "'" : " and ModelID='" + pmodel.ModelID + "'";
                    sql += " order by addTime";
                    _data = eBase.DataBase.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\":\"" + dr["path"].ToString() + "\"}");
                        i++;
                    }
                    sb.Append("]}");
                    _json = sb.ToString();
                }
                return _json;
            }
        }
        public string aspxfile = "";
        public eUser user;
        public string PictureMaxWidth = "1000";
        protected void Page_Load(object sender, EventArgs e)
        {
           
            user = new eUser(eBase.getUserArea(UserArea));
            aspxfile = Request.CurrentExecutionFilePath;// eBase.getAspxFileName();

            act = eParameters.QueryString("act");
            if (act.Length == 0) act = eParameters.Request("act").ToLower();

            #region 下载文件
            if (act == "down")
            {
                string path = eParameters.QueryString("path");
                string name = eParameters.QueryString("name");
                if (name.Length > 0) name = HttpUtility.UrlDecode(name);
                string filePath = Server.MapPath("~/" + path);
                if (path.ToLower().IndexOf("upload/") == -1)
                {
                    Response.Write("禁止其他目录文件下载!");
                    Response.End();
                }
                string ext = path.fileExtension();
                if (eConfig.PreventExtensions.Contains(ext))
                {
                    Response.Write("文件类型不允许下载!");
                    Response.End();
                }
                if (System.IO.File.Exists(filePath))
                {
                    eFileInfo efi = new eFileInfo(filePath);
                    if (name.Length == 0) name = efi.FullName;
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(name));
                    Response.TransmitFile(filePath);
                    Response.End();
                }
                else
                {
                    Response.Write("附件不存在!");
                    Response.End();
                }
            }
            #endregion


            parentID = eParameters.QueryString("id");
            pmodel = new eModelInfo(user);

            eTable etb;
            switch (act)
            {
                case "save":
                    if (HttpContext.Current.Items["Action"] != null)
                    {
                        if (HttpContext.Current.Items["Action"].ToString() == "getdata") return;
                    }      
                    #region 保存
                    if (pmodel.postJson.Count == 1)
                    {
                        string pid = pmodel.ID;
                        JsonData data = pmodel.postJson[0];
                        if (data.Contains("eformdata_" + modelid))
                        {
                            data = data["eformdata_" + modelid];
                            DateTime Now = DateTime.Now;
                            foreach (JsonData item in data)
                            {
                                JsonData jd = JsonMapper.ToObject("[]");
                                jd.Add(item);

                                eForm eform = new eForm("Accessorys", user);
                                eform.AutoRedirect = false;
                                eform.postJson = jd;
                                //eBase.AppendLog(jd.ToJson());
                                foreach (JsonData row in jd)
                                {
                                    string Delete = row.getValue("Delete").ToLower();
                                    if (Delete == "true")
                                    {
                                        string url = row.getValue("m1_f5");
                                        eFileHelper.remove(url);
                                    }
                                }

                                #region 控件集合
                                eFormControl ef = new eFormControl("m1_f1");
                                ef.Field = "MC";
                                ef.Action = "save";
                                eform.AddControl(ef);

                                ef = new eFormControl("m1_f2");
                                ef.Field = "Ext";
                                ef.Action = "save";
                                eform.AddControl(ef);

                                ef = new eFormControl("m1_f3");
                                ef.Field = "Size";
                                ef.Action = "save";
                                eform.AddControl(ef);

                                ef = new eFormControl("m1_f4");
                                ef.Field = "AddTime";
                                ef.Action = "save";
                                //eform.AddControl(ef);


                              



                                ef = new eFormControl("m1_f5");
                                ef.Field = "Path";
                                ef.ControlType = "file";
                                ef.Action = "save";
                                eform.AddControl(ef);
                                #endregion

                                string ID = item.getValue("ID");
                                if (ID.Length == 0)
                                {
                                    eform.Fields.Add("addTime", Now);
                                    Now = Now.AddSeconds(1);
                                    eform.Fields.Add("DataID", pid);
                                    eform.Fields.Add("ApplicationItemID", pmodel.ApplicationItemID);
                                    eform.Fields.Add("ModelID", pmodel.ModelID);
                                }
                                eform.Save();
                            }
                            //eBase.AppendLog(data.ToJson());
                        }
                    }
                    #endregion
                    break;
                case "del":
                    #region 删除
                    etb = new eTable("Accessorys", user);
                    etb.Where.Add("DataID='" + parentID + "'");
                    etb.Delete();
                    #endregion
                    break;
            }
            DataRow[] rs = eBase.a_eke_sysModelItems.Select("ModelID='" + pmodel.ModelID + "' and ProgrameFile like '%Accessorys.aspx'");
            if (rs.Length > 0)
            {
                if (rs[0]["PictureMaxWidth"].ToString().Length > 1)
                {
                    PictureMaxWidth = rs[0]["PictureMaxWidth"].ToString();
                }
            }
        }
    }
}