<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="salestrategy_config_setdonategiftrule.aspx.cs" Inherits="VA.Modules.JDingMember.sale.salestrategy_config_setdonategiftrule" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <!--#include virtual="/include/css/edit.aspx"-->
    <!--#include virtual="/include/js/edit.aspx"-->     
    <script type="text/javascript">

        function save(flag) {

            var enableRule = $("input[name=rbnEnableRule]:checked").val();
            if (enableRule == "1") { //启用规则
                if (!formEditListTable_checkTableData()) {
                    return;
                }
            }

            if (flag == 1) {
                update();
            }
        }

        function update() {
            $.ajax({
                type: "POST",
                url: "salestrategy_config_setdonategiftrule.aspx?act=update",
                dataType: "html",
                data: $("form").eq(0).serialize(),
                success: function (data, textStatus) {
                    if (data == "ok") {
                        showActResult("修改成功！", true);
                    } else if (data.indexOf("01|") != -1) {
                        showActResult(data.substring(3), false);
                    }
                    else {
                        showActResult("修改失败：" + data, false);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    showActResult("修改失败！textStatus :" + textStatus, false);
                }
            });
        }

        //显示操作结果；
        function showActResult(sMsg, actResult) {
            if (actResult) {
                JTongAlert('操作结果', sMsg, 'info');
            } else {
                JTongAlert('操作结果', sMsg, 'error');
            }

            if (actResult) {
                try {
                    window.parent.reload();
                } catch (e) { }
            }
        }

        function resetPage() {
            $("#txtCharges").val("");
            $("#txtItemName").val("");
            $("#txtItemName_hiddenValue").val("");
            formEditListTable_clearRows();
        }

        function JTongSmartDropDownList_BeforeTakeValue(JTongSmartDropDownList_inputObjID, selectedRow) {
            if (selectedRow != null) {

                if (JTongSmartDropDownList_inputObjID == "txtItemName") {
                    
                    var chargeAmount = $("#txtCharges").val();
                    if (chargeAmount == "") {
                        alert("请先填写充值金额！");
                        $("#txtCharges").focus();
                        return false;
                    }

                    /*检测是否存在给定的金额*/
                    var $srcTable = $("#srcTable");
                    var srcTableID = $srcTable.attr("id");
                   
                    var result = true;
                    $srcTable.find("input[name=txtChargeAmount]").each(function () {
                        var sChargeAmount = $(this).val();
                        if (chargeAmount == sChargeAmount) {
                            JTongAlert("提示", "已经存在充值金额为" + chargeAmount + "的规则！", "warning");
                            result = false;
                            return;
                        }
                    });

                    if (!result) {
                        return false;
                    }
                }
            }

            //返回true，继续取值；返回false，取消取值；
            return true;
        }

        function JTongSmartDropDownList_AfterTakeValue(JTongSmartDropDownList_inputObjID, selectedRow) {
            if (selectedRow != null) {

                if (JTongSmartDropDownList_inputObjID == "txtItemName") {

                    var itemCode = selectedRow.cells[0].innerHTML;
                    var itemName = selectedRow.cells[1].innerHTML;
                    var unit = selectedRow.cells[2].innerHTML;
                    var chargeAmount = $("#txtCharges").val();
                    if (chargeAmount == ""){
                        JTongAlert("提示", "充值金额不能为空！", "warning");
                        $("#txtCharges").focus();
                        return;
                    }
                    var quantity = 1;

                    formEditListTable_addRow(chargeAmount, itemCode, itemName, unit, quantity);

                    $("#txtCharges").val("");
                    $("#txtItemName").val("");
                    $("#txtItemName_hiddenValue").val("");
                    $("#txtCharges").focus();
                }
            }
        }        

        $(function () {
            $("#txtCharges").focus();          
        });
    </script>

    <script type="text/javascript">

        var formEditListTable_RowCounter = 0;

        function formEditListTable_addRow(chargeAmount, itemCode, itemName, unit, quantity) {

            formEditListTable_RowCounter++;
            
            var $srcTable = $("#srcTable");
            var srcTableID = $srcTable.attr("id");

            var rowHtml = '';
            var $row = null;
            var rowCnt = $srcTable[0].rows.length;
            var rowID = formEditListTable_RowCounter;

            itemName = itemName.replace(/'/g, "‘");
            unit = unit.replace(/'/g, "‘");

            var price = 0.0;
            var amount = price * quantity;

            rowHtml += '<tr id="tr_' + rowID + '">';
            rowHtml += '<td style="text-align:center;" class="tdRowNo"></td>';

            rowHtml += '<td><input type="text" name="txtChargeAmount" value="' + chargeAmount + '" id="txtChargeAmount_' + rowID + '" /></td>';

            rowHtml += '<td style="text-align:left;padding-left:5px;">';
            rowHtml += '<span>' + itemName + '</span>';
            rowHtml += '<input type="hidden" name="hfItemName" value="' + itemName + '" />';
            rowHtml += '<input type="hidden" name="hfItemCode" value="' + itemCode + '" />';
            rowHtml += '</td>';

            rowHtml += '<td style="text-align:center;">';
            rowHtml += '<span>' + unit + '</span>';
            rowHtml += '<input type="hidden" name="hfUnit" value="' + unit + '" />';
            rowHtml += '</td>';

            rowHtml += '<td><input type="text" name="txtQuantity" value="' + quantity + '" id="txtQuantity_' + rowID + '" onkeyup="formEditListTable_caculateAmount(' + rowID + ')" /></td>';
        
            /*
            rowHtml += '<td><input type="text" name="txtPrice" value="' + price + '" id="txtPrice_' + rowID + '" onkeyup="formEditListTable_caculateAmount(' + rowID + ')" /></td>';            

            rowHtml += '<td style="text-align:right;padding-right:5px;">';
            rowHtml += '<span style="font-weight:bold;" id="spanAmount_' + rowID + '">' + amount + '</span>';
            rowHtml += '<input type="hidden" name="hfAmount" value="' + amount + '" id="hfAmount_' + rowID + '" />';
            rowHtml += '</td>';
            */

            rowHtml += '<td style="text-align:center;"><a href="javascript:formEditListTable_removeRow(' + rowID + ')">删除</a></td>';
            rowHtml += '</tr>';

            $row = $(rowHtml);
            $srcTable.append($row);

            formEditListTable_setRowNo();
            formEditListTable_setTotalAmount();
            formEditListTable_hideTbNoRecord();
        }

        function formEditListTable_removeRow(rowID) {

            var $srcTable = $("#srcTable");
            $srcTable.find("#tr_" + rowID).remove();

            var dataRowCount = $srcTable.find("input[name=txtChargeAmount]").length;
            if (dataRowCount == 0) { //如果已无数据行，则重置计数器；
                formEditListTable_RowCounter = 0;
                formEditListTable_showTbNoRecord();
            }

            formEditListTable_setRowNo();
            formEditListTable_setTotalAmount();
        }

        function formEditListTable_clearRows() {
            var $srcTable = $("#srcTable");
            $srcTable.find("tr[id]").remove();

            formEditListTable_setTotalAmount();
            formEditListTable_showTbNoRecord();
        }

        function formEditListTable_showTbNoRecord() {
            $("#tbNoRecord").show();
        }
        function formEditListTable_hideTbNoRecord() {
            $("#tbNoRecord").hide();
        }

        function formEditListTable_setRowNo() {
            var $srcTable = $("#srcTable");
            var $tdNos = $srcTable.find("td.tdRowNo");
            $.each($tdNos, function (n, value) {
                $(value).html(n + 1);
            });
        }

        function formEditListTable_setTotalAmount() {
            return;
            var $srcTable = $("#srcTable");
            $srcTable.find("#trTotal").remove();

            var totalRowHtml = '';
            var total = 0.00;
            var $hfAmountList = $srcTable.find("input[name=hfAmount]");

            $hfAmountList.each(function () {
                total += parseFloat($(this).val());
            });

            if ($hfAmountList.length > 0) {  //如果有数据行，则添加合计行
                totalRowHtml += '<tr id="trTotal">';

                totalRowHtml += '<td colspan="6" style="text-align:right;padding-right:5px;font-weight:bold;">合计</td>';

                totalRowHtml += '<td style="text-align:right;padding-right:5px;">';
                totalRowHtml += '<span style="font-weight:bold;" id="spanTotalAmount">' + total.toFixed(2).toString() + '</span>';
                totalRowHtml += '<input type="hidden" name="hfTotalAmount" value="' + total.toFixed(2).toString() + '" id="hfTotalAmount" />';
                totalRowHtml += '</td>';

                totalRowHtml += '<td></td>';

                totalRowHtml += '</tr>';

                $srcTable.append($(totalRowHtml));
            }
        }

        function formEditListTable_caculateAmount(rowID) {
            return;
            var $txtQuantity = $("#txtQuantity_" + rowID);
            var $txtPrice = $("#txtPrice_" + rowID);
            var sQuantity = $txtQuantity.val();
            var sPrice = $txtPrice.val();
            var amount = 0.00;

            if (sQuantity == "") {
                sQuantity = "0";
            }
            if (sPrice == "") {
                sPrice = "0";
            }

            ////清除非数字字符；(会影响光标键输入，故不再使用，更改为判断如果为非数字，直接清空)
            //clearNoNum($txtQuantity[0]);
            //clearNoNum($txtPrice[0]);

            if (isNaN(sQuantity)) {
                alert("数量为无效数字！");
                $txtQuantity.val("");
                $txtQuantity.focus();
                return;
            }
            if (isNaN(sPrice)) {
                alert("单价为无效数字.");
                $txtPrice.val("");
                $txtPrice.focus();
                return;
            }

            if (parseFloat(sQuantity) > 100000) {  //限制数量不能超过100000
                alert("数量不能超过100000.");
                $txtQuantity.val("");
                $txtQuantity.focus();
                return;
            }
            if (parseFloat(sPrice) > 100000) {  //单价不能超过100000
                alert("单价不能超过100000.");
                $txtPrice.val("");
                $txtPrice.focus();
                return;
            }

            if ($txtQuantity.hasClass("error")) {
                $txtQuantity.removeClass("error");
            }
            if ($txtPrice.hasClass("error")) {
                $txtPrice.removeClass("error");
            }

            amount = parseFloat(sQuantity) * parseFloat(sPrice);

            $("#hfAmount_" + rowID).val(amount.toFixed(2).toString());
            $("#spanAmount_" + rowID).html(amount.toFixed(2).toString());

            formEditListTable_setTotalAmount();
        }

        function formEditListTable_checkTableData() {

            var result = true;

            var dataRowCount = 0;
            var $srcTable = $("#srcTable");

            $srcTable.find("input[name=txtChargeAmount]").each(function () {
                dataRowCount++;
                var sChargeAmount = $(this).val();
                if ($.trim(sChargeAmount) == "" || $.trim(sChargeAmount) == "0") {
                    alert("充值金额不能为空或0！");
                    $(this).focus();
                    $(this).addClass("error");
                    result = false;
                    return;
                }
            });

            $srcTable.find("input[name=txtQuantity]").each(function () {
                dataRowCount++;
                var sQuantity = $(this).val();
                if ($.trim(sQuantity) == "" || $.trim(sQuantity) == "0") {
                    alert("数量不能为空或0！");
                    $(this).focus();
                    $(this).addClass("error");
                    result = false;
                    return;
                }
            });

            /*
            $srcTable.find("input[name=txtPrice]").each(function () {
                var sPrice = $(this).val();
                if ($.trim(sPrice) == "" || $.trim(sPrice) == "0") {
                    alert("单价不能为空或0！");
                    $(this).focus();
                    $(this).addClass("error");
                    result = false;
                    return;
                }
            });
            */

            if (dataRowCount == 0) {
                alert("规则条目不能为空！");
                result = false;
            }

            return result;
        }

        function formEditListTable_clearNoNum(obj) {
            obj.value = obj.value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符  
            obj.value = obj.value.replace(/^\./g, "");  //验证第一个字符是数字而不是. 
            obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的.   
            obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        }

    </script>

</head>
<body>
<form id="Form1" method="post" runat="server">

<div class="editPageWrapper" style="width:700px;">

<div class="centerFormTitle">
   <h1><asp:Label ID="lblFormTitle" runat="server">设置营销规则</asp:Label></h1>
</div>

<table cellspacing="0" cellpadding="3" class="editTable">
<tr id="trEditResult" runat="server" visible="false">
<td colspan="2" style="text-align:center;">
    <div class="editResult">
    <asp:Literal id="litEditResult" runat="server" />
    </div>
</td>
</tr>
<tr>
<td class="th">策略类型：</td>
<td>
    <asp:Label ID="lblBizType" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="th">策略名称：</td>
<td>              
    <asp:Label ID="lblStrategyName" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="th">启用规则：</td>
<td>              
    <asp:RadioButtonList ID="rbnEnableRule" runat="server"
         RepeatDirection="Horizontal"
         RepeatLayout="Flow">
        <asp:ListItem Value="1" Selected="True">启用</asp:ListItem>
        <asp:ListItem Value="0">不启用</asp:ListItem>
    </asp:RadioButtonList>                 
</td>
</tr>
</table>

<table cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td class="th" style="font-weight:bold;text-align:left;">礼品赠送规则</td>
</tr>
</table>
<table cellspacing="0" class="formEditListTable" id="srcTable" style="width:700px;margin-top:-1px;">
<thead>
<tr>
<td style="width:30px;text-align:center;">No.</td>
<td style="width:100px;text-align:center;">充值金额满</td>
<td style="width:390px;text-align:center;">赠送礼品</td>
<td style="width:50px;text-align:center;">单位</td>
<td style="width:50px;text-align:center;">数量</td>
<!--
<td style="width:50px;text-align:center;">单价</td>    
<td style="width:70px;text-align:center;">金额</td>
-->
<td style="text-align:center;">操作</td>
</tr>    
</thead>    
<tbody>
</tbody>
</table>

<table id="tbNoRecord" cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td style="text-align:center;height:100px;">
    暂无数据
</td>
</tr>
</table>

<table id="Table1" cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td class="th">添加规则：</td>
<td style="text-align:right;">

    充值金额满：
    <VACTL:TextBox ID="txtCharges" Runat="server"
            EnableViewState="False"
            CssClass="input"
            Width="60px"
            CanBeNull="No"
            FieldName="充值金额"
            RequiredFieldType="Money"
            MaxLength="10" /> 元  
    &nbsp;
    赠送礼品：
    <VACTL:TextBox ID="txtItemName" Runat="server"
                EnableViewState="False"
                CssClass="input"
                onfocus="JTongSmartDropDownList_OnfocusHandler(this, '../smartdropdownlist_datasrc/get_gifts.aspx',true,true,310,180);"
                Width="310px"
                />
    <asp:HiddenField runat="server" id="txtItemName_hiddenValue" />  
</td>
</tr>
</table>

<table cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td class="footer">

    <input type="button" id="btnUpdate" runat="server" class="btn" style="width:100px" onclick="save(1)" value="保存" />
    <input type="button" id="btnReset" class="btn" style="width:80px" onclick="resetPage()" value="重置" />
    <asp:Label ID="lblNote" runat="server" ForeColor="Red"></asp:Label>

    <asp:HiddenField ID="hfKey" runat="server" />
    
    <VACTL:Hint ID="Hint1" runat="server" HintImageUrl="/app_themes/default/images/textbox" />
    <VACTL:ValidationSummary ID="ValidationSummary1" runat="server"
            DisplayMode="List"
            EnableClientScript="true" />
    
    <!--注意：这个文件一定要放到页面底部，以便覆盖asp.net验证脚本中的同名函数-->
    <script type="text/javascript" src="/scripts/utils/aspnet_validator_extend.js"></script>  
        
</td>
</tr>
</table>

<!--每个页面上只能有一个该控件实例-->
<VACTL:SmartDropDownList ID="SmartDropDownList1" runat="server"></VACTL:SmartDropDownList>  


</div><!--editPageWrapper.END-->

</form>
</body>
</html>

<%    
    Response.Write("<script type=\"text/javascript\">");       
    Response.Write("var itemList = [");       
       
    var i = 0;
    System.Collections.Generic.List<VA.Modules.JDingMember.Core.Model.Sale.Strategy.SSDonateGiftRuleInfo> rules = base.strategy.GetDonateGiftRules(base.strategyCode);
    foreach (VA.Modules.JDingMember.Core.Model.Sale.Strategy.SSDonateGiftRuleInfo item in rules)
    {
        string chargeAmount = item.Charges.ToString("F2");
        string itemCode = item.Item_Code;
        string itemName = item.Item_Name;
        string unit = item.Unit;        
        string quantity = item.Quantity.ToString();

        Response.Write("{");
        Response.Write("\"chargeAmount\":\"" + chargeAmount + "\",\"itemName\":\"" + itemName + "\",\"itemCode\":\"" + itemCode + "\",\"unit\":\"" + unit + "\",\"quantity\":\"" + quantity + "\"");

        if (i == rules.Count - 1)
            Response.Write("}");
        else
            Response.Write("},");
        
        i++;
    }

    Response.Write("];");      
    Response.Write("</script>");        
%>

<script type="text/javascript">
    for (var i = 0; i < itemList.length; i++) {
        formEditListTable_addRow(
            itemList[i].chargeAmount,
            itemList[i].itemCode,
            itemList[i].itemName,
            itemList[i].unit,        
            itemList[i].quantity);
    }
</script>
