<%@ 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="Kesion.NET.WebSite.Admin.Exam" %>
<script runat="server" type="text/C#">
	dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
	private static dynamic __info = new System.Dynamic.ExpandoObject();   //初始化当前页信息
    private string righttmtype = string.Empty;
    
    protected void Page_Load(object sender, EventArgs e)
    {

        __info.ClassID = KSCMS.S("DrpClassID");
        if (KSCMS.S("action") == "save")
        {
            save();
        }
    }

    protected void save()
    {
        righttmtype = Utils.FilterIDs(KSCMS.S("righttmtype"));
        if (string.IsNullOrEmpty(righttmtype))
        {
            JS.Alert("出错啦!");
        }
        var righttmtypearr = Utils.SplitString(righttmtype, ",");
        var totalfs = 0;
        HttpCookie userck = new HttpCookie("sjrnd" + KSCMS.SiteSN);
        if (Kesion.Config.BaseConfigManage.AllowSubDomain.ToLower().Equals("true")) //启用二级域名
        {
            userck.Domain = Kesion.Config.BaseConfigManage.RootDomain;
        }
        userck.Values["righttmtype"] = righttmtype;
     
        foreach (string s in righttmtypearr)
        {
            var tmType = s;
            if (!string.IsNullOrEmpty(Utils.FilterIDs(KSCMS.S("tmids" + tmType))))
            {

                //======传递参数到添加试卷页面=============================
                userck.Values["exam_tmids" + tmType] = Utils.FilterIDs(KSCMS.S("tmids" + tmType));
                userck.Values["exam_num" + tmType] = Utils.SplitString(Utils.FilterIDs(KSCMS.S("tmids" + tmType)), ",").Length.ToString();
                userck.Values["exam_title" + tmType] = KSCMS.S("title" + tmType);
                userck.Values["exam_fs" + tmType] = KSCMS.S("fs" + tmType);
                userck.Values["exam_koufs" + tmType] = KSCMS.S("koufs" + tmType);
                userck.Values["exam_iskoufs" + tmType] = KSCMS.S("iskoufs" + tmType);
                userck.Values["exam_orderid" + tmType] = KSCMS.S("orderid" + tmType);
                userck.Values["exam_tmtype" + tmType] = KSCMS.S("tmtype" + tmType);
                totalfs = totalfs + Utils.StrToInt(KSCMS.S("fs" + tmType)) * (Utils.SplitString(Utils.FilterIDs(KSCMS.S("tmids" + tmType)), ",").Length);

                //===================================================

            }

        }
        userck.Values["exam_totalfs"] = totalfs.ToString();
        HttpContext.Current.Response.AppendCookie(userck);
        
     KSCMS.Redirect(BasicField.GetUserUrl("sj/tcsjlist","do-add,dtfs-3"));
     // HttpContext.Current.Server.Transfer(BasicField.GetUserUrl("sj/tcsjlist", "do-add,dtfs-3"));

    }
    
    
    protected string Step2()
    {       


        var tmids = KSCMS.S("ids");
        tmids = Utils.FilterIDs(tmids);
        if (string.IsNullOrEmpty(tmids)) tmids = "0";
        var m = 0;
        var n = 0;
        StringBuilder sb = new StringBuilder();
        sb.Append(@"<table width='98%' style='margin-top:10px' border='0' align='center'  cellspacing='1' class='CTable'>");
        using (DataTable dttype = DataFactory.GetDataTable("SELECT Distinct TmType From KS_SJTK Where TMID in(" + tmids + ")"))
        {
            if (dttype.Rows.Count > 0)
            {
                foreach (DataRow drtype in dttype.Rows)
                {
                    int tmType = Utils.StrToInt(drtype["tmtype"].ToString());
                    var sqlStr = "SELECT TOP 300 * From KS_SJTK Where TMID IN(" + tmids + ") AND TmType=" + tmType;
                    using (DataTable dt = DataFactory.GetDataTable(sqlStr))
                    {
                        if (dt.Rows.Count > 0)
                        {
                            int k = 0;
                            foreach (DataRow dr in dt.Rows)
                            {
                                tmType = Utils.StrToInt(dr["tmType"].ToString());
                                string tmTypeTag = tmType.ToString();
                                if (tmType == 6 || tmType == 7 || k == 0)
                                {
                                    if (tmType == 6 || tmType == 7)
                                    {
                                        tmTypeTag = tmType + "" + dr["tmid"].ToString();
                                    }
                                    righttmtype += "," + tmTypeTag;

                                    var tstr = Kesion.Exam.Function.TMTypeArr[tmType - 1];
                                    m++;
                                    sb.AppendFormat(@"<tr class='CTitle {0}' id='dd{0}'><td height='25' style='text-align:left'>
				                 <span style='float:right;padding-right:5px;'><a href=""javascript:deldt({0});"" style=""color:green"">删除大题</a></span><strong>
				                 第<input type='text' name='orderid{0}' value='{1}' class='textbox' style='width:40px;text-align:center'/>大题：", tmTypeTag, m);
                                    sb.Append(tstr);
                                    sb.AppendFormat(@"</strong>&nbsp;<span class='tips'>每小题分数：<input type='text' class='textbox' size='4' style='text-align:center' name='fs{0}' value='{1}'/>分</span>
                                       </td></tr>", tmTypeTag, dr["TmFs"].ToString());
                                    if (tmType == 3)
                                    {
                                        sb.AppendFormat(@"<tr class='CTitle {0}'><td height='25' style='text-align:left'>少选，每个选项得:<input type='text' class='textbox' size='2' style='text-align:center' name='koufs{0}' value='0'/>分</td></tr>", tmTypeTag);
                                    }
                                    else
                                        if (tmType == 4)
                                        {
                                            sb.AppendFormat(@"<tr class='CTitle {0}' ><td height='25' style='text-align:left'>答错扣:<input type='text' class='textbox' size='2' style='text-align:center' name='koufs{0}' value='0'/>分</td></tr>", tmTypeTag);
                                            sb.AppendFormat(@"<tr class='CTitle {0}' ><td height='25' style='text-align:left'>不答是否扣分:<input type='radio' name='iskoufs{0}' value='0' checked/>否<input type='radio' name='iskoufs{0}' value='1'/>是</td></tr>", tmTypeTag);
                                        }
                                    if (tmType == 6 || tmType == 7)
                                    {
                                        sb.AppendFormat("<input type='hidden' name='num{0}' value='1'/>", tmTypeTag);
                                    }
                                    else
                                    {
                                        sb.AppendFormat("<input type='hidden' name='num{0}' value='{1}'/>", tmTypeTag, dt.Rows.Count);
                                    }
                                    sb.AppendFormat("<input type='hidden' name='title{0}' value='{1}'/>", tmTypeTag, tstr);
                                    sb.AppendFormat("<input type='hidden' name='tmtype{0}' value='{1}'/>", tmTypeTag, tmType);
                                }

                                sb.AppendFormat("<tr class='tdbg {0}' id='xt{1}'><td class='Ctd'>", tmTypeTag, dr["tmid"].ToString());

                                n = n + 1;
                                sb.AppendFormat(@"<div><span style='float:right;padding-right:5px;'><a href=""javascript:del({0});"" style=""color:red"">删除</a></span><input type='hidden' name='tmids{1}' value='{0}'><div style='margin-bottom:5px'><strong>第<span style='color:red'> {2}</span> 题：</strong> ", dr["tmid"].ToString(), tmTypeTag, n);
                                sb.AppendFormat(Utils.ReplaceString(dr["title"].ToString().Replace("{", @"{{").Replace("}", "}}"), "{#answer}", "<input type='text' name='a" + n + "' class='anstext'/>", true));
                                sb.AppendFormat("</div><div style='background:url(/images/line.gif) repeat-x;height:2px;overflow:hidden'></div>");
                                sb.Append(Utils.replaceBR(dr["tmnr"].ToString()).Replace("{", @"{{").Replace("}", "}}").Replace("{#answer}", "<input type='text' name='a" + n + "' class='anstext'/>"));
                                sb.Append("</div>");

                                //  if (Utils.StrToInt(dr["tmType"].ToString()) == 6 || Utils.StrToInt(dr["tmType"].ToString()) == 7 || k == 0)
                                {
                                    sb.Append("</td></tr>");
                                }


                                k++;

                            }

                        }
                    }
                }
            }
            else
            {
               // JS.Alert("没有找到试题", "KS.SJXTZJ.AspX");
            }
        }

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

    }
    
    public string GetBusiness(string nametype)
    {
        #region 经营范围


        DataTable dt = MyCache.GetCacheSJCategoryTable();       //考试分类         

        StringBuilder sb = new StringBuilder();
        if (!string.IsNullOrEmpty(nametype))
        {
            DataView dv = dt.DefaultView;
            nametype = Utils.FilterIDs(nametype);
            dv.RowFilter = " classid in(" + nametype + ")";
            //  dv.Sort = "root,orderid";
            //  dt = dv.ToTable();
        }
        int depth = 1;
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                string str = string.Empty;
                depth = Utils.StrToInt(dr["depth"].ToString());
                if (depth == 2)
                {
                    str = "　├ ";
                }
                if (depth == 3)
                {
                    str = "　   ├ ";
                }
                if (depth == 4)
                {
                    str = "　   　     ├ ";
                }
                nametype = "," + nametype + ",";
                if (nametype.IndexOf("," + dr["classid"].ToString() + ",") != -1)
                {
                    sb.AppendFormat(@"<option value ={0} selected = 'selected' >{1}</option>", dr["classid"].ToString(), str + dr["classname"].ToString());

                }
                else
                {
                    sb.AppendFormat(@"<option value ='{0}' >{1}</option>", dr["classid"].ToString(), str + dr["classname"].ToString());
                }
            }

        }
        dt.Dispose();
        return sb.ToString();
        #endregion
    }
</script>

   <div class="t_tybox">
       <% if ( KSCMS.S("do")==""){ %>
       <div class="ty_title">手工组卷</div>
           <table width="100%"border="0" cellpadding="0" cellspacing="0" class="border"> 
                <tr>

             <td align="right" class="lefttd" height="30">试卷分类：</td>
            <td class="tag_left">
               
                <select name="DrpClassID" id="DrpClassID">
				<%
        string selceted = "," + __info.ClassID + ",";
        string str = GetBusiness(selceted);

       KSCMS.W(str);
				 %>
				</select>

            </td>

        </tr>

       <tr>
                <td align="right" class="lefttd" height="30">
                    <strong>题目难易：</strong></td>
                <td class="righttd">
                       <select name="Difficulty" id="Difficulty" >
                           <option value="-1" >无</option>
		<option value="0" >易</option>
    	<option value="1" >中</option>
	<option value="2" >难</option>
	
	</select>

                </td>
          </tr>
         <tr>
                <td align="right" class="lefttd" height="30" >
                    <strong>题目类型：</strong></td>
                <td class="righttd">
                    <% 
                   var strr = string.Empty;
             int    i = 1;
            foreach (string s in Kesion.Exam.Function.TMTypeArr)
            {
                strr += "<label><input type='checkbox' value='" + i + "' name='TmType'/>" + s + "</label>";
                i++;
            }
            KSCMS.W(strr);
            %>
                </td>
            </tr>
        <tr>
                <td align="right" class="lefttd" height="30" ></td>
                <td  class="righttd" height="30"  style="text-align:left">
                    <input type="button"  onclick='return (show(1))' value="搜索试题" class="button"/>
                    <input type="button"  onclick="jQuery('#searchform').toggle('fast')" value="显示/隐藏搜索框" class="button"/>


                     <span style="float:right">
                        <input type="button" class="button" value="全选" onclick="CheckInputBox(1)"/>
                        <input type="button" class="button" value="反选" onclick="CheckInputBox(2)"/>
                        <input type="button" class="button" value="不选" onclick="CheckInputBox(0)"/>
                      </span>
                </td>
            </tr> 
     

               </table>
          <div id="showresult"></div>
          <script>
              var ClassID = 0;
              var key = '';
              var tmtype = '0';
              var TmZDYType = '0';
              var Difficulty = '';
              var KnowledgeId = '0';

              var selids = '';
              function selectst(obj) {
                  var v = obj.value;
                  if (obj.checked) {
                      selids += ',' + v;
                  } else {
                      selids = selids.replace("," + v, '');
                  }
                  seltips();
              }
              function seltips() {
                  var num = (selids.split(",").length - 1);
                  if (num > 0) {
                      jQuery.dialog.tips('<div style="font-size:14px;padding-left:10px">已选择了 <font color=red>' + num + '</font> 题!</div><br/><input type="button" onclick="location.href=\'<%=BasicField.GetUserUrl("sj/tcsjrnd","do-add,dtfs-3,ids-")%>'+selids.substr(1, selids.length) + '\';" value="完成选题，创建试卷" class="button"/>', 300000000000, 'success.gif', function () { });
                  } else {
                      jQuery.dialog.tips('没有选择试题!', 1, 'success.gif', function () { });
                  }
              }

              function show(p) {
                  tmtype = '0';
                  jQuery("input[name=TmType]:checked").each(function (n) {
                      if (n == 0) {
                          tmtype = jQuery(this).val();
                      } else {
                          tmtype += ',' + jQuery(this).val();
                      }
                  });
                  ClassID = jQuery("#DrpClassID").val();
                  jQuery("#showresult").html('loading...');
                  jQuery.get("/plus/exam/tcsjajax.ashx", { action: "getsearchsjtk", p: p, Difficulty: Difficulty, tmtype: tmtype, classid: ClassID }, function (v) {
                      jQuery('#showresult').html(unescape(v));
                      if (selids != '') {
                          var ss = "," + selids;
                          jQuery("input[name=selt]").each(function () {
                              if (ss.indexOf("," + jQuery(this).val()) != -1) {
                                  jQuery(this)[0].checked = true;
                              }
                          });
                      }
                  });
              };

              function CheckInputBox(v) {
                  if (v == 1) {
                      $("#showresult").find("input[type='checkbox']").attr("checked", true);
                      $("#showresult").find("input[type='checkbox']").each(function () {
                          selids += ',' + $(this).val();
                      });
                  } else if (v == 2) {
                      $("#showresult").find("input[type='checkbox']").each(function () {
                          if ($(this).prop("checked") == true) {
                              $(this).attr("checked", false);
                              selids = selids.replace("," + $(this).val(), '');
                          } else {
                              $(this).attr("checked", true);
                              selids += ',' + $(this).val();
                          }
                      });
                  } else {
                      $("#showresult").find("input[type='checkbox']").each(function () {
                          $(this).attr("checked", false);
                          selids = selids.replace("," + $(this).val(), '');
                      });
                  }
                  seltips();
              }

          </script>
       <%}else{ %>
         <form name="myform" action="<%=BasicField.GetUserUrl("SJ/TcSjrnd") %>" method="post" id="Form1" >
	  <input type="hidden" name="action" value="save" />
       			<div style='padding:10px;text-align:center'>
			<input type='button' class='button' value=' 返回重新选题组卷 ' onclick='history.back(-1);'/>
	       <input type='submit' class='button'  value=' 下一步：填写试卷信息并写入数据库 ' />
               
                  
</div>
       <script type="text/javascript">
           function del(id) {
               if (confirm('确定删除该小题吗？')) {
                   jQuery("#xt" + id).remove();
               }
           }
           function deldt(id) {
               if (confirm('确定删除整个大题吗?')) {
                   jQuery("." + id).remove();
                   /*
                   var righttmtype = ',' + jQuery("#righttmtype").val();
                   righttmtype = righttmtype.replace(',' + id, '').substr(1, righttmtype.length);
                   jQuery("#righttmtype").val(righttmtype);
       
                   jQuery("#dt" + id).empty().hide();
                   jQuery("#dd" + id).empty().hide();
                   */
               }
           }
           function check() {
               if (jQuery("#righttmtype").val() == '') {
                   if (confirm('没有试题了，现在重新随机组卷吗?')) {
                       location.reload();
                   } else {
                       return false;
                   }
               }
               return true;
           }
			</script>
       <%=Step2() %>
<input type="hidden" name="righttmtype" value="<%=righttmtype %>">
</form>
<%} %>
    </div>
