<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="Kesion.APPCode" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Kesion.Course" %>
<%@ Import Namespace="Kesion.Components" %>
<%@ Import Namespace="System.IO" %>
<script runat="server" type="text/C#">

    DataTable dt;

    int sum = 0;
    int num = 0;
    int dbtype;
    int passmd5 = 0;
    int groupid = 0;
    string ConnectionString;
    int succnum = 0;
    int errornum = 0;
    string[] sk = new string[100];
    string[] csk = new string[100];
    StringBuilder sb = new StringBuilder();//导入成功数据
    StringBuilder ss = new StringBuilder(); //导入失效数据
    protected void Page_Load(object sender, EventArgs e)
    {
        if (KSCMS.S("action") == "CheckDataSource")
        {
            //测试数据源
            Response.Write(LabelSource.CheckDataSource(Utils.StrToInt(KSCMS.S("lst", false)), KSCMS.S("cstr", false)));
            Response.End();
        }
        else if (KSCMS.S("action") == "loadTable")
        {
            StringBuilder sb = new StringBuilder();
            using (DataTable dt = LabelSource.getAllTable(Utils.StrToInt(KSCMS.S("lst", false)), KSCMS.S("cstr", false)))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("<option value='" + dr["TABLE_NAME"].ToString() + "'>" + dr["TABLE_NAME"].ToString() + "</option>");
                }
            }
            KSCMS.W(sb.ToString());
        }
        else if (KSCMS.S("action") == "content" && KSCMS.S("flag") == "pause")
        {
            check();
        }
        else
        {
            if (KSCMS.S("upload") == "upload") //导入
            {
                check();
            }
        }
    }
    public void loaddata()
    {
        dbtype = Utils.StrToInt(KSCMS.S("LabelDataSource"));
        ConnectionString = KSCMS.S("ConnStr");
    }
    private string GetDataField(string fieldname)
    {
        DataTable sourceFieldDT = null;

        if (sourceFieldDT == null)
        {
            string tablename = KSCMS.S("tablename");
            sourceFieldDT = LabelSource.getTableFiled(dbtype, ConnectionString, tablename);
        }
        StringBuilder sb = new StringBuilder();

        if (fieldname.ToLower() == "groupid")
        {
            sb.Append("<select name='" + fieldname + @"' onchange=""if (this.value==0){ jQuery('#showgroup').show(); }else{ jQuery('#showgroup').hide(); } "">");
            sb.Append("<option value='0'>从数据源字段导入</option>");
            using (DataTable dt = MyCache.GetUserGroupTable())
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.AppendFormat("<option value='{0}'{2}>{1}</option>", dr["groupid"].ToString(), dr["groupname"].ToString(), dr["groupid"].ToString() == "2" ? " selected" : string.Empty);
                }
            }
            sb.Append("</select>");
            sb.Append("<select id='showgroup' style='display:none' name='field" + fieldname + "'>");

        }
        else
        {
            sb.Append("<select id='" + fieldname + "' name='field" + fieldname + "'>");

        }
        sb.Append("<option value='0'>此字段不导入</option>");
        using (DataTable dtfield = sourceFieldDT)
        {
            foreach (DataRow dr in dtfield.Rows)
            {

                sb.Append(string.Format("<option value='{0}'{1}>{0}</option>", dr["COLUMN_NAME"].ToString(), fieldname.ToLower() == dr["COLUMN_NAME"].ToString().ToLower() ? " selected" : ""));

            }
        }
        sb.Append("</select>");
        return sb.ToString();

    }

    public void check()
    {
        if (dt != null)
        {
            int PauseTime = 1;
            int count = Utils.StrToInt(KSCMS.S("CurrNowNum"));
            int nownum = 0;
            if (Utils.StrToInt(KSCMS.S("CurrNowNum")) > 0)
            {
                nownum = Utils.StrToInt(KSCMS.S("CurrNowNum"));
            }
            if (nownum == 0)
            {
                succnum = 0;
                errornum = 0;
            }
            ShowMain();
            for (int i = nownum; i < dt.Rows.Count; i++)
            {

                DataRow dr = dt.Rows[i];
                Hashtable ht = new Hashtable();
                if (KSCMS.S("flag") != "pause")
                {
                    passmd5 = Utils.StrToInt(KSCMS.S("passmd5"));
                    groupid = Utils.StrToInt(KSCMS.S("groupid"));
                    using (DataTable dtfield = LabelSource.getTableFiled(0, ConnectionString, "KS_User", true))
                    {
                        int j = 0;
                        foreach (DataRow dc in dtfield.Rows)
                        {
                            if (dc["COLUMN_NAME"].ToString().ToLower() != "groupid" || (dc["COLUMN_NAME"].ToString().ToLower() == "groupid" && groupid == 0))
                            {
                                //KSCMS.W(KSCMS.S("field" + dc["COLUMN_NAME"].ToString()) + "==" + dc["COLUMN_NAME"].ToString() + "<br/>");
                                sk[j] = KSCMS.S("field" + dc["COLUMN_NAME"].ToString());
                                csk[j] = dc["COLUMN_NAME"].ToString();
                                j++;
                            }
                        }

                    }
                }
                string[] dateField = { "regdate", "joindate", "begindate", "lastlogintime", "birthday" };
                string[] numField = { "privacy", "logintimes", "chargetype", "edays", "score", "money", "scorehasuse", "point", "locked" };

                // if (groupid != 0) ht.Add("groupid", groupid);
                ht.Add("groupid", 2);
                ht.Add("agent", UserManage.GetUserInfo(new TemporaryVar().UserName).UserName);
                string username = "";
                for (int kk = 0; kk < sk.Length; kk++)
                {
                    if (sk[kk] != "0" && !string.IsNullOrEmpty(sk[kk]))
                    {
                        #region 有选择导入的字段
                        if (csk[kk].ToUpper() == "USERNAME")
                        {
                            username = dr[sk[kk]].ToString();
                        }

                        if (csk[kk].ToUpper() == "PASSWORD" && passmd5 == 1)
                        {
                            ht.Add(csk[kk], Utils.MD5(dr[sk[kk]].ToString(), 16));
                        }
                        //else if (csk[kk].ToUpper() == "GROUPID" && groupid != 0)
                        //{
                        //    ht.Add(csk[kk].ToLower(), groupid);
                        //}
                        else
                        {
                            switch (csk[kk].ToLower())
                            {
                                case "chargetype":
                                case "logintimes":
                                case "edays":
                                case "score":
                                case "money":
                                case "scorehasuse":
                                case "point":
                                case "locked":
                                case "groupid":
                                    ht.Add(csk[kk], Utils.StrToInt(dr[sk[kk]].ToString()));
                                    break;
                                case "regdate":
                                case "joindate":
                                case "begindate":
                                case "lastlogintime":
                                case "birthday":
                                    if (Utils.IsDateTime(dr[sk[kk]].ToString()))
                                    {
                                        ht.Add(csk[kk], dr[sk[kk]].ToString());
                                    }
                                    else
                                    {
                                        ht.Add(csk[kk], DateTime.Now);
                                    }
                                    break;
                                default:
                                    ht.Add(csk[kk], dr[sk[kk]].ToString());
                                    break;
                            }
                        }
                        #endregion
                    }
                    else if (sk[kk] == "0")
                    {
                        if (Utils.InArray(csk[kk].ToLower(), dateField, true) == true)
                        {
                            ht.Add(csk[kk], DateTime.Now);
                        }
                        else if (Utils.InArray(csk[kk].ToLower(), numField, true) == true)
                        {
                            if (csk[kk].ToLower() == "chargetype")
                            {
                                ht.Add(csk[kk], 1);
                            }
                            else
                            {
                                ht.Add(csk[kk], 0);
                            }
                        }
                    }

                }

                if (string.IsNullOrEmpty(username))
                {
                    errornum++;
                }
                else
                {
                    string sql = "select top 1 userid from ks_user where username='" + username + "'";
                    int id = Utils.StrToInt(DataFactoryUser.GetOnlyValue(sql)); //判断用户是否已经存在
                    if (id <= 0)
                    {
                        succnum++;
                        CommonDataUser.Insert("ks_user", ht);
                        sb.AppendLine("会员名[" + username + "]导入成功\n");
                    }
                    else
                    {
                        errornum++;
                        ss.AppendLine("会员名[" + username + "]已存在:\n");
                    }
                }
                count++;
                ///InnerJS(count, dt.Rows.Count, "位会员");
                if (count % 100 == 0)
                {
                    string url = "EpUserImport.aspx?action=content&from=" + KSCMS.S("from") + "&flag=pause&CurrNowNum=" + count;
                    KSCMS.W("<scr"+"ipt>");
                    KSCMS.W(@"fsohtml.innerHTML='<div style=""text-align:cdenter""><div style=""margin:10px;height:80px;padding:8px;border:1px dashed #cccccc;text-align:left;""><img src=""../../admin/images/info_success_48.gif"" align=""left""><br>&nbsp;&nbsp;&nbsp;&nbsp;<b>温馨提示：</b><br>&nbsp;&nbsp;&nbsp;&nbsp;以免过度占用服务器资源，系统暂停" + PauseTime + @"秒后继续<img src=""../../admin/images/wait.gif""><br>&nbsp;&nbsp;&nbsp;&nbsp;如果" + PauseTime + @"秒后没有继续，请点此<a href=""" + url + @"""><font color=red>继续</font></a>或点此<a href=""EpUserImport.aspx""><font color=red>停止</font></a>!</div></div>';");
                    KSCMS.W("</scr"+"ipt>");
                    KSCMS.W(@"<meta http-equiv=""refresh"" content=""" + PauseTime + @";url=" + url + @""">");
                }
            }
        }
        else
        {
            Msg.Alert("请绑定数据源");
            return;
        }
        sucss(sb.ToString()); //导入成功记录    
        final(ss.ToString());   //导入失效记录   

        KSCMS.W("<script>");
        KSCMS.W("fsohtml.innerHTML='';");
        KSCMS.W("img2.width=400;");
        KSCMS.W("txt2.innerHTML='导入进度:100';");
        KSCMS.W(string.Format(@"txt3.innerHTML=""总共有 <font color=blue><b>{0}</b></font> 位会员， 导入成功 <font color=green><b>{1}</b></font> 位，导入失败 <font color=red><b>{2}</b></font> 位！"";", dt.Rows.Count, succnum, errornum));
        KSCMS.W("</scr"+"ipt>");
        KSCMS.W(@"<div style='text-align:center;margin-top:10px'><input type='button' value='返回' onclick=""location.href='EpUserImport.aspx';"" class='button'/></div>");
    }
    public void sucss(string str)
    {
        try
        {
            FileStream fs = new FileStream(Server.MapPath("~/UploadFiles/temp/user_import_success_log.txt"), FileMode.CreateNew);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(str);
            fs.Close();
        }
        catch (Exception)
        {

        }
    }
    public void final(string str)
    {

        try
        {
            FileStream fs = new FileStream(Server.MapPath("~/UploadFiles/temp/user_import_error_log.txt"), FileMode.CreateNew);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(str);
            sw.Flush();
            fs.Close();
        }
        catch (Exception)
        {

        }
    }

    private void ShowMain()
    {
        #region 显示主体
        string str = @"
                    <!DOCTYPE html><html>
                    <head>
                      <link href='/admin/images/style.CSS' rel='stylesheet' type='text/css' />
                    </head>
                  <body scroll=no bgcolor='transparent'>
                   ";

        str += @"<div><br><br>";
        str += @"<table id=""BarShowArea"" width=""400"" border=""0"" align=""center"" cellspacing=""1"" cellpadding=""1"">
				    <tr>
				    <td bgcolor=000000>
				     <table width=""400"" border=""0"" cellspacing=""0"" cellpadding=""1"">
				    <tr>
				    <td bgcolor=ffffff height=9><img src=""../../sysimg/default/bar.gif"" width=0 height=10 id=img2 name=img2 align=absmiddle></td></tr></table>
				    <td bgcolor=ffffff height=9><span width=0 height=16 id=Span1 name=img2 align=absmiddle bgcolor='#000000'></span></td></tr></table>
				    </td></tr></table>
				    <table width=""550"" border=""0"" align=""center"" cellspacing=""1"" cellpadding=""1""><tr>
				    <td align=center> <span id=txt2 name=txt2 style=""font-size:9pt"">0</span><span id=txt4 style=""font-size:9pt"">%</span></td></tr>
				    <tr><td align=center><span id=txt3 name=txt3 style=""font-size:9pt"">0</span></td></tr>
				    </table>
    			
			     <table width=""80%""  border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"">
			      <tr>
			        <td height=""50"">
			          <div align=""center""> 
			            </div>
			          </td>
			        </tr>
			     </table>
			     </div>
    		 

		     <table width=""100%""   border=""0"" cellpadding=""0"" cellspacing=""0"">
		      <tr>
		        <td height=""50"" id=""fsohtml"">
		           </td>
		        </tr>
		     </table>
           </body>
         </htmL>
              ";
        KSCMS.W(str);
        #endregion
    }

    private void InnerJS(int NowNum, int TotalNum, string itemname)
    {
        #region 显示进度
        KSCMS.W("<script>");
        // KSCMS.W(string.Format(@"fsohtml.innerHTML='{0}';", ListStr));
        KSCMS.W(string.Format(@"img2.width={0};", ((double)NowNum / TotalNum) * 400));
        KSCMS.W(string.Format(@"txt2.innerHTML=""导入进度:{0}"";", (((double)NowNum / TotalNum) * 100).ToString("f2")));
        KSCMS.W(string.Format(@"txt3.innerHTML=""总共导入 <font color=red><b>{0}</b></font> {1},<font color=red><b>在此过程中请勿刷新此页面！！！</b></font> 系统正在导入第 <font color=red><b>{2}</b></font> {1}"";", TotalNum, itemname, NowNum));
        KSCMS.W("</scr"+"ipt>");
        KSCMS.Flush();
        #endregion

    }
</script>
   <style type="text/css"> 
body{ 
text-align:center; 
} 
.graph{ 
width:450px; 
border:1px solid #9bdf70; 
height:25px; 
} 
#bar{ 
display:block; 
background:#FFE7F4; 
float:left; 
height:100%; 
text-align:center; 
} 
#barNum{ 
position:absolute; 
} 
</style>
<script type="text/javascript">

    function loadTable() {
        jQuery("#showtable").show();
        jQuery.get("{=getUserUrl(teacher/UserImport,action-loadTable|lst-" + jQuery('#LabelDataSource>option:selected').val() + "|cstr-" + jQuery('#ConnStr').val() + ")}", function (s) {
            jQuery("#tablename").empty().append(s);
        });
    }
    function checkdatasource() {
        var lst = jQuery('#LabelDataSource>option:selected').val();
        var cstr =jQuery('#ConnStr').val();
        jQuery.get("{=getUserUrl(teacher/UserImport,action-CheckDataSource|lst-"+lst+"|cstr-"+cstr+")}", function (s) {
            if (s == 'true') {
                KesionJS.AlertByTime(1, '恭喜，数据源连接测试通过!', 2);
                loadTable();
            }
            else {
                KesionJS.AlertByTime(2, '连接出错，请检查连接字符串!', 2);
            }
            return false;
        });
    }

    function changeconnstr() {
        switch (parseInt(jQuery('#LabelDataSource>option:selected').val())) {
            case 1:
                jQuery('#ConnStr').val('/DBPath/数据库.mdb');
             break;
         case 2:
             jQuery('#ConnStr').val('User ID=sa; Password=989066; Initial Catalog=kesionicms; server=(local);');
             break;
         case 3:
             jQuery('#ConnStr').val('DSN=数据源名;UID=用户名;PWD=密码');
                 break;
             case 4:
                 jQuery('#ConnStr').val('Data Source=数据源名;User Id=用户名;Password=密码;Integrated Security=no;');
                 break;
             case 5:
                 jQuery('#ConnStr').val('/DBPath/test.xls');
                 break;
             case 6:
                 jQuery('#ConnStr').val('Data Source=完整数据库路径+名称;Provider=Microsoft.JET.OLEDB.4.0;');
                 break;
         }
     }

    </script>
<form action="{$GetCurrUrl}" method="post">
    <input type="hidden" name="upload" value="upload" />
     <div ID="top"  Width="100%">

      <table width="96%" align="center" border="0" cellpadding="1" cellspacing="1" class="CTable">  
          <tr><td class="lefttd" style="text-align:left;padding-left:4px;"><strong>第一步 请选择数据源</strong></td></tr>
          </table>
    <br />
      <table width="96%" align="center" border="0" cellpadding="1" cellspacing="1" class="CTable">  
           <tr>
               <td class="lefttd" style="height: 30px; text-align: right">
                    <strong>数 据 源：</strong></td>
                <td class="righttd" style="height: 30px; text-align: left">
                        <select name="LabelDataSource" ID="LabelDataSource" onchange="changeconnstr()" >
                       <%--  <asp:ListItem Value="1"  Selected="true">外部Access数据源</asp:ListItem>
                         <asp:ListItem Value="2">外部MS SQL数据源</asp:ListItem>
                         <asp:ListItem Value="3">外部ODBC数据源</asp:ListItem>
                         <asp:ListItem Value="4">外部Oracle数据源</asp:ListItem>--%>
                         <option Value="5" selected>外部Excel数据源</option>
                        <%-- <asp:ListItem Value="6">外部OLE数据源</asp:ListItem> --%>
                        </select>
       
                </td>
            </tr>
      <tr>
                <td class="lefttd" style="height: 30px; text-align: right">
                    <strong>连接字符串：</strong></td>
                <td class="righttd" style="height: 30px; text-align: left">
                 <input type="text" name="ConnStr" ID="ConnStr"  Height="50px" TextMode="MultiLine" Width="450px"></input>
                         <%=Kesion.APPCode.UploadAPI.EchoUpload("useruploadexcelfile","ConnStr")%>
                    <br />
                    <input type="button" ID="TextButton"  value="测试数据源" Class="button" onclick="return(checkdatasource())"  />

                </td>
            </tr> 
          <tbody  style="display:none;" id="showtable">
        <tr>
        <td class="lefttd" style="height: 30px; text-align: right"><strong>请选择要导入数据表：</strong></td>
          <td class="righttd" style="height: 30px; text-align: left" > 
              <select name="tablename" id="tablename"></select>
         </td>
     </tr> 
          <tr>
                <td class="lefttd" style="height: 30px; text-align: right">
                            
                    </td>
           <td class="righttd" style="height: 30px; text-align: left">  
               <input type="button" ID="Button1"  Class="button" OnClick="Button1_Click" value="下一步" />
            </td>
          </tr>
              </tbody> 
  </table>
  </div>   
     <div ID="list"  Width="100%">
           <span ID="Label1"  Text="Label"></span>
         <br />
           <input type="submit" ID="Button2" Class="button"  value="确定导入"   />   

 </div> 
 
</form>


