<%@ 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.Xml" %>
<script runat="server" type="text/C#">
   
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
    
    int CourseId;
    int Id;
    int SpreadStatus;
    string SpreaRecommend;
    string SpreaPopular;
    string SpreaIstop;
    string SpreaHuandeng;
    string SpreaIs3g;
    string introduce;
    string Money;
    int EffectiveDay;
    bool status1 = true;//推荐
    bool status2 = true;//精彩
    bool status3 = true;//固顶
    bool status4 = true;//幻灯
    int recordcount, pagecount;
    int PageIndex = new BasicField().GetCurrPage;
    int pagesize = 10;
    string label2 = "0";
    DataRow drr = null;//编辑初始化
    private string GetVal(string fieldName)
    {
        if (drr != null)
        {
            return drr[fieldName].ToString();
        }
        else
        {
            return string.Empty;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        InitialConfig();//初始化配置文件信息
        
        if (SpreadStatus == 0)
        {
            Msg.Alert("对不起，推广已关闭！", BasicField.GetUserUrl("school"));
            return;
        }
        string _action = KSCMS.S("action");
        if (_action == "delete") 
        {
            delSt(KSCMS.S("ids"));//删除
        } 
        if (_action == "addorupdate")
        {
            if (Utils.StrToInt(KSCMS.S("id")) != 0)
            {
                initialEdit(Utils.StrToInt(KSCMS.S("id")));//编辑初始化
            }
            if (KSCMS.S("news") == "news")
            {
                addinfo();//新增以及修改操作
            }
        }
    }
    //删除
    private void delSt(string Id)
    {
        if (Id == null || Id == "0") return;
        Id = Utils.FilterIDs(Id);
        using (DataTable dt = DataFactory.GetDataTable("select ID from KS_EnterPriseSpread Where ID in(" + Id + ")"))
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int id = Utils.StrToInt(dr["ID"].ToString());
                    Hashtable ht = new Hashtable();
                    ht.Add("ID", id);
                    CommonData.Delete("KS_EnterPriseSpread", ht);
                }
            }
        }
        Msg.Alert("恭喜,删除成功!", KSCMS.GetComeUrl());
    }
    private void InitialConfig()
    {
        try
        {
            #region 读取XML
            XmlDocument xd = new XmlDocument();
            xd.Load(Server.MapPath("/config/course/Spread.config"));

            //获取根节点
            XmlNode root = xd.DocumentElement;

            //获取节点列表
            XmlNodeList items = root.ChildNodes;
            //遍历item项          
            foreach (XmlNode p in items)
            {
                if (p.Name == "SpreadStatus")
                {
                    SpreadStatus = Utils.StrToInt(p.InnerText);
                }
                else if (p.Name == "SpreaRecommend")//如果找到    推荐
                {
                    SpreaRecommend = p.InnerText;
                    if (p.Attributes["check"] != null)
                    {
                        status1 = Convert.ToBoolean(p.SelectSingleNode("@check").InnerText);
                    }
                }
                else if (p.Name == "SpreaPopular")//如果找到      精彩
                {
                    if (p.Attributes["check"] != null)
                    {
                        status2 = Convert.ToBoolean(p.SelectSingleNode("@check").InnerText);
                    }
                    SpreaPopular = p.InnerText;
                }
                else if (p.Name == "SpreaIstop")//如果找到     固顶  
                {
                    if (p.Attributes["check"] != null)
                    {
                        status3 = Convert.ToBoolean(p.SelectSingleNode("@check").InnerText);
                    }
                    SpreaIstop = p.InnerText;
                }  
                else if (p.Name == "SpreaHuandeng")//如果找到     幻灯
                {
                    if (p.Attributes["check"] != null)
                    {
                        status4 = Convert.ToBoolean(p.SelectSingleNode("@check").InnerText);
                    }
                    SpreaHuandeng = p.InnerText;
                } 
                else if (p.Name == "EffectiveDay")
                {
                    EffectiveDay = Utils.StrToInt(p.InnerText);
                    label2 = Utils.StrToInt(p.InnerText).ToString();
                }
                else if (p.Name == "introduce")//如果找到
                {
                    introduce = p.InnerText;
                }
            }

            #endregion
        }
        catch
        { }
    }
    //编辑初始化
    private void initialEdit(int ID)
    { 
        SqlParam[] param = new SqlParam[1];
        param[0] = new SqlParam("ID", ID);
        using (DataTable dt = CommonData.GetDataTable("[KS_EnterPriseSpread]", "*", param))
        {
            if (dt.Rows.Count > 0)
            {
                drr = dt.Rows[0];
            }
        }
    }
    //新增以及修改的操作
    private void addinfo() 
    {
        if (Utils.StrToInt(KSCMS.S("DropDownList1")) == 0)
        {
            Msg.Alert("推广课程不能为空" ,KSCMS.GetComeUrl());
            return;
        }
        if (Utils.StrToInt(KSCMS.S("RadioButtonList1")) == 0)
        {
            Msg.Alert("请选择推广类型", KSCMS.GetComeUrl());
            return;
        }
        if (Utils.StrToInt(KSCMS.S("Label2")) == 0)
        {
            Msg.Alert("展示天数不能为空！", KSCMS.GetComeUrl());
            return;
        } 
        Hashtable ht = new Hashtable();
        ht.Add("CourseID", Utils.StrToInt(KSCMS.S("DropDownList1")));
        ht.Add("Type", Utils.StrToInt(KSCMS.S("RadioButtonList1")));//推广类型
        ht.Add("Money", Utils.StrToDecimal(KSCMS.S("Label1")));//需要支付的钱
        ht.Add("Remarks", Utils.RemoveXss(KSCMS.S("Txtremark"))); //备注     
        ht.Add("EffectiveDay", Utils.StrToInt(KSCMS.S("Label2")));//展示天数
        ht.Add("TotalMoney", Utils.StrToDecimal(KSCMS.S("money")));//需要的总金额
        ht.Add("PhotoUrl", KSCMS.S("DefaultPic"));//推广封面信息
        if (Utils.StrToInt(KSCMS.S("id"))==0)
        {
            string _OrderID = "TG" + string.Format("{0:yyyyMMddHHmmssfffffff}", DateTime.Now);  //付款订单
            ht.Add("OrderID", _OrderID);
            ht.Add("IsPay", 0);
            ht.Add("Status", 0);
            ht.Add("adddate", DateTime.Now);  //添加时间
            ht.Add("inputer", __user.UserName);//推广者
            //插入表
            if (!DataFactory.Exists("KS_EnterPriseSpread", "enddate >=getdate() and CourseID=" + Utils.StrToInt(KSCMS.S("DropDownList1")) + " and Type =" + Utils.StrToInt(KSCMS.S("RadioButtonList1")) + " AND inputer ='" + __user.UserName + "'"))
            {
                CommonData.Insert("KS_EnterPriseSpread", ht);
                Msg.Alert("恭喜,添加成功!", BasicField.GetUserUrl("teacher/UserEpSpread"));
            }
            else
            {
                Msg.Alert("该课程的该推广类型已重复!", BasicField.GetUserUrl("teacher/UserEpSpread"));
            }
        }
        else
        {
            CommonData.Update("KS_EnterPriseSpread", ht, "where ID=" + Utils.StrToInt(KSCMS.S("id")));
            Msg.Alert("恭喜,修改成功!", BasicField.GetUserUrl("teacher/UserEpSpread"));
        }
    }
    protected string GetType(int num)
    {
        string _Type = string.Empty;

        switch (num)
        {
            case 1:
                _Type = "课程推荐";
                break;
            case 2:
                _Type = "课程精彩";
                break;
            case 3:
                _Type = "课程固顶";
                break;
            case 4:
                _Type = "课程幻灯";
                break;
        }
        return _Type;
    }

    protected string GetDate(DateTime time, int courseid, int _type, int ispay, int id)
    {
        string _time = string.Empty;
        if (ispay > 0)
        {
            string _typename = string.Empty;
            switch (_type)
            {
                case 1:
                    _typename = "Recommend";
                    break;
                case 2:
                    _typename = "popular";
                    break;
                case 3:
                    _typename = "istop";
                    break;
                case 4:
                    _typename = "huandeng";
                    break;
                case 5:
                    _typename = "is3g";
                    break;
            }

            if (time >= DateTime.Now)
            {
                _time = (time.Date - DateTime.Now.Date).Days + "天";
            }
            else
            {
                if (ispay == 1)
                {
                    DataFactory.ExecuteNonQuery(string.Format("Update  KS_Course Set {0}=0 where courseid={1}", _typename, courseid));
                    DataFactory.ExecuteNonQuery(string.Format("Update  KS_EnterPriseSpread Set ispay=2 where id={0}", id));
                }
                _time = "<font color=red>已过期</font>";
            }
        }
        else
        {
            _time = string.Empty;
        }

        return _time;
    }
    private void initial()
    {
        // this.DropDownList1.Items.Clear();
        string sql = "select top 200 courseid,name from KS_Course where username='" + __user.UserName + "' or schoolid="+__user.UserID;
        using (DataTable dt = DataFactory.GetDataTable(sql))
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    KSCMS.W("<option value='" + dr["courseid"] + "' " +( GetVal("courseid") == dr["courseid"].ToString() ? "selected='selected'" : "" )+ "  >" + dr["name"] + "</option>");
                }
            }
        }
    }
       
</script>
<script> 
   
    function getMoney(id) {
        var d = 0;
        if (id == '1')//推荐
        {
            d = '<%=SpreaRecommend %>';
        } else if (id == '2')//精彩
        {
            d = '<%=SpreaPopular %>';
        } else if (id == '3')//固顶
        {
            d = '<%=SpreaIstop %>';
        } else if (id == '4')//幻灯
        {
            d = '<%=SpreaHuandeng %>';
        }
        jQuery("#Label1").empty();
        jQuery("#Label1").val(d);
        countmoney();
         }
       </script>
	<%if(KSCMS.S("action")==""){ %>
 <div ID="ListPanel"  Width="100%">
      <div class="t_tybox">
			<div class="tytitle clearfix">
			<h4 class="fl lf">推广申请列表</h4><a href="<%=BasicField.GetUserUrl("teacher/UserEpSpread","action-addorupdate") %>" class="addbtn">添加申请</a>
			 <div class="top_c_sc mt10">
                
		   <form action="{$GetCurrUrl}" method="post">
                <span>课程名称：</span>
                <input type="text" name="TxtKeyWord" ID="TxtKeyWord" class="textbox" ></input>
                <input type="submit" ID="Button4"  value=" 搜索 " class="button"   />
            </form>
            </div>
			</div>
			<div class="clear blank10"></div>
           
                
              <table id="tablist" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="border" >
               <tr align="center" class="title">
				   <td height="25" width="60" align="center">序号</td>				
                   <td  width="6%" align="center">付款</td>
				   <td class="tag_left1" style="text-align:center;">课程名称</td>
				   <td width="10%">推广类型</td>
                   <td width="8%">每日费用</td>
                   <td width="8%">展示天数</td>
                   <td width="8%">总金额</td>
                    <td width="20%">订单号</td>        
                   <td width="10%">有效时间</td>
				   <td align="center" nowrap width="14%" >操作</td>
              </tr>
                  <% 
            string sqlParam = "KS_EnterPriseSpread a inner join KS_Course b on a.courseid = b.courseid  Where a.inputer='" +__user.UserName + "' ";
             
            if (!string.IsNullOrEmpty(KSCMS.S("TxtKeyWord")))
            {
                sqlParam += " and b.name like '%" + Utils.ChkSQL(KSCMS.S("TxtKeyWord")) + "%'";
            }
            //绑定及翻页
            using (DataTable dt = DataFactory.GetPage("a.*,b.name", sqlParam, "a.ID", "order by  a.AddDate desc", PageIndex, pagesize, out recordcount, out pagecount))
            {

                if (dt.Rows.Count > 0) {
                    int i = 0;
                    foreach (DataRow dr in dt.Rows) 
                    {
                        %> 
       <tr class="tdbg">
                 <td height="25" align="v">
                 <%=i+1 %> 
                 </td>                  
               <td  align="center">				
				<%= Utils.StrToInt(dr["IsPay"].ToString())>0?"<font color=green>已付</font>":"<font color=red>未付</font>" %>			
				</td>
                 <td class="tag_left lefticon">          
                    <a href='<%=Kesion.HtmlTags.BasicField.GetRewriteUrl("courseview", Utils.StrToInt(dr["courseid"].ToString()))%>' target="_blank" ><i class="iconfont">&#xe637;</i></a> <font class="fonths"><%= dr["name"]%></font>
                 </td>

				 <td align="center">
               	    <%= GetType(Utils.StrToInt(dr["type"]))%>        
                 </td>
           	     <td >
                	<font color="blue">￥<%= Kesion.APPCode.Public.ReturnShopPrice(Utils.StrToDecimal( dr["money"]))%></font></td >
           	     <td >
                	<font color="green"><%=dr["EffectiveDay"]%>天</font></td >
           	     <td >
                	<font color="blue">￥<%= Kesion.APPCode.Public.ReturnShopPrice(Utils.StrToDecimal( dr["TotalMoney"]))%></font></td >
                 <td >
               	     <%=dr["OrderID"] %>         
                 </td >        
           	     <td align="center">
               	     <%= GetDate(Utils.StrToDateTime(dr["EndDate"].ToString()),Utils.StrToInt(dr["courseid"]),Utils.StrToInt(dr["type"]),Utils.StrToInt(dr["IsPay"]),Utils.StrToInt(dr["id"]))%> 
                 </td>            
			<td>    
                <div class="gl_btn">
                    <span class="span1" style="width:33.3%"><a style='display:<%= Utils.StrToInt(dr["IsPay"].ToString()) >0  ? "none":"" %>' href="<%=BasicField.GetUserUrl("teacher/User_Pay","from-Spread,orderId-"+dr["OrderID"])%>"><i class="iconfont">&#xe60f;</i>支付</a> </span>
                     <span class="span4" style="width:33.3%"><a href="<%=BasicField.GetUserUrl("teacher/UserEpSpread","action-addorupdate,id-"+dr["id"]) %>"  style='<%= Utils.StrToInt( dr["IsPay"].ToString()) >0 ? "display:none":"" %>'  ><i class="iconfont">&#xe61d;</i>编辑</a></span>
                 	<span class="span5" style="width:33.3%"><a href="<%=BasicField.GetUserUrl("teacher/UserEpSpread","action-delete,ids-"+dr["id"]) %>"   style='<%= Utils.StrToInt( dr["IsPay"].ToString()) >0 ? "display:none":"" %>'   ><i class="iconfont">&#xe731;</i>删除</a></span>
            	 </div>
           </td>
       </TR>
                  <%
                        i++;
                    }
                }
                else {
                    KSCMS.W(@"<tr class=""tdbg"" >
                                <td class=""Ctd"" style=""text-align:center"" colspan=""10"">
                                  <div class=""empty"">暂未添加任何推广申请</div>
                                </td>
                               </tr> ");
                }
            }                      
                       %>

               </table>

    
      	<div class="fy_box" >
                      <%
            #region 分页
            string PageStr = "[KS:PageStr1]";
            BasicField.ReplaceFilterPage(ref PageStr, PageIndex, pagesize, pagecount, recordcount);
            KSCMS.W(PageStr);
            #endregion
         %>
      	</div>
   <div class="clearfix"></div>
    </div>
</div>
    <div ID="Panel1"  Width="100%">
                <div style="padding: 10px 0px">
                    <script type="text/javascript">
                        showtips('<span>操作说明：<br /></span><span class="tips_cor" style="display:block;margin-top:5px;">如果参加推广的话，您的课程就会在首页推广</span>');
                    </script>
                </div> 
            </div>
	<%} if(KSCMS.S("action")=="addorupdate"){ %>
<script>
    $(document).ready(function () {
        getMoney('<%=GetVal("type")%>');
        countmoney();
    });
    //计算总金额
    function countmoney()
    {
        var money = parseFloat(jQuery("#Label1").val());//获取每天的金额
        var day = parseInt(jQuery("#Label2").val());//获取天数
        if (day == '0'||day=="")
        {
            jQuery("#Label2").val('1')
            day = 1;
        }
        var totalmoney = parseFloat(parseFloat(money) * parseInt(day));//计算出来的总金额
        jQuery("#money").val(totalmoney);//后台用来获取的金额总数
        jQuery("#showmoney").html(totalmoney);//显示金额
    }
</script>
<div ID="AddPanel"  Width="100%">
	<div class="t_tybox">	
        <form action="{$GetCurrUrl}" method="post"> 
            <input type="hidden" name="news" value="news" />
    	<div class="tytitle"><h4>推广申请</h4></div>
         <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" class="border"> 
         <tr>
             <td class="lefttd" height="30" align="right" width="120">
                推广课程：</td>
            <td class="tag_left">
                <select name="DropDownList1" ID="DropDownList1" >
                    <%initial(); %>        
                </select>
            </td>
        </tr> 
        <tr>
            <td align="right" class="lefttd" height="30" >推广类型：</td>
            <td class="tag_left">
                <%if(status1==true){ %>
                 <input type="radio" class="radiobtn" name="RadioButtonList1" Value="1"  <%=GetVal("type")=="1"?"checked":"" %>  onclick="getMoney(this.value)" >推荐</input> 
                <%} if(status2==true){ %>
                <input type="radio" class="radiobtn" name="RadioButtonList1"  Value="2"  <%=GetVal("type")=="2"?"checked":"" %> onclick="getMoney(this.value)" >精彩</input> 
                <%} if(status3==true){ %>
                 <input type="radio" class="radiobtn" name="RadioButtonList1"  Value="3"  <%=GetVal("type")=="3"?"checked":"" %> onclick="getMoney(this.value)" >固顶</input>           
                <%} if(status4==true){ %>
                 <input type="radio" class="radiobtn" name="RadioButtonList1"  Value="4" <%=GetVal("type")=="4"?"checked":"" %> onclick="getMoney(this.value)" >幻灯</input>             
                <%} %>
            </td>
        </tr>
        <tr>
            <td align="right" class="lefttd" height="30">
                推广类型费用：</td>
            <td class="tag_left">
                <input readonly="readonly" type="text" class="textbox"   ID="Label1" name="Label1" value="<%=Kesion.APPCode.Public.ReturnShopPrice(Utils.StrToDecimal(GetVal("money"))) %>" ForeColor="Red"  style=" font-size:30px;color:#f14e29;"></input> 元/天
            </td>
        </tr>
          <tr>
            <td align="right" class="lefttd" height="30">
                展示天数：</td>
            <td class="tag_left">
                <input  type="text" class="textbox"  oninput="countmoney()" onkeyup="CheckNumber(this,'展示天数')" name="Label2" value="<%=GetVal("EffectiveDay")==""?label2:GetVal("EffectiveDay") %>" id="Label2" ForeColor="Red"  style=" font-size:30px;color:#f14e29;" ></input> 天
            </td>
        </tr>  
            <tr>
                <td align="right" class="lefttd" height="30">需要支付金额：</td>
                <td class="tag_left"><input type="hidden" name="money" id="money" value="" /><span id="showmoney" style="color:red;font-size:20px;">0</span>元</td>
            </tr>
             <tr>
                <td align="right" class="lefttd" height="30">推广封面：</td>
                 <td class="tag_left">              
                <input id="DefaultPic" name="DefaultPic" Class="textbox" style="float:left" type="text" value="<%=GetVal("PhotoUrl") %>" >
                &nbsp;  &nbsp;<input type="button" class="ty_button" onclick="SelectUserFiles('DefaultPic', 0);" value="选择图片" />
                <div class="clear blank10"></div>
     	        <%=Kesion.APPCode.UploadAPI.EchoUpload("courseUserPic","DefaultPic") %> 
                </td>
             </tr>
        <tr>
            <td align="right" class="lefttd" height="30">
           推广理由：</td>
            <td class="tag_left" >
            <textarea name="Txtremark" ID="Txtremark" class="textbox" TextMode="MultiLine" Rows="9"  Width="600" style=" padding:10px;height:100px"><%=GetVal("Remarks") %></textarea>
           </td>
        </tr>
      </table>
         <div class="cz_btn nofloat" style="padding:20px 0px 0px 162px">
                <span><input type="submit" ID="Button2" OnClick="return(CheckForm())" class="button"  value="确定保存"  /></span>
                <span><input type="button" class="button" onclick="window.history.go(-1);"value=" 返 回 "></span>
          </div>  
       </form>
   </div>
   
</div>

	<%} %>
