namespace Kesion.NET.WebSite
{
    using System;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Collections;
    using Kesion.Components;
    using Kesion.Config;
    using System.Collections.Generic;
    using System.Net;
    using System.Xml;

    using Kesion.Publics;
    using Kesion.BLL;
    using Kesion.Cache;
    using Kesion.APPCode;
    using System.Text;
    public partial class Admin_TemplateSkin : KSCMS
    {
        public static int PageSize = 20;
        public int CurrPage = 1;
        public string _Action;
        public int TemplateType = 0;
        public string typeName = string.Empty;
        public string TemplateDir = string.Empty;  //总模板目录
        public static string targetFolder = MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/tmp/";  //解压目标目录　
        public string uploadFolder = MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/";  //导入及云端下载时，上传的临时目录
        public static string zipFile = string.Empty;

        XmlDocument xmlDoc = new XmlDocument();
        public static int totalByte = 0;  //压缩包总大小
        public static int currByte = 0; //压缩包当前已下载大小

        public Dictionary<string, string> classDic = new Dictionary<string, string>();
        public static string Token = string.Empty;
        public static string Appid = string.Empty;
        public bool IsYunAccount = false;
        public int tpType = 0;                   //云端模板类型 0、PC模板 1、手机 2、班级 3、机构主页
        protected void Page_Load(object sender, EventArgs e)
        {

            KSSecurity.CheckPermissions();
            zipFile = Server.MapPath(uploadFolder) + "tmp.zip";
            _Action = KSCMS.S("action");
            TemplateType = Utils.StrToInt(KSCMS.S("showType"));
            if (TemplateType == -1 && _Action != "UploadStep2")
            {
                GetToken();
                tpType = Utils.StrToInt(KSCMS.S("tpType"));
                #region 云端风格管理
                if (KSCMS.S("action").Equals("yundown"))
                {
                    YunDownPanel.Visible = true;
                    mainlist.Visible = false;
                    return;

                }
                else if (KSCMS.S("action").Equals("downbeginimport")) //下载完成，开始导入
                {
                    downBeginImport();
                }
                else
                {
                    this.Page1.OnPageChange += new PageHandler(PageNavigator1_PageChange_Yun);
                    if (!IsPostBack)
                    {
                        initialYunTemplate(1);
                    }
                }
                #endregion
            }
            else
            {
                #region  本地风格管理

                TemplateDir = GetTemplateAllDir(TemplateType, ref typeName);  //模板总目录

                if (string.IsNullOrEmpty(TemplateDir)) TemplateDir = "tp";

                if (!System.IO.Directory.Exists(Server.MapPath(MyCache.GetCacheConfig(0) + TemplateDir)))
                {
                    JS.Alert("模板总目录[" + TemplateDir + "]不存在！");
                }
                this.Page1.OnPageChange += new PageHandler(PageNavigator1_PageChange);

                if (!IsPostBack)
                {
                    switch (_Action)
                    {
                        case "setdefault":
                            Utils.TipsDisabled();  //检查是否演示状态
                            SetDefault(Utils.StrToInt(KSCMS.S("TemplateId")), TemplateType);
                            JS.Alert("恭喜，设置默认风格成功！", KSCMS.GetComeUrl());
                            break;
                        case "add":
                            initialAdd();
                            break;
                        case "del":
                            Utils.TipsDisabled();  //检查是否演示状态
                            doDelete();
                            break;
                        case "export":
                            doExport();
                            break;
                        case "upload":
                            doUpload();
                            break;
                        case "UploadStep2":
                            uploadStep2();
                            break;
                        case "checkEname":
                            checkEname();
                            break;
                        case "clone":
                            Utils.TipsDisabled();  //检查是否演示状态
                            initialClone();
                            break;
                        default:
                            initialList(1);
                            break;
                    }
                }
                #endregion

            }
        }

        #region 云模板操作 
        private XmlDocument initialYunTemplateXML(int page = 1, int beginDown = 0, int templateId = 0)
        {
            #region 初始化云模板XML
            XmlDocument xmlDOC = new XmlDocument();
            if (Internet.CheckIsConneted(Kesion.BLL.Yun.GetYaSite))  //可连接官网VIP
            {
                Response.Write("<script>processTips('云端服务器已连接，正在初始化，请稍候...');</script>");
                Response.Flush();

                string YunXmlUrl = "http://" + Kesion.BLL.Yun.GetYaSite + "/api/market/LoadTemplate?showver=" + Utils.GetSysInfo("//sysinfo/showver").ToLower() + "&tpType=" + tpType + "&page = " + page;

                // KSCMS.Die(YunXmlUrl);

                if (beginDown == 1)
                {
                    YunXmlUrl += "&token=" + Kesion.BLL.Yun.GetToken() + "&beginDown=" + beginDown + "&templateId=" + templateId + "&isbusiness=" + Utils.GetSysInfo("//sysinfo/isbusiness").ToLower() + "&domain=" + Request.ServerVariables["SERVER_NAME"].Trim() + "&sitesn=" + MyCache.GetCacheConfig(57).ToString();
                }


                //使用rssURL的值建立了一个WebRequest项              
                WebRequest myRequest = WebRequest.Create(YunXmlUrl);
                //WebRequest请求的响应将会被放到一个WebResponse对象myResponse里,然后这个WebResponse对象被用来建立一个流来取出XML的值                       
                WebResponse myResponse = myRequest.GetResponse();
                Stream stream = myResponse.GetResponseStream();
                //使用一个XmlDocument对象rssDoc来存储流中的XML内容。XmlDocument对象用来调入XML的内容    
                xmlDOC.Load(stream);

                Response.Write("<script>processTips('初始化完毕，正在转入下载，请稍候...');</script>");
                Response.Flush();

            }
            else
            {
                KSCMS.Die("温馨提示：暂无法连接到官方云端，请稍候重试！");
            }
            return xmlDOC;
            #endregion
        }
        private void initialYunTemplate(int PageIndex)
        {
            #region 初始化云端风格管理
            this.TpList.Visible = false;
            this.YunTemplateList.Visible = true;
            if (Internet.CheckIsConneted(Kesion.BLL.Yun.GetYaSite))  //可连接官网
            {
                xmlDoc = initialYunTemplateXML(PageIndex);
                if (xmlDoc != null)
                {
                    XmlNode xmlNode = xmlDoc.SelectSingleNode("root");
                    XmlElement xe = (XmlElement)xmlNode.SelectSingleNode("templateinfo");
                    int pageCount = Utils.StrToInt(xe.Attributes["pagecount"].InnerText);
                    int recordCount = Utils.StrToInt(xe.Attributes["recordcount"].InnerText);
                    int PageSize = 20;
                    CurrPage = PageIndex;

                    string templateXML = xmlDoc.InnerXml;
                    string templateInfo = Utils.CutHttpString(templateXML, "<templateinfo", "</templateinfo>", true);
                    templateXML = Utils.ReplaceString(templateXML, templateInfo, string.Empty, true);

                    DataSet ds = Kesion.XML.XmlObject.StringToDataSet(templateXML);
                    if (ds.Tables.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];

                        this.YunTemplateList.DataSource = dt;
                        this.YunTemplateList.DataBind();

                        this.Page1.PageCount = pageCount;
                        this.Page1.PageIndex = PageIndex;
                        this.Page1.RecordCount = recordCount;
                        this.Page1.PerPageNum = PageSize;
                        this.Page1.DataBind();  //新增
                    }
                    else
                    {
                        showEmpty.Visible = true;
                    }

                }

            }
            else
            {
                KSCMS.Die("温馨提示：暂无法连接到官方云端，请稍候重试！");
            }
            #endregion
        }
        public void initialYunDown()
        {


            Response.Write("<script>processTips('正在尝试连接云端服务器，请稍候...');</script>");
            Response.Flush();

            CurrPage = Utils.StrToInt(KSCMS.S("page"), 1);

            int templateId = Utils.StrToInt(KSCMS.S("TemplateID"));

            xmlDoc = initialYunTemplateXML(CurrPage, 1, templateId); //初始化开始下载

            if (xmlDoc != null)
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode("root");
                XmlElement xe = (XmlElement)xmlNode.SelectSingleNode("item");
                string allowdown = xe.SelectSingleNode("allowdown").InnerText.Trim();
                if (allowdown != "true")
                {
                    JS.AlertDoFun("对不起，商业模板，您没有权限下载；如果您是我们的是授权VIP用户，请安装到授权域名下即可获得下载权限！", "top.box.close()");
                }
                else
                {
                    if (xe.SelectSingleNode("isdrag") != null)
                    {
                        int isDrag = Utils.StrToInt(xe.SelectSingleNode("isdrag").InnerText);
                        if (isDrag == 1 && SiteKey.VerifyModulePower("drag") == false)
                        {
                            JS.AlertDoFun("对不起，你当前授权的版本不支持拖拽模板风格！", "top.box.close()");
                            return;
                        }
                    }

                    string domain = xe.SelectSingleNode("domain").InnerText.Trim();
                    string sitesn = xe.SelectSingleNode("sitesn").InnerText.Trim();
                    string downUrl = xe.SelectSingleNode("downurl").InnerText.Trim();


                    xe = (XmlElement)xmlNode.SelectSingleNode("item[@templateid=" + templateId + "]");
                    if (xe != null)
                    {
                        zipFile = Server.MapPath(uploadFolder) + "tmp.zip";

                        downUrl = xe.SelectSingleNode("downurl").InnerText.Trim();
                        if (!downUrl.ToLower().StartsWith("http://")) downUrl = "http://" + Kesion.BLL.Yun.GetYaSite + downUrl;

                        Kesion.Publics.UtilsFile.CreateFolders(uploadFolder);

                        DownLoadFile(downUrl, zipFile);
                        Response.Flush();


                    }
                    else
                    {
                        KSCMS.Die("error");
                    }

                }
            }
            else
            {
                JS.AlertDoFun("对不起，云端未连接，请稍候再试！", "top.box.close()");
            }
        }


        public string GetYunTemplatePic(string defaultPic)
        {
            defaultPic = defaultPic.Trim();
            if (!defaultPic.ToLower().StartsWith("http://"))
            {
                defaultPic = "http://" + Kesion.BLL.Yun.GetYaSite + defaultPic;
            }
            return defaultPic;
        }

        private void downBeginImport()
        {
            DoZipImport();
        }


        private static long GetLength(string uri)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            long len = res.ContentLength;
            res.Close();
            return len;
        }

        private void DownLoadFile(string address, string filename)
        {
            //address 文件下载路径,filename文件存放的本地路径

            WebClient client = new WebClient();
            //client.DownloadFile(address, filename);
            Stream str = client.OpenRead(address);
            StreamReader reader = new StreamReader(str);
            byte[] mbyte = new byte[GetLength(address) + 1];
            int allmybyte = (int)mbyte.Length;
            totalByte = allmybyte;
            Response.Write("<script> Start();</script>");
            Response.Flush();
            Response.Write("<script>SetProcess('" + totalByte + "|" + currByte + "');</script>");
            Response.Flush();
            int startmbyte = 0;
            while (allmybyte > 0)
            {
                int m = str.Read(mbyte, startmbyte, allmybyte);
                if (m == 0)
                {
                    break;
                }
                startmbyte += m;
                currByte = startmbyte;  //当前已下载大小
                allmybyte -= m;
                Response.Write("<script>SetProcess('" + totalByte + "|" + currByte + "');</script>");
                Response.Flush();
            }
            FileStream fstr = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
            fstr.Write(mbyte, 0, startmbyte);
            str.Close();
            fstr.Close();
            KSCMS.Die("<script> End();</script>");

        }



        /// <summary>
        /// PageNavigator1_PageChange_Yun 的摘要说明
        /// 分页加载函数
        /// </summary>
        protected void PageNavigator1_PageChange_Yun(object sender, int PageIndex)
        {
            initialYunTemplate(PageIndex);
        }
        #endregion



        #region   ===========通用类===========================

        /// <summary>
        /// 设置默认风格
        /// </summary>
        /// <param name="templateId"></param>
        /// <param name="TemplateType"></param>
        public void SetDefault(int templateId, int TemplateType)
        {
            #region 设置默认
            string templateEname = string.Empty;
            if (templateId > 0)
            {
                using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_Template Where TemplateId=" + templateId))
                {
                    if (dt.Rows.Count > 0)
                    {
                        templateEname = dt.Rows[0]["TemplateEname"].ToString();
                    }
                }
            }


            if (!string.IsNullOrEmpty(templateEname))
            {
                DataFactory.ExecuteNonQuery("Update KS_Template Set IsDefault=0 Where TemplateType=" + TemplateType + "");
                DataFactory.ExecuteNonQuery("Update KS_Template Set IsDefault=1 Where TemplateType=" + TemplateType + " and TemplateId=" + templateId);


                ConfigInfo __configinfo = ConfigManage.Deserialize(Server.MapPath("/config/general.config"));
                string settings = __configinfo.ShopTemplates;
                if (settings.Split('#').Length < 100)
                {
                    settings += "##################################################################";
                }
                string[] tpSetting = settings.Split('#');
                string newTp = string.Empty;
                int ii = 0;
                foreach (string s in tpSetting)
                {
                    if (ii == 0)
                    {
                        newTp = s;
                    }
                    else if (ii == 87 && TemplateType == 0)
                    {
                        newTp += "#" + templateId.ToString(); //87 PC当前模板风格ID
                    }
                    else if (ii == 88 && TemplateType == 1)
                    {
                        newTp += "#" + templateId.ToString(); //88 手机当前模板风格ID
                    }
                    else if (ii == 92 && TemplateType == 2)
                    {
                        newTp += "#" + templateId.ToString(); //92 机构默认模板风格ID
                    }
                    else if (ii == 93 && TemplateType == 3)
                    {
                        newTp += "#" + templateId.ToString(); //93 个人空间模板风格ID
                    }
                    else if (ii == 120 && TemplateType == 4)
                    {
                        newTp += "#" + templateId.ToString(); //120 微店模板风格ID
                    }
                    else if (ii == 122 && TemplateType == 5)
                    {
                        newTp += "#" + templateId.ToString(); //122 班级模板风格ID
                    }
                    else
                    {
                        newTp += "#" + s;
                    }
                    ii++;
                }
                __configinfo.ShopTemplates = newTp;

                //KSCMS.Die(newTp);

                ConfigManage.Serialiaze(__configinfo, Server.MapPath("/config/general.config"));
                #region 更新缓存
                KSCache cache = KSCache.GetCacheService();
                cache.RemoveObject("/CMS/ConfigList");
                CleanTemplateCache();
                #endregion

            }



            #endregion
        }

        /// <summary>
        /// 导入模板库操作
        /// </summary>
        /// <param name="path1">源目录</param>
        /// <param name="path2">目标目录</param>
        /// <param name="oriTemplateID">原模型ID号</param>
        /// <param name="templateName">模板名称，可留空</param>
        /// <returns></returns>
        public bool ZipTemplateToDB(string path1, string path2, int oriTemplateID, string templateName = "")
        {
            #region 导入模板库操作
            string templateEname = UtilsFile.GetLastFolderName(path2);  //得到目录名称

            if (DataFactory.Exists("KS_Template", "TemplateEname='" + templateEname + "'"))
            {
                path2 = Utils.ReplaceArrayStrToNewElement(path2, "/", templateEname + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second);
                templateEname = UtilsFile.GetLastFolderName(path2);  //得到目录名称
            }
            if (!Directory.Exists(Server.MapPath(path2)))
            {
                //  Kesion.Publics.UtilsFile.CreateFolders(path2);     //创建模板目录
            }

            UtilsFile.MoveFolder(path1, path2);     //移动物理路径


            string SkinInfoXML = path2 + "info.xml";
            string labelClassXML = path2 + "labelclass.xml";
            string labelXML = path2 + "label.xml";
            string labelJSXML = path2 + "labeljs.xml";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(SkinInfoXML));
            if (xmlDoc != null)
            {

                #region 写入模板风格表
                XmlNode xmlNode = xmlDoc.SelectSingleNode("Template");
                string templateAuthor = ((XmlElement)xmlNode.SelectSingleNode("Author")).InnerText;
                string templateIntro = ((XmlElement)xmlNode.SelectSingleNode("Intro")).InnerText;
                int isViewEdit = 0;
                if (xmlNode.SelectSingleNode("IsViewEdit") != null)
                {
                    isViewEdit = Utils.StrToInt(((XmlElement)xmlNode.SelectSingleNode("IsViewEdit")).InnerText);
                }

                int templateType = Utils.StrToInt(((XmlElement)xmlNode.SelectSingleNode("TemplateType")).InnerText);

                int agentType = 0;
                if (xmlNode.SelectSingleNode("AgentType") != null)
                {
                    agentType = Utils.StrToInt(((XmlElement)xmlNode.SelectSingleNode("AgentType")).InnerText);
                }

                string defaultPic = path2 + "view.jpg";
                if (!File.Exists(Server.MapPath(defaultPic)))
                {
                    defaultPic = ((XmlElement)xmlNode.SelectSingleNode("DefaultPic")).InnerText;
                }

                if (string.IsNullOrEmpty(templateName))
                {
                    if (xmlNode.SelectSingleNode("TemplateName") != null)
                    {
                        templateName = ((XmlElement)xmlNode.SelectSingleNode("TemplateName")).InnerText;
                    }
                    else
                    {
                        templateName = "默认模板";
                    }
                }
                if (string.IsNullOrEmpty(templateEname))
                {
                    if (xmlNode.SelectSingleNode("TemplateEName") != null)
                    {
                        templateEname = ((XmlElement)xmlNode.SelectSingleNode("TemplateEName")).InnerText;
                    }
                }


                Hashtable ht = new Hashtable();
                ht.Add("TemplateName", templateName);
                ht.Add("TemplateEName", templateEname);
                ht.Add("templateType", templateType);
                ht.Add("Author", templateAuthor);
                ht.Add("Intro", templateIntro);
                ht.Add("AddDate", DateTime.Now);
                ht.Add("DefaultPic", defaultPic);
                ht.Add("IsDefault", 0);
                ht.Add("IsViewEdit", isViewEdit);
                ht.Add("AgentType", agentType);
                ht.Add("OriTemplateID", oriTemplateID);

                CommonData.Insert("KS_Template", ht);

                int templateId = CommonData.GetMaxId("KS_Template", "templateId");
                #endregion

                #region  导入标签分类
                xmlDoc.Load(Server.MapPath(labelClassXML));
                if (xmlDoc != null)
                {
                    //获取根节点
                    XmlNode root = xmlDoc.DocumentElement;
                    ImportLabelClass(0, 0, templateId, root);

                }
                #endregion

                #region 导入标签
                xmlDoc.Load(Server.MapPath(labelXML));
                if (xmlDoc != null)
                {
                    XmlNode root = xmlDoc.DocumentElement;
                    XmlNodeList items = root.ChildNodes;
                    foreach (XmlNode item in items)
                    {
                        ht = new Hashtable();
                        ht.Add("labelid", CommonData.GetMaxIdAddOne("KS_Label", "labelid"));
                        ht.Add("labelname", item.Attributes["labelname"].InnerText);
                        ht.Add("labelcontent", item.SelectSingleNode("labelcontent").InnerText);
                        ht.Add("description", item.SelectSingleNode("description").InnerText);
                        int oldClassid = Utils.StrToInt(item.Attributes["classid"].InnerText);
                        if (classDic.ContainsKey("classid" + oldClassid))
                        {
                            ht.Add("classid", Utils.StrToInt(classDic["classid" + oldClassid].ToString()));
                        }
                        else
                        {
                            ht.Add("classid", 0);
                        }
                        ht.Add("orderid", item.Attributes["orderid"].InnerText);
                        ht.Add("labeltype", item.Attributes["labeltype"].InnerText);
                        ht.Add("labelflag", item.Attributes["labelflag"].InnerText);
                        ht.Add("adddate", item.Attributes["adddate"].InnerText);
                        ht.Add("from3g", 0);
                        ht.Add("templateid", templateId);
                        CommonData.Insert("KS_Label", ht);

                    }
                }
                #endregion

                #region 导入JS标签
                xmlDoc.Load(Server.MapPath(labelJSXML));
                if (xmlDoc != null)
                {

                    XmlNode root = xmlDoc.DocumentElement;
                    XmlNodeList items = root.ChildNodes;
                    foreach (XmlNode item in items)
                    {
                        ht = new Hashtable();
                        ht.Add("jsname", item.Attributes["jsname"].InnerText);
                        ht.Add("jsfilename", item.Attributes["jsfilename"].InnerText);
                        ht.Add("jsconfig", item.SelectSingleNode("jsconfig").InnerText);
                        ht.Add("description", item.SelectSingleNode("description").InnerText);
                        ht.Add("jstype", item.Attributes["jstype"].InnerText);
                        ht.Add("adddate", item.Attributes["adddate"].InnerText);
                        ht.Add("orderid", item.Attributes["orderid"].InnerText);
                        int oldClassid = Utils.StrToInt(item.Attributes["classid"].InnerText);
                        if (classDic.ContainsKey("classid" + oldClassid))
                        {
                            ht.Add("classid", Utils.StrToInt(classDic["classid" + oldClassid].ToString()));
                        }
                        else
                        {
                            ht.Add("classid", 0);
                        }
                        ht.Add("from3g", 0);
                        ht.Add("templateid", templateId);
                        CommonData.Insert("KS_JSFile", ht);
                    }
                }
                #endregion


                #region  导入成功删除标签XML文件等
                Kesion.Publics.UtilsFile.DelFile(SkinInfoXML);
                Kesion.Publics.UtilsFile.DelFile(labelClassXML);
                Kesion.Publics.UtilsFile.DelFile(labelXML);
                Kesion.Publics.UtilsFile.DelFile(labelJSXML);
                #endregion

                CleanTemplateCache();
            }
            else
            {
                return false;
            }
            return true;
            #endregion
        }
        #endregion




        public string GetTemplateAllDir(int TemplateType, ref string typeName)
        {
            #region 模板总目录
            string TemplateDir = MyCache.GetCacheConfig(84);
            switch (TemplateType)
            {
                case 1:
                    typeName = "手机";
                    TemplateDir = MyCache.GetCacheConfig(85); //手机模板的总目录
                    break;
                case 2:
                    typeName = "机构";
                    TemplateDir = MyCache.GetCacheConfig(86); //机构模板的总目录
                    break;
                case 3:
                    typeName = "个人空间";
                    TemplateDir = MyCache.GetCacheConfig(87); //个人空间的总目录
                    break;
                case 4:
                    typeName = "微店";
                    TemplateDir = MyCache.GetCacheConfig(89); //微店的总目录
                    break;
                case 5:
                    typeName = "微店";
                    TemplateDir = MyCache.GetCacheConfig(93); //班级的总目录
                    break;
                default:
                    typeName = "PC";
                    TemplateDir = MyCache.GetCacheConfig(84);  //PC模板的总目录
                    break;
            }
            return TemplateDir;
            #endregion
        }


        private void initialList(int PageIndex)
        {
            #region 本地风格列表
            int recordcount, pagecount;
            if (PageIndex <= 0) PageIndex = 1;
            string param = " where templateType=" + TemplateType;
            if (Utils.StrToInt(KSCMS.S("agentType")) > 0)
            {
                param += " and AgentType = " + KSCMS.S("agentType");
            }

            using (DataTable dt = DataFactory.GetPage("*", "KS_Template" + param, "templateid", "order by isdefault Desc,templateid desc", PageIndex, PageSize, out recordcount, out pagecount))
            {

                this.Page1.PageCount = pagecount;
                this.Page1.PageIndex = PageIndex;
                this.Page1.RecordCount = recordcount;
                this.Page1.PerPageNum = PageSize;

                this.TpList.DataSource = dt;
                this.TpList.DataBind();
            }
            #endregion
        }


        /// <summary>
        /// PageNavigator1_PageChange 的摘要说明
        /// 分页加载函数
        /// </summary>
        protected void PageNavigator1_PageChange(object sender, int PageIndex)
        {
            initialList(PageIndex);
        }


        private void initialAdd()
        {
            #region 初始化添加
            this.mainlist.Visible = false;
            this.addlist.Visible = true;
            GetTemplateDir();

            Utils.SetButtonDisabled(this.Button1);


            string groupLevel = string.Empty;
            int templateId = Utils.StrToInt(KSCMS.S("templateId"));
            if (templateId > 0)
            {
                using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_Template Where TemplateId=" + templateId))
                {
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        this.TxtTemplateName.Text = dr["templateName"].ToString();
                        this.dropTemplateDir.SelectedValue = dr["templateEname"].ToString().ToLower();
                        this.TxtDefaultPic.Text = dr["DefaultPic"].ToString();
                        this.TxtAuthor.Text = dr["author"].ToString();
                        this.TxtIntro.Text = dr["intro"].ToString();
                        this.HidTemplateId.Value = templateId.ToString();
                        this.HidTemplateType.Value = dr["templateType"].ToString();
                        this.RdbIsViewEdit.SelectedValue = Utils.StrToInt(dr["isviewedit"].ToString()).ToString();
                        groupLevel = dr["groupLevel"].ToString();
                        if (TemplateType == 4)
                            this.AgentType.SelectedValue = dr["AgentType"].ToString();
                        this.Button1.Text = "确定修改(A)";
                    }
                }
            }
            else
            {
                this.HidTemplateType.Value = TemplateType.ToString();
            }

            #region 个人空间模板
            if (TemplateType == 3)
            {
                this.chkUserlevel.InnerHtml = BaseFun.GetUserGroup_CheckBox("DefaultArrGroupID", 3, groupLevel);
            }
            #endregion

            #region 机构模板
            if (TemplateType == 2)
            {
                if (BaseFun.CheckTableExists("KS_JobPower"))
                {
                    using (DataTable dt = DataFactory.GetDataTable("select id,Title from KS_JobPower Where [type]=1"))
                    {
                        if (dt.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                ListItem li1 = new ListItem();
                                li1.Value = dr["id"].ToString();
                                li1.Text = dr["Title"].ToString();
                                if (Utils.InArray(dr["id"].ToString(), groupLevel, ","))
                                {
                                    li1.Selected = true;
                                }
                                else
                                {
                                    li1.Selected = false;
                                }
                                this.CheckBoxList1.Items.Add(li1);
                            }
                        }
                    }
                }
            }
            #endregion

            #endregion
        }


        private void GetTemplateDir()
        {
            string _path = "~/" + TemplateDir + "/";
            DirectoryInfo d = new DirectoryInfo(Server.MapPath(_path));
            foreach (DirectoryInfo _d in d.GetDirectories())
            {
                ListItem list = new ListItem();
                list.Value = _d.Name.ToString().ToLower();
                list.Text = _d.Name.ToString();
                this.dropTemplateDir.Items.Add(list);
            }
        }

        private void doExport()
        {
            #region 模板导出ZIP
            string sourceFolder = string.Empty;
            string targetFolder = MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/";
            Kesion.Publics.UtilsFile.CreateFolders(targetFolder);
            int templateId = Utils.StrToInt(KSCMS.S("templateID"));
            string templateName = string.Empty;
            string SkinInfoXML = string.Empty;
            string defaultPic = string.Empty;
            using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_Template Where TemplateId=" + templateId))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    defaultPic = dr["defaultPic"].ToString();
                    if (!string.IsNullOrEmpty(defaultPic))
                    {
                        if (!defaultPic.ToLower().StartsWith("http"))
                        {
                            defaultPic = MyCache.GetCacheConfig(5) + defaultPic;
                        }
                    }
                    SkinInfoXML = string.Format(@"<?xml version=""1.0"" encoding=""gb2312""?>
                    <Template>
                      <TemplateName>{0}</TemplateName>
                      <TemplateEName>{1}</TemplateEName>
                      <TemplateType>{2}</TemplateType>
                      <Author>{3}</Author>
                      <AddDate>{4}</AddDate>
                      <Intro><![CDATA[ {5}  ]]></Intro>
                      <DefaultPic>{6}</DefaultPic>
                      <IsViewEdit>{7}</IsViewEdit>
                      <AgentType>{8}</AgentType>
                   </Template>", dr["templateName"].ToString(), dr["templateEName"].ToString(), dr["TemplateType"].ToString(),
                   dr["Author"].ToString(), dr["AddDate"].ToString(), dr["Intro"].ToString(), defaultPic, Utils.StrToInt(dr["isViewEdit"].ToString()).ToString(), Utils.StrToInt(dr["AgentType"].ToString()));

                    templateName = dt.Rows[0]["templateName"].ToString() + ".zip";

                    TemplateDir = GetTemplateAllDir(Utils.StrToInt(dr["TemplateType"].ToString()), ref typeName);  //模板总目录

                    sourceFolder = KSCMS.GetInstallDir() + TemplateDir + "/" + dt.Rows[0]["templateEname"].ToString() + "/";
                    if (!Directory.Exists(Utils.GetMapPath(sourceFolder)))
                    {
                        JS.Alert("对不起，模板目录不存在，无法导出！");
                    }
                }
            }
            if (!string.IsNullOrEmpty(sourceFolder))
            {
                #region 生成模板风格的基本信息到info.xml文件
                string skinInfoFileName = sourceFolder + "info.xml";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(SkinInfoXML);
                xmlDoc.Save(Server.MapPath(skinInfoFileName));
                #endregion

                #region 生成标签的分类到 labelclass.xml
                StringBuilder lbSb = new StringBuilder();
                lbSb.Append(@"<?xml version=""1.0"" encoding=""gb2312""?>
                       <class>
                ");
                using (DataTable dt = DataFactory.GetDataTable("select * from KS_LabelClass Where TemplateID=" + templateId))
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            lbSb.AppendLine(string.Format(@"<item classid=""{0}"" classname=""{1}"" parentidpath=""{2}"" parentid=""{3}"" orderid=""{4}"" classtype=""{5}"" adddate=""{6}"">"
                                , dr["classid"].ToString()
                                , dr["classname"].ToString()
                                , dr["parentidpath"].ToString()
                                , dr["parentid"].ToString()
                                , dr["orderid"].ToString()
                                , dr["classtype"].ToString()
                                , dr["adddate"].ToString()
                                ));
                            lbSb.AppendLine(string.Format(@"<description><![CDATA[ {0}  ]]></description>", dr["description"].ToString()));
                            lbSb.AppendLine("</item>");

                        }
                    }

                }
                lbSb.AppendLine("</class>");
                string labelClassFileName = sourceFolder + "labelClass.xml";
                xmlDoc.LoadXml(lbSb.ToString());
                xmlDoc.Save(Server.MapPath(labelClassFileName));
                #endregion

                #region 生成标签到 label.xml
                lbSb = new StringBuilder();
                lbSb.Append(@"<?xml version=""1.0"" encoding=""gb2312""?>
                       <label>
                ");
                using (DataTable dt = DataFactory.GetDataTable("select * from KS_Label Where TemplateID=" + templateId))
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            lbSb.AppendLine(string.Format(@"<item labelname=""{0}"" classid=""{1}"" orderid=""{2}"" labeltype=""{3}"" labelflag=""{4}"" adddate=""{5}"">"
                                , dr["labelname"].ToString()
                                , dr["classid"].ToString()
                                , dr["orderid"].ToString()
                                , dr["labeltype"].ToString()
                                , dr["labelflag"].ToString()
                                , dr["adddate"].ToString()
                                ));
                            lbSb.AppendLine(string.Format(@"<labelcontent><![CDATA[ {0}  ]]></labelcontent>", dr["labelcontent"].ToString()));
                            lbSb.AppendLine(string.Format(@"<description><![CDATA[ {0}  ]]></description>", dr["description"].ToString()));
                            lbSb.AppendLine("</item>");

                        }
                    }

                }
                lbSb.AppendLine("</label>");
                string labelFileName = sourceFolder + "label.xml";
                xmlDoc.LoadXml(lbSb.ToString());
                xmlDoc.Save(Server.MapPath(labelFileName));
                #endregion

                #region 生成JS标签到 labelJS.xml
                lbSb = new StringBuilder();
                lbSb.Append(@"<?xml version=""1.0"" encoding=""gb2312""?>
                       <labeljs>
                ");
                using (DataTable dt = DataFactory.GetDataTable("select * from KS_JSFile Where TemplateID=" + templateId))
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            lbSb.AppendLine(string.Format(@"<item jsname=""{0}"" jsfilename=""{1}"" jstype=""{2}"" adddate=""{3}"" orderid=""{4}"" classid=""{5}"">"
                                , dr["jsname"].ToString()
                                , dr["jsfilename"].ToString()
                                , dr["jstype"].ToString()
                                , dr["adddate"].ToString()
                                , dr["orderid"].ToString()
                                , dr["classid"].ToString()
                                ));
                            lbSb.AppendLine(string.Format(@"<jsconfig><![CDATA[ {0}  ]]></jsconfig>", dr["jsconfig"].ToString()));
                            lbSb.AppendLine(string.Format(@"<description><![CDATA[ {0}  ]]></description>", dr["description"].ToString()));
                            lbSb.AppendLine("</item>");

                        }
                    }

                }
                lbSb.AppendLine("</labeljs>");
                string labelJSFileName = sourceFolder + "labeljs.xml";
                xmlDoc.LoadXml(lbSb.ToString());
                xmlDoc.Save(Server.MapPath(labelJSFileName));
                #endregion

                #region 保存封面图
                if (!string.IsNullOrEmpty(defaultPic))
                {
                    Public.SaveRemoteFile(defaultPic, sourceFolder + "view.jpg");
                }
                #endregion



                //创建ZIP文件
                Program.CreatePackage(Server.MapPath(sourceFolder), Server.MapPath(targetFolder + templateName));

                //打包完成，删除模板信息XML文件及标签等相关XML文件
                Kesion.Publics.UtilsFile.DelFile(skinInfoFileName);
                Kesion.Publics.UtilsFile.DelFile(labelClassFileName);
                Kesion.Publics.UtilsFile.DelFile(labelFileName);
                Kesion.Publics.UtilsFile.DelFile(labelJSFileName);
                Kesion.Publics.UtilsFile.DelFile(sourceFolder + "view.jpg");

                Response.Redirect(targetFolder + templateName);
            }
            else
            {
                JS.Alert("找不到模板风格！");
            }
            #endregion
        }
        private void doUpload()
        {
            #region 上传ZIP模板
            uploadPanel.Visible = true;
            mainlist.Visible = false;
            #endregion
        }

        private void doDelete()
        {
            #region 删除风格
            int templateId = Utils.StrToInt(KSCMS.S("TemplateId"));
            if (templateId > 0)
            {
                using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_Template Where TemplateID=" + templateId))
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["isdefault"].ToString() == "1")
                        {
                            JS.Alert("对不起，当前风格不能删除!");
                        }
                        else
                        {
                            string templateEname = MyCache.GetCacheConfig(0) + TemplateDir + "/" + dt.Rows[0]["templateEname"].ToString() + "/";
                            UtilsFile.DelFolder(templateEname);
                            DataFactory.ExecuteNonQuery("Delete From KS_Template Where TemplateID=" + templateId);
                            DataFactory.ExecuteNonQuery("Delete From KS_LabelClass Where TemplateID=" + templateId);
                            DataFactory.ExecuteNonQuery("Delete From KS_Label Where TemplateID=" + templateId);
                            DataFactory.ExecuteNonQuery("Delete From KS_JSFile Where TemplateID=" + templateId);
                        }

                    }
                }
            }
            CleanTemplateCache();
            JS.Alert("恭喜，删除成功!", KSCMS.GetComeUrl());
            #endregion
        }



        protected void dlPubInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GV.RowMouseOver(ref e);

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

            }
        }
        protected void dlPubInfo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                string[] Param = e.CommandArgument.ToString().Split('|');
            }
            else if (e.CommandName == "txtedit" || e.CommandName == "viewedit")
            {
                this.mainlist.Visible = false;
                this.addlist.Visible = true;
            }
        }


        protected void dlPubInfo_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btn = (LinkButton)e.Row.FindControl("LinkDelButton");
                btn.Attributes.Add("onclick", "return confirm('此操作不可逆，您确认要删除吗？');");
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            #region 保存添加/修改
            string templateName = this.TxtTemplateName.Text;
            string templateEname = this.dropTemplateDir.SelectedValue;
            int templateId = Utils.StrToInt(this.HidTemplateId.Value);
            if (string.IsNullOrEmpty(templateName))
            {
                JS.Alert("请输入模板风格名称!");
            }
            if (string.IsNullOrEmpty(templateEname))
            {
                JS.Alert("请选择模板所在目录");
            }
            if (DataFactory.Exists("KS_Template", "templatetype=" + Utils.StrToInt(this.HidTemplateType.Value) + " and templateid<>" + templateId + " and templatename = '" + templateName + "'"))
            {
                JS.Alert("对不起，模板风格名称已存在！");
            }
            if (DataFactory.Exists("KS_Template", "templatetype=" + Utils.StrToInt(this.HidTemplateType.Value) + " and templateid <>" + templateId + " and templateename = '" + templateEname + "'"))
            {
                JS.Alert("对不起，模板目录已存在！");
            }
            Hashtable ht = new Hashtable();
            ht.Add("templatename", templateName);
            ht.Add("templateename", templateEname.ToLower());
            ht.Add("defaultpic", this.TxtDefaultPic.Text);
            ht.Add("author", this.TxtAuthor.Text);
            ht.Add("intro", this.TxtIntro.Text);
            if (TemplateType == 4)     //分销类型
            {
                if (Kesion.ODS.AgentClass.GetFXSVersion() == 3)
                {
                    ht.Add("AgentType", this.AgentType.SelectedValue);

                }
                else if (Kesion.ODS.AgentClass.GetFXSVersion() == 2)
                {
                    ht.Add("AgentType", 2);
                }
                else if (Kesion.ODS.AgentClass.GetFXSVersion() == 1)
                {
                    ht.Add("AgentType", 1);
                }
            }
            if (TemplateType == 0)     //是否响应式
            {
                ht.Add("IsResponsive", this.IsResponsive.SelectedValue);
            }
            ht.Add("IsViewEdit", Utils.StrToInt(this.RdbIsViewEdit.SelectedValue));    //是否可视化


            #region 机构及空间模板加权限
            if (Utils.StrToInt(this.HidTemplateType.Value) == 2)
            {
                string listvalue = string.Empty;
                for (int i = 0; i < CheckBoxList1.Items.Count; i++)
                {
                    if (CheckBoxList1.Items[i].Selected == true)
                    {
                        listvalue = listvalue + "," + CheckBoxList1.Items[i].Value;
                    }
                }
                listvalue = Utils.FilterRepeatInArray(listvalue, ",");
                ht.Add("GroupLevel", listvalue);
            }
            else if (Utils.StrToInt(this.HidTemplateType.Value) == 3)
            {
                ht.Add("GroupLevel", KSCMS.S("DefaultArrGroupID"));
            }
            #endregion

            if (this.HidTemplateId.Value == "0")
            {
                ht.Add("isdefault", 0);
                ht.Add("OriTemplateID", 0);
                ht.Add("templateType", Utils.StrToInt(this.HidTemplateType.Value));
                ht.Add("adddate", DateTime.Now);
                CommonData.Insert("KS_Template", ht);
                CleanTemplateCache();
                JS.Confirm("恭喜，模板风格添加成功，继续添加吗？", "location.href='" + KSCMS.GetInstallDir() + MyCache.GetCacheConfig(4) + "/label/KS.TemplateSkin.aspx?action=add&showType=" + TemplateType + "'", "top.box.close()");
            }
            else
            {
                CommonData.Update("KS_Template", ht, "where templateid=" + Utils.StrToInt(this.HidTemplateId.Value));
                CleanTemplateCache();
                JS.AlertDoFun("恭喜，模板风格修改成功！", "top.box.close();");
            }
            #endregion

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            #region 上传Zip压缩包
            if (File1.HasFile)
            {
                Kesion.Publics.UtilsFile.CreateFolders(uploadFolder);
                if (!File1.FileName.ToLower().EndsWith(".zip"))
                {
                    JS.Alert("对不起，上传格式不正确，请上传ZIP模板包！");
                }
                File1.SaveAs(zipFile);

                DoZipImport();
            }
            else
            {
                JS.Alert("请选择ZIP模板压缩包!");
            }
            #endregion
        }

        private void DoZipImport()
        {
            #region 本地导入或是下载云端成功后 执行导入
            Kesion.Publics.UtilsFile.CreateFolders(targetFolder);
            Program.ExtractPackage(Server.MapPath(targetFolder), zipFile, false);
            //删除ZIP包
            Kesion.Publics.UtilsFile.DelFile(zipFile);

            string SkinInfoXML = targetFolder + "info.xml";
            if (!UtilsFile.FileOrDirectoryIFExist(SkinInfoXML))
            {
                JS.AlertDoFun("对不起,ZIP模板压缩包格式不正确，上传失败!", "top.box.close()");
            }
            else
            {

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(Server.MapPath(SkinInfoXML));
                if (xmlDoc != null)
                {
                    #region 上传成功，入库
                    Response.Redirect(KSCMS.GetInstallDir() + MyCache.GetCacheConfig(4) + "/label/KS.TemplateSkin.aspx?action=UploadStep2&showType=" + TemplateType + "&templateID=" + Utils.StrToInt(KSCMS.S("TemplateID")));
                    #endregion

                    // JS.Alert("恭喜,ZIP压缩包上传成功!");
                }
                else
                {
                    JS.Alert("对不起,读不到ZIP模板压缩包信息，上传失败!");
                }
            }
            #endregion
        }


        public static void CleanTemplateCache()
        {
            #region 清缓存
            KSCache cache = KSCache.GetCacheService();
            cache.RemoveObject("/CMS/TemplateTable");
            #endregion
        }

        private void uploadStep2()
        {
            #region 确认导入
            this.mainlist.Visible = false;
            this.uploadPanel.Visible = false;
            this.uploadPanelStep2.Visible = true;
            string SkinInfoXML = targetFolder + "info.xml";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(SkinInfoXML));
            if (xmlDoc != null)
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode("Template");
                string templateName = ((XmlElement)xmlNode.SelectSingleNode("TemplateName")).InnerText;
                string templateEName = ((XmlElement)xmlNode.SelectSingleNode("TemplateEName")).InnerText;
                string templateAuthor = ((XmlElement)xmlNode.SelectSingleNode("Author")).InnerText;
                string templateIntro = ((XmlElement)xmlNode.SelectSingleNode("Intro")).InnerText;
                HidOriTemplateId.Value = Utils.StrToInt(KSCMS.S("templateId")).ToString();
                int templateType = Utils.StrToInt(((XmlElement)xmlNode.SelectSingleNode("TemplateType")).InnerText);

                TemplateDir = GetTemplateAllDir(templateType, ref typeName);

                this.LabTemplateDir.Text = TemplateDir;
                this.TxtName.Text = templateName;
                this.LabAuthor.Text = templateAuthor;
                this.LabIntro.Text = templateIntro;
                this.TxtEname.Text = templateEName;
            }
            #endregion

        }

        private void checkEname()
        {
            #region 检查模板目录是否可用
            string eName = KSCMS.S("ename");
            if (string.IsNullOrEmpty(eName))
            {
                KSCMS.Die("对不起，模板目录不能为空!");
            }
            else
            {
                string skinDir = MyCache.GetCacheConfig(0) + TemplateDir + "/" + eName + "/";
                if (System.IO.Directory.Exists(Utils.GetMapPath(skinDir)))
                {
                    KSCMS.Die("对不起，您要导入的模板目录[" + skinDir + "]已存在了，请重新输入！");
                }
                else
                {
                    KSCMS.Die("true");
                }
            }
            #endregion
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            #region 确认执行导入ZIP
            string templateName = this.TxtName.Text;
            string templateEname = this.TxtEname.Text;
            if (string.IsNullOrEmpty(templateName))
            {
                JS.Alert("对不起，请输入模板名称！");
            }
            if (string.IsNullOrEmpty(templateEname))
            {
                JS.Alert("对不起，导入的目录不能为空！");
            }
            TemplateDir = LabTemplateDir.Text;
            string skinDir = MyCache.GetCacheConfig(0) + TemplateDir + "/" + templateEname + "/";

            if (DataFactory.Exists("KS_Template", "templatename='" + Utils.ChkSQL(templateName) + "'"))
            {
                JS.Alert("对不起，您要导入的模板名称已存在了，请重新输入！");

            }

            if (System.IO.Directory.Exists(Utils.GetMapPath(skinDir)))
            {
                JS.Alert("对不起，您要导入的模板目录[" + skinDir + "]已存在了，请重新输入！");
            }

            if (ZipTemplateToDB(targetFolder, skinDir, Utils.StrToInt(HidOriTemplateId.Value), templateName))
            {
                JS.AlertDoFun("恭喜，模板风格导入成功！", "top.frames['main'].location.href='" + KSCMS.GetInstallDir() + MyCache.GetCacheConfig(4) + "/Label/KS.TemplateSkin.aspx';top.box.close();");
            }
            else
            {
                JS.Alert("对不起无法导入，读取模板配置文件失败！");
            }

            #endregion
        }



        private void ImportLabelClass(int oldParentid, int newParentID, int templateId, XmlNode root)
        {
            #region 导入标签分类
            XmlNodeList items = root.SelectNodes("//item[@parentid='" + oldParentid + "']");
            foreach (XmlNode item in items)
            {

                LabelClassInfo __info = new LabelClassInfo();
                __info.ClassName = item.Attributes["classname"].InnerText;
                __info.ParentID = newParentID;
                __info.ParentIDPath = "0";
                __info.Description = item.SelectSingleNode("description").InnerText;
                __info.ClassType = Utils.StrToInt(item.Attributes["classtype"].InnerText);
                __info.OrderID = 0;
                __info.AddDate = Convert.ToDateTime(item.Attributes["adddate"].InnerText);
                __info.From3G = 0;
                __info.TemplateID = templateId;

                if (LabelClassManage.CreateLabelClass(__info).Equals("success"))
                {
                    int newClassID = CommonData.GetMaxId("KS_LabelCLass", "classid");
                    classDic.Add("classid" + item.Attributes["classid"].InnerText, newClassID.ToString());
                    ImportLabelClass(Utils.StrToInt(item.Attributes["classid"].InnerText), newClassID, templateId, root);

                }



                //  KSCMS.W(item.Attributes["classname"].InnerText + "===" + item.SelectSingleNode("description").InnerText + "<br/>");
            }
            #endregion
        }


        private void initialClone()
        {
            #region 初始化克隆
            this.clonePanel.Visible = true;
            this.mainlist.Visible = false;
            int templateId = Utils.StrToInt(KSCMS.S("templateid"));
            using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_Template Where TemplateID=" + templateId))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    this.TxtCloneTemplateName.Text = dr["templatename"].ToString() + "_new";
                    this.TxtCloneTemplateEName.Text = dr["templateEname"].ToString() + "_new";
                    this.HiddenTemplateId.Value = templateId.ToString();
                }
                else
                {
                    KSCMS.Die("error");
                }
            }
            #endregion
        }
        protected void Button4_Click(object sender, EventArgs e)
        {
            #region 确认克隆
            int templateId = Utils.StrToInt(HiddenTemplateId.Value);
            string templateName = this.TxtCloneTemplateName.Text;
            string templateEname = this.TxtCloneTemplateEName.Text;
            if (string.IsNullOrEmpty(templateName))
            {
                JS.Alert("请输入模板名称！");
            }
            if (string.IsNullOrEmpty(templateEname))
            {
                JS.Alert("请输入模板文件存放目录！");
            }
            if (DataFactory.Exists("KS_Template", "templateType=" + TemplateType + " and templatename='" + Utils.ChkSQL(templateName) + "'"))
            {
                JS.Alert("模板名称已存在，请重新输入！");
            }
            if (DataFactory.Exists("KS_Template", "templateType=" + TemplateType + " and templateEname ='" + Utils.ChkSQL(templateEname) + "'"))
            {
                JS.Alert("模板文件存放目录[" + templateEname + "]已存在，请重新输入！");
            }

            using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_Template Where TemplateID=" + templateId))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    string oldTemplateEname = dr["templateEname"].ToString();
                    string sourceFolder = KSCMS.GetInstallDir() + TemplateDir + "/" + oldTemplateEname + "/";
                    string destFolder = KSCMS.GetInstallDir() + TemplateDir + "/" + templateEname + "/";

                    #region 写入模板风格表

                    Hashtable ht = new Hashtable();
                    ht.Add("TemplateName", templateName);
                    ht.Add("TemplateEName", templateEname);
                    ht.Add("Author", dr["author"].ToString());
                    ht.Add("Intro", dr["intro"].ToString());
                    ht.Add("AddDate", dr["adddate"].ToString());
                    ht.Add("defaultPic", dr["defaultPic"].ToString());
                    ht.Add("TemplateType", dr["templateType"].ToString());
                    ht.Add("OriTemplateID", dr["OriTemplateID"].ToString());
                    ht.Add("IsViewEdit", dr["IsViewEdit"].ToString());
                    ht.Add("IsDefault", 0);
                    ht.Add("AgentType", dr["agentType"].ToString());
                    CommonData.Insert("KS_Template", ht);

                    int newTemplateId = CommonData.GetMaxId("KS_Template", "templateId");
                    #endregion

                    #region 克隆标签目录
                    CloneLabelClass(templateId, newTemplateId, 0, 0);
                    #endregion

                    #region 克隆标签
                    using (DataTable dtl = DataFactory.GetDataTable("select * From KS_Label Where TemplateID=" + templateId))
                    {
                        if (dtl.Rows.Count > 0)
                        {
                            foreach (DataRow drl in dtl.Rows)
                            {
                                ht = new Hashtable();
                                ht.Add("labelid", CommonData.GetMaxIdAddOne("KS_Label", "labelid"));
                                ht.Add("labelname", drl["labelname"].ToString());
                                ht.Add("labelcontent", drl["labelcontent"].ToString());
                                ht.Add("description", drl["description"].ToString());
                                int oldClassid = Utils.StrToInt(drl["classid"].ToString());
                                if (classDic.ContainsKey("classid" + oldClassid))
                                {
                                    ht.Add("classid", Utils.StrToInt(classDic["classid" + oldClassid].ToString()));
                                }
                                else
                                {
                                    ht.Add("classid", 0);
                                }
                                ht.Add("orderid", drl["orderid"].ToString());
                                ht.Add("labeltype", drl["labeltype"].ToString());
                                ht.Add("labelflag", drl["labelflag"].ToString());
                                ht.Add("adddate", drl["adddate"].ToString());
                                ht.Add("from3g", 0);
                                ht.Add("templateid", newTemplateId);
                                CommonData.Insert("KS_Label", ht);

                            }
                        }
                    }
                    #endregion

                    #region 克隆JS标签
                    using (DataTable dtl = DataFactory.GetDataTable("select * From KS_JSFile Where TemplateID=" + templateId))
                    {
                        if (dtl.Rows.Count > 0)
                        {
                            foreach (DataRow drl in dtl.Rows)
                            {
                                ht = new Hashtable();
                                ht.Add("jsname", drl["jsname"].ToString());
                                ht.Add("jsfilename", drl["jsfilename"].ToString());
                                ht.Add("jsconfig", drl["jsconfig"].ToString());
                                ht.Add("description", drl["description"].ToString());
                                ht.Add("jstype", drl["jstype"].ToString());
                                ht.Add("adddate", drl["adddate"].ToString());
                                ht.Add("orderid", drl["orderid"].ToString());
                                int oldClassid = Utils.StrToInt(drl["classid"].ToString());
                                if (classDic.ContainsKey("classid" + oldClassid))
                                {
                                    ht.Add("classid", Utils.StrToInt(classDic["classid" + oldClassid].ToString()));
                                }
                                else
                                {
                                    ht.Add("classid", 0);
                                }
                                ht.Add("from3g", 0);
                                ht.Add("templateid", newTemplateId);
                                CommonData.Insert("KS_JSFile", ht);
                            }
                        }
                    }
                    #endregion


                    //复制模板文件
                    UtilsFile.CopyDir(Utils.GetMapPath(sourceFolder), Utils.GetMapPath(destFolder));
                    JS.AlertDoFun("恭喜，模板风格克隆成功！", "top.box.close()");
                }
                else
                {
                    KSCMS.Die("error");
                }
            }

            #endregion
        }


        private void CloneLabelClass(int oldTemplateId, int newTemplateID, int parentId, int newParentID)
        {
            #region 克隆标签目录
            using (DataTable dt = DataFactory.GetDataTable("select * From KS_LabelClass where templateID=" + oldTemplateId + " and parentId=" + parentId))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {

                        LabelClassInfo __info = new LabelClassInfo();
                        __info.ClassName = dr["classname"].ToString();
                        __info.ParentID = newParentID;
                        __info.ParentIDPath = "0";
                        __info.Description = dr["description"].ToString();
                        __info.ClassType = Utils.StrToInt(dr["classtype"].ToString());
                        __info.OrderID = 0;
                        __info.AddDate = Convert.ToDateTime(dr["adddate"].ToString());
                        __info.From3G = 0;
                        __info.TemplateID = newTemplateID;

                        if (LabelClassManage.CreateLabelClass(__info).Equals("success"))
                        {
                            int newClassID = CommonData.GetMaxId("KS_LabelCLass", "classid");
                            classDic.Add("classid" + dr["classid"].ToString(), newClassID.ToString());
                            CloneLabelClass(oldTemplateId, newTemplateID, Utils.StrToInt(dr["classid"].ToString()), newClassID);

                        }


                    }
                }

            }
            #endregion
        }


        public string ShowButton(decimal prices, int infoId)
        {
            #region 显示操作按钮
            string str = string.Empty;
            if (Kesion.BLL.Yun.YunTemplateHasDown(infoId))
            {
                str = @"<a href='#'><i class='iconfont icon suc'>&#xe603;</i>已下载</a>";
            }
            else
            {
                if (prices > 0)
                {
                    if (!IsYunAccount)
                    {
                        str = @"<a href='javascript:;' onclick=""KesionJS.Alert('请先对接云市场','location.href=\'/" + MyCache.GetCacheConfig(4) + @"/yun/KS.YunAccountApi.aspx\';')"">去购买</a>";
                    }
                    else
                    {
                        if (Kesion.BLL.Yun.YunProductHasPower(infoId))
                        {
                            str = @"<a href=""javascript:;"" onclick='YunDownLoad(" + Eval("templateId") + "," + CurrPage + @")'>下载并导入</a>";
                        }
                        else
                        {
                            str = "<a href=\"" + Kesion.BLL.Yun.GetServerUrl + "/websys/orderinfo.aspx?id=" + infoId + "&token=" + Token + "&appid=" + Appid + "\"  target=\"_blank\">去购买</a>";
                        }
                    }
                }
                else
                {
                    str = @"<a href=""javascript:;"" onclick='YunDownLoad(" + Eval("templateId") + "," + CurrPage + @")'>下载并导入</a>";
                }
            }

            return str;
            #endregion

        }


        private void GetToken()
        {
            IsYunAccount = Kesion.BLL.Yun.IsYunAccount();
            Token = Kesion.BLL.Yun.GetToken();
            Appid = Kesion.BLL.Yun.GetYunAccountInfo("appid");


        }
    }
}
