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

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

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

        if (!formEditListTable_checkTableData()) {
            return;
        }

        var flag = "0";
        if ($("#hfKey").val() != "") {
            flag = "1";
        }

        if (flag == 0) {
            add();
        }
        else {
            update();
        }
    }

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

    function update() {
        var requestType = "POST";
        var url = pageName + "?act=update";
        var dataType = "html";
        var data = $("form").eq(0).serialize();
        var successFN = function (data, textStatus) {
            if (data == "ok") {
                showActResult("修改成功！", true, doAfterUpdate);
            } else if (data.indexOf("01|") != -1) {
                showActResult(data.substring(3), false, doAfterUpdate);
            }
            else {
                showActResult("修改失败：" + data, false, doAfterUpdate);
            }
        };
        ajaxRequest(requestType,
            url,
            dataType,
            data,
            successFN,
            errorFN
            );
    }

    function doAfterAdd(actResult) {
        if (actResult) {
            try {
                if (window.parent != window.self) {
                    window.parent.reload();
                }
            } catch (e) { }
            resetPage();
        }
    }
    function doAfterUpdate(actResult) {
        if (actResult) {
            try {
                if (window.parent != window.self) {
                    window.parent.closeFrameWindow();
                    window.parent.reload();
                }
            } catch (e) { }
        }
    }

    function resetPage() {

        $("#txtCardName").val("");
        $("#txtValidTermNumber").val("");
        $("#txtSrvCount").val("");                
        $("#ddlValidTermUnit")[0].options[1].selected = true;
        $("#ddlEnableRule")[0].options[0].selected = true;
        $("#txtRemark").val("");

        formEditListTable_clearRows();

        clearInputValidatorError();

        $("#txtCardName").focus();
    }
   
    /**商品/服务项目添加操作.BEGIN**********************/

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

            if (JTongSmartDropDownList_inputObjID == "txtItemName") {
                
                var itemType = $(selectedRow.cells[0]).find("input:hidden[name=hfItemType]").eq(0).val();
                var itemCategory = $(selectedRow.cells[0]).find("input:hidden[name=hfItemCategory]").eq(0).val();
                var itemCode = selectedRow.cells[1].innerHTML;
                var itemName = selectedRow.cells[2].innerHTML;
                var unit = selectedRow.cells[3].innerHTML;
                var price = selectedRow.cells[4].innerHTML;
                var discountedPrice = price;
                var quantity = 1;

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

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

    function caculateCardPrice() {
        var hfTotalAmount = $("#hfTotalAmount").val();
        var srvCount = $("#txtSrvCount").val();
        var cardPrice = 0.00;

        if ($.trim(hfTotalAmount) == "") {
            hfTotalAmount = "0.00";
        }
        if ($.trim(srvCount) == "") {
            srvCount = "0.00";
        }

        cardPrice = parseFloat(hfTotalAmount) * parseFloat(srvCount);

        $("#lblCardPrice").html(cardPrice.toFixed(2).toString());
        $("#hfCardPrice").val(cardPrice.toFixed(2).toString());
    }

    /**商品/服务项目添加操作.END**********************/
    
    function setControls() {
        
        var cardType = $('input:radio[name=rbnCardType]:checked').val();
        
        if (cardType == "1") { //自由消费卡
            $("#txtValidTermNumber").val("100");
            $("#tr_ValidTerm").hide();
            $("#ddlEnableRule")[0].options[0].selected = true;
            $("#ddlEnableRule").removeAttr("disabled");
        } else if (cardType == "2") { //包期消费卡
            $("#tr_ValidTerm").show();
            $("#ddlEnableRule")[0].options[1].selected = true;
            $("#ddlEnableRule").attr("disabled", "disabled");            
        }
    }

    $(function () {
        $("#txtCardName").focus();
        $("#txtSrvCount").keyup(function (event) {            
            caculateCardPrice();
        });

        $("input[name=rbnCardType]").change(function () {
            setControls();
        }).click(function(){
            setControls();
        });        

        setControls();
    });

    </script>

    <script type="text/javascript">

        var formEditListTable_RowCounter = 0;

        function formEditListTable_addRow(itemType, itemCode, itemName, unit, price, discountedPrice, 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, "‘");
            unit = unit.replace(/'/g, "‘");
            
            var amount = discountedPrice * 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 += '</td>';

            rowHtml += '<td style="text-align:left;padding-left:5px;">';
            rowHtml += '<span>' + itemName + '</span>';
            rowHtml += '<input type="hidden" name="hfItemType" value="' + itemType + '" />';
            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 style="text-align:center;">';
            rowHtml += '<span>' + price + '</span>';
            rowHtml += '<input type="hidden" name="hfPrice" value="' + price + '" />';
            rowHtml += '</td>';

            rowHtml += '<td><input type="text" name="txtDiscountedPrice" value="' + discountedPrice + '" id="txtDiscountedPrice_' + rowID + '" 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="7" 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));
            }

            caculateCardPrice();
        }

        function formEditListTable_caculateAmount(rowID) {
            var $txtQuantity = $("#txtQuantity_" + rowID);
            var $txtPrice = $("#txtDiscountedPrice_" + 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=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 id="noteBar">                          
    <p>注：计次卡只能使用全局商品/服务项目字典，以便会员可以跨门店划次消费。</p>
</div><!--toolBar.END--> 

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

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

<%
    if (VA.Modules.JDingMember.Core.SystemInfo.SoftInfo.SoftLevel == VA.Modules.JDingMember.Core.Enums.SoftLevel.Free ||
        VA.Modules.JDingMember.Core.SystemInfo.SoftInfo.SoftLevel == VA.Modules.JDingMember.Core.Enums.SoftLevel.Basic)
    {
        base.ShowSoftFunctionLimitNote(VA.Modules.JDingMember.Core.SystemInfo.SoftInfo.SoftLevelName);
    }
%>

<div class="centerFormTitle">
   <h1><asp:Label ID="lblFormTitle" runat="server">添加计次卡</asp:Label></h1>
</div>

<table cellspacing="0" cellpadding="3" class="editTable">
<tr>
<td class="th">(<span class="note mustfill">*</span>)卡 类 型：</td>
<td>
    <asp:RadioButtonList ID="rbnCardType" runat="server"
         RepeatDirection="Horizontal"
         RepeatLayout="Flow">
    <asp:ListItem Value="1" Selected="True">自由消费卡</asp:ListItem>
    <asp:ListItem Value="2">包月消费卡</asp:ListItem>
    </asp:RadioButtonList>  
</td>
</tr>
<tr>
<td class="th">(<span class="note mustfill">*</span>)卡 名 称：</td>
<td>
    <VACTL:TextBox ID="txtCardName" Runat="server"
            EnableViewState="False"
            CssClass="input"
            Width="300px"
            CanBeNull="No"
            FieldName="赠品代码"
            MaxLength="50" />  
</td>
</tr>
<tr id="tr_ValidTerm" runat="server" visible="false">
<td class="th">(<span class="note mustfill">*</span>)有 效 期：</td>
<td>              
    <VACTL:TextBox ID="txtValidTermNumber" Runat="server"
            EnableViewState="False"
            CssClass="input"
            Width="100px"
            CanBeNull="No"
            FieldName="有效期"
            RequiredFieldType="PositiveInteger"
            MaxLength="10" />        
    <asp:DropDownList ID="ddlValidTermUnit" Runat="server">     
        <asp:ListItem Value="月" Selected="True">月</asp:ListItem>
       <%-- <asp:ListItem Value="年">年</asp:ListItem>--%>
    </asp:DropDownList>
</td>
</tr>
<tr>
<td class="th">(<span class="note mustfill">*</span>)生效规则：</td>
<td>              
    <asp:DropDownList ID="ddlEnableRule" Runat="server"
         Width="104px" >    
        <asp:ListItem Value="1" Selected="True">即时生效</asp:ListItem>        
        <asp:ListItem Value="2">下月初生效</asp:ListItem>
    </asp:DropDownList>
</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:70px;text-align:center;">项目代码</td>
<td style="width:200px;text-align:center;">项目品名</td>
<td style="width:50px;text-align:center;">单位</td>
<td style="width:70px;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:100px;">
    暂无数据
</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"
                onfocus="JTongSmartDropDownList_OnfocusHandler(this, '../smartdropdownlist_datasrc/get_chargeitems.aspx',true,true,450,180);"
                Width="310px"
                />
    <asp:HiddenField runat="server" id="txtItemName_hiddenValue" /> 
    <asp:HiddenField runat="server" id="txtItemName_CustomParms" Value="range=2" /> 
</td>
</tr>
</table>

<table cellspacing="0" cellpadding="3" class="editTable">
<tr>
<td class="th">(<span class="note mustfill">*</span>)可用次数：</td>
<td>              
    <VACTL:TextBox ID="txtSrvCount" Runat="server"
            EnableViewState="False"
            CssClass="input"
            Width="100px"
            CanBeNull="No"
            FieldName="有效期"
            RequiredFieldType="PositiveInteger"
            MaxLength="10" />       
</td>
</tr>
<tr>
<td class="th">(<span class="note mustfill">*</span>)售价：</td>
<td>              
    <asp:Label ID="lblCardPrice" runat="server">0.00</asp:Label>
    <asp:HiddenField runat="server" id="hfCardPrice" Value="0.00" />    
</td>
</tr>
<tr>
<td class="th">备注：</td>
<td>    
    <VACTL:TextBox ID="txtRemark" Runat="server"
        EnableViewState="False"
        CssClass="input"
        Width="580px"
        MaxLength="100"     
        />        
</td>
</tr>
<tr>
<td class="th">卡状态：</td>
<td>    
    <asp:RadioButtonList ID="rbnStatus" runat="server"
         RepeatDirection="Horizontal"
         RepeatLayout="Flow">
    <asp:ListItem Value="1" Selected="True">启用</asp:ListItem>
    <asp:ListItem Value="2">停用</asp:ListItem>
    </asp:RadioButtonList>
</td>
</tr>
</table>

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

    <% if (base.flag == 0) { %>
    <input type="button" id="Button1" class="btn" style="width:100px" onclick="save()" value="保存" />
    <input type="button" id="Button2" class="btn" style="width:100px" onclick="resetPage()" value="重置" />
    <% } else { %>
    <input type="button" id="btnUpdate" runat="server" class="btn" style="width:100px" onclick="save()" 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-->

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

<% if (base.flag == 1){ %>
<%    
    Response.Write("<script type=\"text/javascript\">");       
    Response.Write("var itemList = [");       
       
    var i = 0;       
    foreach (VA.Modules.JDingMember.Core.Model.PointCard.PointCardChargeItemInfo item in base.cardInfo.ChargeItems)
    {
        string itemType = item.Item_Type;
        string itemCode = item.Item_Code;
        string itemName = item.Item_Name;
        string unit = item.Unit;
        string price = item.Price.ToString("F2");
        string discountedPrice = item.Discounted_Price.ToString("F2");
        string quantity = item.Quantity.ToString();

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

        if (i == base.cardInfo.ChargeItems.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].itemType,
        itemList[i].itemCode,
        itemList[i].itemName,
        itemList[i].unit,
        itemList[i].price,
        itemList[i].discountedPrice,
        itemList[i].quantity);            
    }
</script>

<% } %>


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

