{echo:JS::import("form")}
<link type="text/css" rel="stylesheet" href="{url:#css/simple.css}" />
{set:$items=array("购物车","确认订单信息","选择支付","订购完成");}
{widget:name=sub_navs action=crumbs items=$items step=4 current=2}
<div class="container">
    <div class="order-info">
        {if:isset($msg)}
        <div class="alert alert-{$msg[0]}">{$msg[1]}</div>
        {/if}
        <form action="{url:/simple/order_act}" class="tiny-form" method="post">
            <div class="clearfix address address-box">
                <h2><b class="fl">选择收货地址：</b><a class="btn btn-main btn-mini fr" href="{url:/ucenter/address}" target="_blank">管理地址</a></h2>
                <ul class="address-list clearfix">
                    {set:$address_default=0;}
                    {list:items=$address}
                    <li>
                        <a href="javascript:;" data-value="{$item['id']}" class="modify"> 修改地址 </a>
                        <div class="address-info " >
                            <input type="radio" name="address_id" city="{$item['city']}" value="{$item['id']}" {if:$item['is_default']==1}{set:$address_default=$item['id']}checked="checked"{/if}><label>{$parse_area[$item['province']]} <strong>{$parse_area[$item['city']]}</strong>（{$item['accept_name']} 收）</label>
                            <p>
                                {$parse_area[$item['county']]} {$item['addr']} {$item['mobile']}
                            </p>
                        </div>
                        <i class="icon-selected-32 ie6png"></i>
                    </li>
                    {/list}
                </ul>
                <div ><a id="address_other" class="btn btn-main btn-mini" href="javascript:;">使用新地址</a></div>
            </div>
            <h2 class="f14 mt20">支付方式：</h2>
            <div class="clearfix">
                <ul class="payment-list">
                    {set:$payment_default = 1;}
                    {query:name=payment as pa fields=pa.*,pp.logo,pp.class_name  join=left join pay_plugin as pp on pa.plugin_id eq pp.id  where=pa.status eq 0 and (pa.client_type eq 0 or pa.client_type eq 2) order=pa.sort desc}
                    <li ><input type="radio" name="payment_id" {if:$key==0} {set:$payment_default = $item['id'];} checked="checked"{/if} value="{$item['id']}" payment_name="{$item['class_name']}"><label><b>{$item['pay_name']}</b> {$item['pay_desc']}</label>
                    <div><img src="{url:@protected/classes/$item[logo]}"></div>
                    </li>
                    {if:$item['class_name']=="received" && $item['config']!=''}
                    {!$received_areas = unserialize($item['config'])}
                    {!$received_areas = $received_areas['areas']}
                    {/if}
                    {/query}
                </ul>
            </div>
            <h2>商品清单：</h2>
            <div class="blank ">
             <table class="table table-line">
              <tr>
               <th style="width:60px;">商品</th>
               <th>名称</th>
               <th style="width:120px;">规格</th>
               <th style="width:100px;">单价</th>
               <th style="width:120px;">数量</th>
               <th style="width:100px;">优惠</th>
               <th style="width:100px;">小计</th>
           </tr>
           {set:$total=0.00;$weight=0;$point=0;$allVirtual=true}
           {list:items=$cart}
           {set:$total+=$item['amount'];$weight += ($item['weight']*$item['num']);$point += ($item['point']*$item['num']);}
           {if:$item['goods_type']==0}{set:$allVirtual=false;}{/if}
           <tr id="{$item['id']}"><td><a href="{url:/index/product/id/$item[goods_id]}" target="_blank"><img src="{url:@$item[img]}" width="50" height="50"></a></td><td><a href="{url:/index/product/id/$item[goods_id]}" target="_blank">{$item['name']}</a></td> <td>{list:items=$item['spec'] item=$spec}
            <p title="{$spec['name']}:{$spec['value'][2]}">{$spec['name']}：{$spec['value'][2]}</p>
            {/list}</td> <td class="tr">{$item['price']}</td> <td class="tc"><div  class="buy-num-bar buy-num clearfix">{$item['num']}</div></td> <td class=" tc">{$item['prom']}</td> <td class="amount red tr">{$item['amount']}</td> </tr>
            {/list}
        </table>
        {set:$prom = new Prom($total);$proms = $prom->meetProms();}
        {set:$fare = new Fare($weight);}
        <table class="table table-list">
            <tr><td> <p>订单备注信息：<input type="text" name="user_remark" style="width:346px;"></p> </td> <td width="260" class="tr">购物车商品合计：</td> <td width="140"><div class="mb10 mt10" style=" background: #f0f0f0;"><span class="fr"><span style=""><span class="currency-symbol f18">{$currency_symbol}</span><b class="cart-total red f18" id="total-amount" total="{$total}">{echo:sprintf("%01.2f",$total)} </b></span></span></div>
            </td></tr>
            <tr>
                <td >
                   <p >订单促销活动：{if:!empty($proms)}<select name="prom_id" id="prom_order">
                    {list:items=$proms}
                    {set:$parse_prom = $prom->parsePorm($item);}
                    <option value="{$item['id']}" data-type="{$item['type']}" data-value="{$parse_prom['value']}">&nbsp;&nbsp;{$parse_prom['note']}&nbsp;&nbsp;</option>
                    {/list}
                </select>{/if}</p>
            </td>
            <td>
                <p class="fr">订单优惠：</p>
            </td>
            <td ><p class="fr">- <b id="prom_order_text">0</b></p></td>

        </tr>
        {if:$open_invoice}
        <tr >
            <td>
               <p style="height:32px;line-height:32px;">索要发票({$tax}%)：<input type="checkbox" name="is_invoice" class="magic-checkbox" id="is_invoice" value="1" data-value="{$tax}"><label for="is_invoice"></label>&nbsp;&nbsp;<span id="invoice" {if:isset($is_invoice) && $is_invoice==1} {else:}style="display:none;"{/if}>发票抬头：<select name="invoice_type"><option value="0">个人</option><option value="1">单位</option></select>&nbsp;&nbsp;<input type="text" name="invoice_title" ></span></p>
           </td>
           <td class="tr">税：</td>
           <td>
            <p class="fr">+ <b id="taxes" data-value="{$tax}">0</b></p>
        </td>
    </tr>
    {/if}
    <tr>
        <td >
        </td>
        <td class="tr">运费：</td>
        <td>
            <p class="fr">+ <b id="fare" data-weight="{$weight}">{echo:$fare->calculate(16);}</b></p>
        </td>
    </tr>
    <tr>
        <td >
        </td>
        <td class="tr orange">送积分：</td>
        <td>
            <p class="fr orange"><b id="point" data-point="{$point}">{$point}</b></p>
        </td>
    </tr>
    <tr><td>
        <input type="checkbox" class="magic-checkbox" id="voucher-select" name=""><label for="voucher-select"></label><a href="javascript:;" id="voucher-btn" style="line-height: 25px;height:25px;">使用代金券抵消部分总额：</a>
    </td><td class="tr">代金券：</td>
    <td><div class="fr">- <b id="voucher">0.00</b></div></td></tr>
</table>
</div>
<div class="box p15 mt5" id="voucher-n" style="display: none">
    <p class="clearfix">提示：一个订单最多能使用一张代金券（<b class="red">注：代金券仅能抵扣商品金额,多出商品的部分忽略不计</b>）。<a id="voucher-cancel" class="fr btn btn-mini ">取消优惠券</a></p>
    <table class="table table-line" >
        <tr style="background: #fff5cc;color: #000;height:20px;"><td>名称</td>
            <td>编号</td>
            <td>面值</td>
            <td>需满足金额</td>
            <td>有效期</td></tr>
            <tbody class="page-content">
                <tr>
                    <td><input name="voucher" type="radio" value="{id}" data-value="{value}"> <label>{name}</label></td>
                    <td>{account}</td>
                    <td>{value}</td>
                    <td>{money}</td>
                    <td>{end_time}</td>
                </tr>
            </tbody>
        </table>
        <div class="page-nav"></div>
    </div>
    <div class="mb10 mt10 clearfix" style="padding:10px; background: #f0f0f0;">
        <span class="fr f14">应付总额：<span style="font-size: 24px;font-family: tahoma"><span class="currency-symbol">{$currency_symbol}</span><b class="cart-total red" id="real-total">{echo:sprintf("%01.2f",$total)}</b></span></span>
    </div>
    <div class="blank line fr">
        <input name="cart_type" type="hidden" value="{$cart_type|''}">
        <p class=""><input type="submit" class="btn btn-main" value="提交订单"></p>
    </div>
    {token:key=order}
</form>
</div>
</div>
<script type="text/javascript">
    {if:$allVirtual}
    $('.address-box').hide();
    {/if}
    $("#address_other").on("click",function(){
        layer.open({
            type: 2,
            title: '添加收货地址',
            shadeClose: true,
            shade: 0.8,
            maxmin: true,
            area: ['960px', '480px'],
            content: '{url:/simple/address_other}'
        });
        return false;
    })
    $(".address-list .modify").each(function(){

        $(this).on("click",function(){
            var id = $(this).attr("data-value");
            layer.open({
                type: 2,
                title: '修改收货地址',
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['960px', '480px'],
                content: '{url:/simple/address_other/id/}'+id
            });
            return false;
        });
    });
    $("#voucher-n").Paging({
        url:'{url:/simple/get_voucher}',
        params:{amount:{$total}},
        callback:function(){
            calculate();
            $("#voucher-n input[name='voucher']").each(function(){
                $(this).on("click",function(){
                    calculate();
                });
            });
        }
    });

    $("#voucher-cancel").on("click",function(){
        if($("#voucher-n input[name='voucher']:checked").size()>0){
            $("#voucher-n input[name='voucher']:checked").prop("checked",false);
            calculate();
        }
    })
    $("#voucher-select").on("click",function(){
        $("#voucher-n").toggle();
    })

    $(".address-list li").each(function(){
        $(this).has("input[name='address_id']:checked").addClass("selected");
        $(this).on("click",function(){
            if(!check_received_areas($(this).find("input").attr("city"),"")){
                layer.alert('此地区不支持货到付款方式。');
                return;
            }
            $(".address-list li").removeClass("selected");
            $("input[name='address_id']").removeProp("checked");
            $("input[name='address_id']",this).prop("checked",true);
            $(this).addClass("selected");
            $("a.default").hide();
            $("a.default",this).show();
            var id = $("input[name='address_id']",this).val();
            var weight = $("#fare").attr("data-weight");
             var allvirtual = "{!=$allVirtual?'true':'false'}";
            $.post("{url:/ajax/calculate_fare}",{weight:weight,id:id,allvirtual:allvirtual},function(data){
                if(data['status']=='success'){
                    $("#fare").text(data['fee']);
                    calculate();
                }
            },'json');
        });
    });
    FireEvent($(".address-list  input[name='address_id']:checked").get(0),"click");

    $(".payment-list li").each(function(){
        $(this).has("input[name='payment_id']:checked").addClass("selected");
        $(this).on("click",function(){
            if(!check_received_areas("",$(this).find("input").attr("payment_name"))){
                layer.alert('此地区不支持货到付款方式。');
                return;
            }
            $(".payment-list li").removeClass("selected");
            $("input[name='payment_id']").removeProp("checked");
            $("input[name='payment_id']",this).prop("checked",true);
            $(this).addClass("selected");
        });
    });

    $("#prom_order").on("change",function(){
        calculate();
    });
    $("#is_invoice").on("click",function(){
        if(!!$(this).prop("checked")){
            $("#invoice").show();
        }
        else $("#invoice").hide();
        calculate();
    })

    //计算实付金额
    function calculate(){
        var total = parseFloat($("#total-amount").attr("total"));
        var voucher = 0;
        var fare = parseFloat($("#fare").text());
        if($("#voucher-n input[name='voucher']:checked").size()>0){
            voucher = parseFloat($("#voucher-n input[name='voucher']:checked").attr('data-value'));
            if(voucher==undefined) voucher =0;
        }
        total -= voucher;
        $("#voucher").text(voucher.toFixed(2));
        if(total<=0) total = 0;

        if($("#is_invoice").size()>0){
            if(!!$("#is_invoice").prop("checked")){
                var tax_fee = ((total * {$tax})/ 100);
                total += tax_fee;
                $("#taxes").text(tax_fee.toFixed(2));
            }
            else{
                $("#taxes").text("0.00");
            }
        }

        total += fare;
        if($("#prom_order").size()>0){
            var prom_order = $("#prom_order").find("option:selected");
            var type = prom_order.attr("data-type");
            var value = parseFloat(prom_order.attr("data-value"));
            var data_point =parseInt($("#point").attr("data-point"));

            $("#point").text(data_point);
            if(type!=4){

                if(type==2){
                    data_point = data_point*value;
                    $("#point").text(data_point);
                    $("#prom_order_text").text('0.00');
                }else{
                    total = (total-value);
                    $("#prom_order_text").text(value.toFixed(2));
                }

            }
            else {
                total = (total-value-fare);
                $("#prom_order_text").text(fare.toFixed(2));
            }
        }
        if(total<0)total = 0;
        $("#real-total").text(total.toFixed(2));
    }
    calculate();
    var form = new Form();
    form.setValue('address_id',"{$order_status['address_id']|$address_default}");
    form.setValue('payment_id',"{$order_status['payment_id']|$payment_default}");
    form.setValue('user_remark',"{$order_status['user_remark']}");
    form.setValue('prom_id',"{$order_status['prom_id']}");
    {if:isset($is_invoice) && $is_invoice == 1}
    form.setValue('is_invoice',"{$is_invoice}");
    form.setValue('invoice_type',"{$invoice_type}");
    form.setValue('invoice_title',"{$invoice_title}");
        //FireEvent(document.getElementById('is_invoice'), 'click');
        {/if}
    function check_received_areas(city,payment_name){
            if(city=="") city = $("input[name='address_id']:checked").attr("city");
            if(payment_name=="") payment_name = $("input[name='payment_id']:checked").attr("payment_name");
            var received_areas = "{$received_areas}";
            var areas = received_areas.split(",");
            var flag =  false;
            if(payment_name == "received"){
                for(i in areas){
                    if(areas[i]==city) flag = true;
                }
            }else{
                flag = true;
            }
            return flag;
        }
    </script>
