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 AccessoryContainer : System.Web.UI.Page
    {
        public string UserArea = "Application";
        private string parentID = "";//主模块添加或编辑数据的主键
        public string modelid = "28108774-e727-4ace-9fb3-96941adc4c2a";//定义一个唯一的模块编号
        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;
                    }
                    if (parentID.Length == 0) return new DataTable();
                    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 += " and ModelID='" + pmodel.ModelID + "'";
                    sql += " order by addTime";
                    //Response.Write(sql);
                    _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\":\"" + (act=="copy" || act=="change" ? "" : 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 allExt = ".jpg.jpeg.gif.bmp.png.tif.xls.xlsx.doc.docx.mp3.mp4.pdf.ppt.pptx.";
        public string PictureMaxWidth = "1500";
        protected void Page_Load(object sender, EventArgs e)
        {

            if (HttpContext.Current.Items.Contains("ID")) parentID = HttpContext.Current.Items["ID"].ToString();
            if (parentID.Length == 0) parentID = eParameters.QueryString("id");
           
            #region 与主模块数据交互
            if (HttpContext.Current.Items.Contains("Action"))
            {

                act = HttpContext.Current.Items["Action"].ToString().ToLower();
                #region 审批回调
                if (act == "checkup")
                {
                    string id = HttpContext.Current.Items["ID"].ToString();//数据ID
                    //eBase.AppendLog("checkup::" + id);
                    return;
                }
                #endregion
                #region 相关数据
                if (act == "getdata")
                {
                    string id = HttpContext.Current.Items["ID"].ToString();//数据ID
                    DataTable dt = eBase.DataBase.getDataTable("SELECT * FROM Accessorys where DataID='" + id + "' and delTag=0");
                    HttpContext.Current.Items["Data_Result"] = dt;
                    return;
                }
                #endregion
                #region 变更时复制原始数据
                if (act == "copyoriginal")
                {
                    string originalid = HttpContext.Current.Items["OriginalID"].ToString();//原始ID
                    string id = HttpContext.Current.Items["ID"].ToString();//新ID
                    DataTable dt = eBase.DataBase.getDataTable("SELECT * FROM Accessorys where DataID='" + originalid + "' and delTag=0");
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["AccessoryID"] = Guid.NewGuid();
                        dr["DataID"] = id;
                    }
                    dt.Append(eBase.DataBase);
                    return;
                }
                #endregion
                #region 数据变更
                if (act == "change")
                {
                    string originalid = HttpContext.Current.Items["OriginalID"].ToString();//原始ID
                    string id = HttpContext.Current.Items["ID"].ToString();//新ID
                    //eBase.AppendLog(act + "::" + originalid + "::" + id);
                    DataTable dt = eBase.DataBase.getDataTable("SELECT * FROM Accessorys where DataID='" + originalid + "' and delTag=0");
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["AccessoryID"] = Guid.NewGuid();
                        dr["DataID"] = id;
                    }
                    dt.Append(eBase.DataBase);
                    return;
                }
                #endregion
                #region API查看
                if (act == "apiview")
                {
                    parentID = HttpContext.Current.Items["ID"].ToString();
                    HttpContext.Current.Items["Data_Result"] = getJson;
                    return;
                }
                #endregion
                #region API编辑
                if (act == "apiedit")
                {
                    parentID = HttpContext.Current.Items["ID"].ToString();
                    HttpContext.Current.Items["Data_Result"] = getJson;
                    return;
                }
                #endregion
                #region API修改有问题
                if (act == "update2")
                {

                    if (HttpContext.Current.Items.Contains("postJson"))
                    {
                        JsonData data = HttpContext.Current.Items["postJson"] as JsonData;
                        data = data[0];
                        if (data.Contains("eformdata_" + modelid))
                        {
                            data = data["eformdata_" + modelid];
                            Save(data, parentID);
                            //eBase.AppendLog(data.ToJson());
                        }
                    }                  
                    return;
                }
                #endregion
                #region API修改
                if (act == "del")
                {
                    parentID = HttpContext.Current.Items["ID"].ToString();
                    eTable etb = new eTable("Accessorys");
                    etb.Where.Add("DataID='" + parentID + "'");
                    etb.Delete();
                    return;
                }
                #endregion
                //return;
            }
            #endregion

            user = new eUser(eBase.getUserArea(UserArea));
            aspxfile = Request.CurrentExecutionFilePath;// eBase.getAspxFileName();

            act = "";
            act = eParameters.QueryString("act");
            if (act.Length == 0) act = eParameters.Request("act").ToLower();
            #region 下载文件
            if (act == "down")
            {
                #region 下载文件参数及安全性检测
                string fileName = eParameters.QueryString("name");
                fileName = HttpUtility.UrlDecode(fileName);
                string path = eParameters.QueryString("path");
                path = path.Replace("../", "");
                if (path.Length < 10)
                {
                    Response.Write("文件不存在!");
                    Response.End();
                }
                string filePath = Server.MapPath("~/" + path);
                if (path.ToLower().IndexOf("upload/") == -1)
                {
                    Response.Write("禁止其他目录文件下载!");
                    Response.End();
                }
                string fileExt = Path.GetExtension(filePath).ToLower();
                if (eConfig.PreventExtensions.Contains(fileExt))
                {
                    Response.Write("文件类型不允许下载!");
                    Response.End();
                }
                #endregion

                if (System.IO.File.Exists(filePath))
                {
                    eFileInfo efi = new eFileInfo(filePath);
                    if (fileName.Length == 0) fileName = efi.FullName;
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(fileName));
                    Response.TransmitFile(filePath);
                    Response.End();
                }
                else
                {
                    Response.Write("附件不存在!");
                    Response.End();
                }
            }
            #endregion
            pmodel = new eModelInfo(user);

            switch (act)
            {
                case "copy":
                case "change":
                case "insert":
                case "update":
                case "save":
                    #region 保存
                    if (pmodel.postJson.Count == 1)
                    {
                        string pid = pmodel.ID;
                        JsonData data = pmodel.postJson[0];
                        if (data.Contains("eformdata_" + modelid))
                        {
                            data = data["eformdata_" + modelid];
                            Save(data, pid);
                        }
                    }
                    #endregion
                    break;
                case "del":
                    #region 删除
                    eTable 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 '%AccessoryContainer.aspx'");
            if (rs.Length > 0)
            {
                if (rs[0]["PictureMaxWidth"].ToString().Length > 1)
                {
                    PictureMaxWidth = rs[0]["PictureMaxWidth"].ToString();
                }
            }
        }
        private void Save(JsonData data,string pid)
        {
            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;

                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);
                }
                //eBase.AppendLog(eform.addSQL);
                eform.Save();
            }

        }
    }
}