<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
	<th:block th:include="include :: header('修改客户订单')" />
	<th:block th:include="include :: datetimepicker-css" />
	<th:block th:include="include :: bootstrap-editable-css" />
</head>
<body class="white-bg">
	<div class="wrapper wrapper-content animated fadeInRight ibox-content">
		<div class="panel-group" id="accordion">
			<div  class="panel panel-default">
				<div  class="panel-heading">
					<h4 class="form-header h4 panel-title">
						<a data-toggle="collapse"
						   href="#collapseOne">
							基本信息
						</a>
					</h4>
				</div>
				<div id="collapseOne" class="panel-collapse collapse in">
					<form class="form-horizontal m" id="form-order-edit"
						  th:object="${crmOrder}">
						<input name="orderId" th:field="*{orderId}" type="hidden">
						<input name="customerId" type="hidden" id="customerId" />
						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">主题：</label>
									<div class="col-sm-8">
										<input name="orderName" th:field="*{orderName}"
											   class="form-control" type="text" required>
									</div>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">成交客户：</label>
									<div class="col-sm-8">
										<div class="input-group">
											<input name="customerName" onclick="selectCustomer()"
												   th:field="*{customer.customerName}" class="form-control" type="text" placeholder="请选择成交客户 " id="customerName" required readonly>
											<span class="input-group-addon"><i class="fa fa-search"></i></span>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">成交总额：</label>
									<div class="col-sm-8">
										<div  style="display: flex;border: 1px solid #e5e6e7;border-radius: 4px;width: 100%;">
											<input name="totalPrice" th:field="*{totalPrice}" class="form-control" type="text" required style="border: none;width: 70%;">
											<i class="fa fa fa-cny" style="width: 30%;display: inline-block;line-height: 30px;text-align: center"><a href="javascript:autoCaculate();">自动计算</a></i>
										</div>
									</div>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">总成本：</label>
									<div class="col-sm-8">
										<div style="display: flex;border: 1px solid #e5e6e7;border-radius: 4px;width: 100%;">
											<input name="costPrice" th:field="*{costPrice}" class="form-control" type="text" required style="border: none;width: 70%;">
											<i class="fa fa fa-cny" style="width: 30%;display: inline-block;line-height: 30px;text-align: center"><a href="javascript:autoCaculate();">自动计算</a></i>

										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">成交/签约时间：</label>
									<div class="col-sm-8">
										<div class="input-group date">
											<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
											<input name="orderDate" th:value="${#dates.format(crmOrder.orderDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
										</div>
									</div>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label">付款方式：</label>
									<div class="col-sm-8">
										<select name="payType" class="form-control m-b" th:with="type=${@dict.getType('pay_type')}">
											<option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{payType}"></option>
										</select>
									</div>
								</div>
							</div>
						</div>
						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">有效期开始时间：</label>
									<div class="col-sm-8">
										<div class="input-group date">
											<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
											<input name="validStart" th:value="${#dates.format(crmOrder.validStart, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
										</div>
									</div>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label is-required">有效期结束时间：</label>
									<div class="col-sm-8">
										<div class="input-group date">
											<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
											<input name="validEnd" th:value="${#dates.format(crmOrder.validEnd, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
										</div>
									</div>
								</div>
							</div>
						</div>

						<div class="row">
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label">订单状态：</label>
									<div class="col-sm-8">
										<select name="orderStatus" class="form-control m-b" th:with="type=${@dict.getType('order_status')}">
											<option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{orderStatus}"></option>
										</select>
									</div>
								</div>
							</div>
							<div class="col-sm-6">
								<div class="form-group">
									<label class="col-sm-4 control-label">合同ID：</label>
									<div class="col-sm-8">
										<div class="input-group">
											<input name="contractId" th:field="*{contractId}" class="form-control" type="text">
											<span class="input-group-addon"><i class="fa fa-search"></i></span>
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="row">
							<div class="col-sm-12">
								<div class="form-group">
									<label class="col-xs-2 control-label">备注：</label>
									<div class="col-xs-10">
										<textarea name="remark" maxlength="500" class="form-control" rows="3">[[*{remark}]]</textarea>
									</div>
								</div>
							</div>
						</div>
					</form>
				</div>

			</div>

			<div class="panel panel-default">
				<div class="panel-heading">
					<h4 class="form-header h4 panel-title">
						<a data-toggle="collapse"
						   href="#collapseTwo">
							产品信息
						</a>
					</h4>
				</div>
				<div id="collapseTwo" class="panel-collapse collapse">
					<div class="container-div">
						<div class="row">
							<div class="btn-group-sm" id="toolbarProduct" role="group">
								<a class="btn btn-success" onclick="addProduct();"> <i
										class="fa fa-plus"></i> 添加
								</a>
							</div>
							<div class="col-sm-12 select-table table-striped">
								<table id="bootstrap-table"></table>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
        </div>
    </div>
	<th:block th:include="include :: footer" />
	<th:block th:include="include :: datetimepicker-js" />
	<th:block th:include="include :: bootstrap-table-editable-js" />
	<script th:inline="javascript">
		var productCategoryDatas = [[${@dict.getType('product_category')}]];
		var orderProductStatusDatas = [[${@dict.getType('order_product_status')}]];
		var prefix = ctx + "crm/order";
		var prefixProduct = ctx + "crm/product";
		var prefixOrderProduct =  ctx + "crm/orderProduct";
		var orderId=[[${orderId}]];
		
		$("#form-order-edit").validate({
			focusCleanup : true
		});
		
		$(function() {
            var options = {
                url: prefixOrderProduct + "/listAll",
                removeUrl: prefixOrderProduct + "/remove",
                showSearch: false,
		        showRefresh: false,
		        showToggle: false,
		        showColumns: false,
		        showPageGo: true,
		        onEditableSave: onEditableSave,
                modalName: "关联产品信息",
                queryParams : {
                    orderId:orderId
				},
                columns: [
                {
                    field : 'orderProductId', 
                    title : '订单产品ID',
                    visible: false
                },
		        {
                    title: "序号",
                    formatter: function (value, row, index) {
                 	    return $.table.serialNumber(index);
                    }
                },
                {
                    field : 'orderId', 
                    title : '订单id',
                    visible: false
                },
                {
                    field : 'productId', 
                    title : '产品id',
                    visible: false
                },
                {
                    field : 'product.productName', 
                    title : '产品名称'
                },
                {
                    field : 'product.incomePrice', 
                    title : '成本'
                },
                {
                    field : 'product.salePrice', 
                    title : '原价'
                },
                {
                    field : 'sellPrice', 
                    title : '销售单价',
					editable : {
						type : 'text',
						title : '销售单价',
						emptytext : "【销售单价】为空",
						validate : function(value) {
							if (value.length == 0) {
								return '销售单价不能为空';
							}
							if (!isNumber(value)) {
						        return '销售单价必须为数字';
						    }	
						}
					}
                },
                {
                    field : 'productCount', 
                    title : '成交数量',
					editable : {
						type : 'text',
						title : '成交数量',
						emptytext : "【成交数量】为空",
						validate : function(value) {
							if (value.length == 0) {
								return '成交数量不能为空';
							}
							if (!(isNumber(value) && value % 1 === 0)) {
						        return '成交数量必须为数字';
						    }	
						}
					}
                },
                {
                    field : 'discount', 
                    title : '折扣',
					editable : {
						type : 'text',
						title : '折扣（1-10之间）',
						emptytext : "【折扣】为空",
						validate : function(value) {
							if (value.length == 0) {
								return '折扣不能为空';
							}
							if (!isNumber(value)) {
						        return '折扣必须为【1-10】之间的数字';
						    }	
							if (parseInt(value)>10||parseInt(value)<0) {
						        return '折扣必须为【1-10】之间的数字';
						    }
						}
					}
                },
                {
                    field : 'realPrice', 
                    title : '实际成交价'
                },
				{
				    title: '图片',
				    formatter: function(value, row, index) {
				    	return $.table.imageView(row.product.productImage);
				    }
				},
                {
                    field : 'product.productCategory', 
                    title : '产品类别',
                    formatter: function(value, row, index) {
                       return $.table.selectDictLabel(productCategoryDatas, value);
                    },
		            sortable: true
                },
                {
                    field : 'orderProductStatus', 
                    title : '状态',
                    formatter: function(value, row, index) {
                       return $.table.selectDictLabel(orderProductStatusDatas, value);
                    },
                    visible: false
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        //actions.push('<a class="btn btn-success btn-xs '  + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.orderProductId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs '  + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.orderProductId + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
        });
		
		function onEditableSave (field, row, oldValue, $el) {
        	//alert("字段名：" + field + "，当前值：" + row[field]  + "，旧值：" + oldValue);
        	if(field=="productCount"){//订购数量
        		if(parseInt(row[field])>parseInt(row.stock.stockNum)){
    				$.modal.msgWarning("订购数量不能大于库存");
    				$.table.refresh();
    				return;
    			}
        		var data = { "orderProductId": row.orderProductId, "productCount": row[field]};
    			$.operate.post(prefixOrderProduct + "/updateOrderProductCount", data);
        	}
        	else if(field=="sellPrice"){//销售价格
        		var data = { "orderProductId": row.orderProductId, "sellPrice": row[field]};
    			$.operate.post(prefixOrderProduct + "/updateOrderSellPrice", data);
        	}
			else if(field=="discount"){//折扣
				var data = { "orderProductId": row.orderProductId, "discount": row[field]};
    			$.operate.post(prefixOrderProduct + "/updateOrderDiscount", data);
        	}
        }

		function submitHandler() {
			if ($.validate.form()) {
				$.operate.saveTab(prefix + "/edit", $('#form-order-edit')
						.serialize());
			}
		}

		$("input[name='orderDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
        
        $("input[name='validStart']").datetimepicker({
    		format: 'yyyy-mm-dd',
    		minView: "month",
    	    todayBtn:  true,
    	    autoclose: true
    	}).on('changeDate', function(event) {
    		event.preventDefault();
    		event.stopPropagation();
    		var startTime = event.date;
    		$("input[name='validEnd']").datetimepicker('setStartDate', startTime);
    	});
    	
    	$("input[name='validEnd']").datetimepicker({
    		format: 'yyyy-mm-dd',
    		minView: "month",
    		todayBtn:  true,
    		autoclose: true
    	}).on('changeDate', function(event) {
    		event.preventDefault();
    		event.stopPropagation();
    		var endTime = event.date;
    		$("input[name='validStart']").datetimepicker('setEndDate', endTime);
    	});
    	
    	/* 自动计算 */
		function autoCaculate(){
			var data = $("#" + table.options.id).bootstrapTable('getData');
			if (data.length == 0) {
       			$.modal.alertWarning("请添加产品后计算！");
       			return;
       		}
			var orderId= [[${orderId}]];
			$.ajax({
	            url: prefixOrderProduct + "/selectOrderPrice",
	            data: {
					"orderId" : orderId
				},
	            type: "post",
	            success: function(result) {
	            	if (result.code == 0) {
	            		$("#totalPrice").val(result.data.totalPrice);
	            		$("#costPrice").val(result.data.costPrice);
	            		$.modal.msgSuccess(result.msg);
	            	} else {
	            		$.modal.msgError(result.msg);
	            	}
	            },
				error : function(e) {
					$.modal.msgError("系统异常");
				}
	        })
		}
		
		/* 订单管理-修改-选择产品  */
		function addProduct()
		{
			var orderId= [[${orderId}]];
			$.modal.open('选择订单产品', prefixProduct + '/selectOrderProduct/'+orderId);
		}
		
		/* 订单管理-修改-选择客户  */
	    function selectCustomer() {
	    	var url = ctx + "crm/customer/selectCustomer";
	   		$.modal.open("选择客户", url);
		}
		
	    function isNumber(val){
	        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
	        if(regPos.test(val)){
	            return true;
	        }else{
	            return false;
	        }
	    }
			
	</script>
</body>
</html>