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

<!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 confirm() {

            //调用asp.net验证控件自带的js数据验证脚本对控件进行验证；
            var validationResult = Page_ClientValidate('');
            if (!validationResult) {
                return;
            }

            if (!formEditListTable_checkTableData()){
                return;
            }

            var totalAmount = $("#txtTotalAmount").val();
            $("#span_Confirm_TotalAmount").html(totalAmount);
            
            $('#winConfirm').css("display", "block");
            $('#winConfirm').window({
                width: 350,
                height: 340,
                left: 180,
                top: 116,
                modal: true,
                maximizable: false,
                minimizable: false,
                collapsible: false,
                title: '确认'
            });
            $("#btnSubmit").focus();
        }

        function cancelSave() {
            $('#winConfirm').window("close");
        }
    
    function save() {

        if (!formEditListTable_checkTableData()) {
            return;
        }

        $("#btnSubmit").attr("disabled", "disabled");

        var requestType = "POST";
        var url = pageName + "?act=add";  //pageName在BasePage中注册到的客户端；
        var dataType = "html";
        var data = $("form").eq(0).serialize();
        var successFN = function (data, textStatus) {
            var bizNo = "";
            if (data.substring(0, 2) == "ok") {
                bizNo = data.split("|")[1];
                showActResult("兑换成功！", true, doAfterAdd, bizNo);
            } else if (data.indexOf("01|") != -1) {
                showActResult(data.substring(3), false, doAfterAdd, bizNo);
            }
            else {
                showActResult("兑换失败：" + data, false, doAfterAdd, bizNo);
            }
        };
        ajaxRequest(requestType,
            url,
            dataType,
            data,
            successFN,
            errorFN
            );
    }

    function doAfterAdd(actResult, bizNo) {
        if (actResult) {

            if ($("#ckbNotify")[0].checked == true) {
                ajaxExecute("get", "../notification/biztransaction_notify.aspx", { "biztype": "giftexchange", "bizno": bizNo });
            }

            cancelSave();
            resetPage();
        }
    }

    //显示操作结果；
    function showActResult(sMsg, actResult, callback, bizNo) {

        $("#btnSubmit").removeAttr("disabled");

        var icon = "info";
        if (!actResult) {
            icon = "error";
        }

        JTongAlert('操作结果', sMsg, icon, function () {
            if (callback != null && callback != undefined) {
                callback(actResult, bizNo);
            }
        });
    }

    function resetPage() {
        
        $("#txtTotalAmount").val("");
        $("#txtRemark").val("");
        $("#txtItemName").attr("disabled", "disabled");
        $("#txtRemark").attr("disabled", "disabled");
        $("#btnNext").attr("disabled", "disabled");

        clearMemberInfo();

        formEditListTable_clearRows();

        //清除错误提示样式；
        $("select,input").each(function () {
            if ($(this).hasClass("error_indicator")) {
                $(this).removeClass("error_indicator");
            }
        });
    }

    //会员信息加载成功时调用的方法；            
    function doWhenMemberInfoLoadSuc(memberInfo) {
        
        $("#txtItemName").removeAttr("disabled");
        $("#txtRemark").removeAttr("disabled");
        $("#btnNext").removeAttr("disabled");

        $("#txtItemName").focus();
    }

    //会员信息加载失败时调用的方法；
    function doWhenMemberInfoLoadFail() {

    }

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

            if (JTongSmartDropDownList_inputObjID == "txtItemName") {

                var itemType = selectedRow.cells[0].innerHTML;                
                var stockCount = selectedRow.cells[5].innerHTML;
                
                if (itemType == "商品" && parseInt(stockCount) <= 0) {
                    //JTongAlert('提示', '该礼品库存不足，不能兑换！', 'error');
                    alert("该礼品库存不足，不能兑换！");
                    return false;
                }
            }
        }

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

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

            if (JTongSmartDropDownList_inputObjID == "txtItemName") {

                //var itemType = selectedRow.cells[0].innerHTML;
                var itemCode = selectedRow.cells[0].innerHTML;
                var itemName = selectedRow.cells[1].innerHTML;
                var unit = selectedRow.cells[2].innerHTML;
                var price = selectedRow.cells[3].innerHTML;
                //var stockCount = selectedRow.cells[4].innerHTML;
                var quantity = 1;
                var itemType = "2";

                //if (itemType == "服务") {
                //    itemType = "1";
                //}
                //else if (itemType == "商品") {
                //    itemType = "2";
                //}

                formEditListTable_addRow(itemType,itemCode, itemName, unit, price, quantity);
                $("#txtItemName").val("");
            }
        }

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

    $(function () {
        $("#txtTotalAmount").attr("disabled", "disabled");
        $("#txtItemName").attr("disabled", "disabled");
        $("#txtRemark").attr("disabled", "disabled");
        $("#btnNext").attr("disabled", "disabled");
    });

    </script>

    <script type="text/javascript">

        var formEditListTable_RowCounter = 0;

        function formEditListTable_addRow(itemType, itemCode, itemName, unit, price, quantity) {

            formEditListTable_RowCounter++;

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

            //如果找到相同数据行，并进行了数量的合并，则不再添加新的行；
            if (formEditListTable_dataMerge($srcTable, itemCode, quantity)) {
                return;
            }

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

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

            var amount = price * quantity;

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

            rowHtml += '<td style="text-align:center;">';
            rowHtml += '<span>' + itemCode + '</span>';
            rowHtml += '<input type="hidden" name="hfItemType" value="' + itemType + '" />';
            rowHtml += '</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="txtPrice" value="' + price + '" id="txtPrice_' + rowID + '" readonly=readonly onkeyup="formEditListTable_caculateAmount(' + rowID + ')" /></td>';
            rowHtml += '<td><input type="text" name="txtQuantity" value="' + quantity + '" id="txtQuantity_' + 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>';

            //调试代码；
            //$("#txtRemark").val(rowHtml);

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

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

        function formEditListTable_setTotalAmount() {
            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.toString() + '</span>';
                totalRowHtml += '<input type="hidden" name="hfTotalAmount" value="' + total.toString() + '" id="hfTotalAmount" />';
                totalRowHtml += '</td>';

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

                totalRowHtml += '</tr>';

                $srcTable.append($(totalRowHtml));
                $("#txtTotalAmount").val(total.toString());
            }
        }

        function formEditListTable_caculateAmount(rowID) {
            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]);

            var validator = new DataValidator();

            if (isNaN(sQuantity)) {
                alert("数量为无效数字！");
                $txtQuantity.val("");
                $txtQuantity.focus();
                return;
            }
            if (!validator.isInteger(sQuantity)) {
                alert("数量必须为正整数！");
                $txtQuantity.val("");
                $txtQuantity.focus();
                return;
            }
            if (parseInt(sQuantity) <= 0){
                alert("数量必须为正整数！");
                $txtQuantity.val("");
                $txtQuantity.focus();
                return;
            }
           
            if (isNaN(sPrice)) {
                alert("兑换分值为无效数字.");
                $txtPrice.val("");
                $txtPrice.focus();
                return;
            }

            if (parseFloat(sQuantity) > 100000 || parseFloat(sQuantity) < 0) {  //限制数量不能超过100000
                alert("数量不能小于0或超过100000.");
                $txtQuantity.val("");
                $txtQuantity.focus();
                return;
            }
            if (parseFloat(sPrice) > 100000 || parseFloat(sPrice) < 0) {  //单价不能超过100000
                alert("单价不能小于0或超过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);

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

            formEditListTable_setTotalAmount();
        }

        function formEditListTable_checkTableData() {

            var result = true;

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

            $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=hfPrice]").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("$#$", ".");
        }
        function clearItems() {
            formEditListTable_clearRows();
        }

    </script>

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

<div id="wrapper" style="height:1%;overflow:hidden;">

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

<div class="centerFormTitle">
   <h1>礼品兑换</h1>
</div>

<!--#include file="../include/memberinfo.aspx"--> 

<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:70px;text-align:center;">代码</td>
<td style="width:250px;text-align:center;">品名</td>
<td style="width:50px;text-align:center;">单位</td>
<td style="width:70px;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:70px;">
    暂无数据
</td>
</tr>
</table>

<table id="Table1" cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td style="text-align:right;">
    添加礼品：
    <VACTL:TextBox ID="txtItemName" Runat="server"
                EnableViewState="False"
                CssClass="input"                
                Width="300px"
                />
    <asp:HiddenField runat="server" id="txtItemName_hiddenValue" />  
    <input type="button" id="btnClearItems" class="simpleBtn" onclick="clearItems()" value="清除礼品" />    
</td>
</tr>
</table>

<table cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td class="th">积分合计：</td>
<td>
    <VACTL:TextBox runat="server" ID="txtTotalAmount" 
            CssClass="input" 
            Width="100px"
            CanBeNull="No"
            FieldName="积分合计"
            RequiredFieldType="Money"
            Enabled="false"
            Font-Bold="true"
            />
</td>
</tr>
<tr>
<td class="th">操 作 员：</td>
    <td>    
	    <%= base.EmployeeName %>
    </td>
</tr>
<tr>
<td class="th">备注：</td>
<td>
    <VACTL:TextBox ID="txtRemark" Runat="server"
        EnableViewState="False"
        CssClass="input"
        Width="580px"
        MaxLength="100"
        />        
</td>
</tr>
</table>


<table cellspacing="0" cellpadding="3" class="editTable" style="margin-top:-1px;">
<tr>
<td class="footer">
    <asp:CheckBox ID="ckbNotify" runat="server"
             Text="短信通知" />   
    <input type="button" id="btnNext" class="btn" style="width:80px" onclick="confirm()" value="兑换" />
    <input type="button" id="btnResetPage" class="btn" style="width:80px" onclick="resetPage()" value="重置" />
    <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-->

</div><!--"wrapper.END"-->

<!--确认窗口-->    
<div id="winConfirm" style="display:none;">

    <div style="width:300px;margin:auto;">
    
    <br />

    <div class="centerFormTitle">
        <h1>确认兑换信息</h1>
    </div>

    <table cellspacing="0" cellpadding="3" class="editTable" style="margin:auto;width:300px;">
    <tr>
    <td class="th">操 作 员：</td>
    <td>    
	    <span id="span_Confirm_OperatorName"><%= base.EmployeeName %></span>
    </td>
    </tr>
    <tr>
    <td class="th">兑换日期：</td>
    <td>    
	    <span id="span1"><% = DateTime.Now.ToString("yyyy-MM-dd") %></span>
    </td>
    </tr>
    <tr>
    <td class="th">合计积分：</td>
    <td>    
	    <span id="span_Confirm_TotalAmount" style="font-weight:bold;"></span>
    </td>
    </tr>   
    <tr>
    <td colspan="2" class="footer">
        <input type="button" id="btnSubmit" class="btn" style="width:80px" onclick="save()" value="确定" />
        <input type="button" id="btnCancel" class="btn" style="width:80px" onclick="cancelSave()" value="取消" />
    </td>
    </tr>
    </table>
    </div>

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

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

