<?php
/* 快捷商城系统
 * 版本号：2.0
 * 官网：http://www.kjcms.cn
 * 2015-02-16
 */
class tab_mall_order {
	static $perms;

	//获取表配置参数
	static function get_perms($key) {
		if( empty(self::$perms) ) {
			self::$perms = array(
				"state" => array("待付款" => 0 , "待发货" => 1 , "待收货" => 2 , "已完成" => 10 , "已取消" => -10),
				"award" => array("已奖励" => 1 , "不奖励" => 0 , "未奖励" => -1),
				"paymethod" => array('afterpayment' => '货到付款','repayment' => '预付款支付','onlinepayment' => '在线付款','bankpayment' => '银行转账'),
			);
		}
		$arr_return = array();
		if(isset(self::$perms[$key])) $arr_return = self::$perms[$key];
		return $arr_return;
	}

	/* 保存操作
	 * arr_fields : 为字段数据，默认如果包函 id，则为修改，否则为插入
	 * where : 默认为空，用于有时候条件修改
	 */
	static function on_save($arr_fields , $where = '') {
		$arr_return = array("code"=>0,"id"=>0,"msg"=>"");
		if(isset($arr_fields['order_id'])) {
			$arr_fields['id'] = $arr_fields['order_id'];
			unset($arr_fields['order_id']);
		}
		if( isset($arr_fields['id']) ) {
			$arr_return['id'] = (int)$arr_fields['id'];
			unset($arr_fields['id']);
			if( $arr_return['id'] > 0 ) { //大于零，为修改状态
				if( empty($where) ){
					$where = " order_id='" . $arr_return['id'] . "'";
				} else {
					$where = "(" . $where . ") and order_id='" . $arr_return['id'] . "'";
				}
			}
		}

		$order_detail = array();
		//序列化明细
		if(isset($arr_fields["order_detail"]) && is_array($arr_fields["order_detail"]) ) {
			$order_detail = $arr_fields["order_detail"];
			$arr_fields["order_detail"] = serialize($arr_fields["order_detail"]);
		}
		//序列化活动
		if(isset($arr_fields["order_act"]) && is_array($arr_fields["order_act"]) ) {
			$arr_fields["order_act"] = serialize($arr_fields["order_act"]);
		}
		$obj_db = cls_obj::db_w();
		if( empty($where) ) {
			//必填项检查
			if(empty($order_detail) || empty($order_detail['goods'])) return array("code" => 500 , "msg" => "购买商品不能为空");
			$arr_ids = $arr_detail_ids = array();
			foreach($order_detail['goods'] as $item) {
				$arrx = explode("-" , $item['id']);
				$arr_ids[] = $arrx[0];
				if(count($arrx)>1) $arr_detail_ids[] = $arrx[1];
			}
			if(empty($arr_ids)) return array("code" => 500 , "msg" => "购买商品不能为空");
			$arr_fields['order_goods_ids'] = implode("," , array_unique($arr_ids));
			$arr_fields['order_detail_ids'] = implode("," , array_unique($arr_detail_ids));
			$arr_fields["order_datetime"] = date("Y-m-d H:i:s",TIME);
			//插入到用户表
			$arr = $obj_db->on_insert(cls_config::DB_PRE."mall_order",$arr_fields);
			if($arr['code'] == 0) {
				$arr_return['id'] = $obj_db->insert_id();
				//其它非mysql数据库不支持insert_id 时
				if(empty($arr_return['id'])) {
					$where  = "order_goods_ids='" . $arr_fields['order_goods_ids'] . " and order_user_id='".$arr_fields['order_user_id'] . "' and order_datetime='".$arr_fields["order_datetime"]."'";
					$obj_rs = $obj_db->get_one("select order_id from ".cls_config::DB_PRE."mall_order where ".$where);
					if(!empty($obj_rs)) $arr_return['id'] = $obj_rs['order_id'];
				}
			} else {
				$arr_return['code'] = $arr['code'];
				$arr_return['msg']  = cls_language::get("db_edit");
			}
		} else {

			if($arr_return['id'] < 1) {
				$obj_rs = $obj_db->get_one("select order_id from ".cls_config::DB_PRE."mall_order where ".$where);
				if(!empty($obj_rs)) {
					$arr_return['id'] = $obj_rs['order_id'];
				} else {
					$arr_return['code'] = 114;
					$arr_return['msg']  = cls_language::get("no_editinfo");//修改信息不在在
					return $arr_return;
				}
				$where = "order_id='".$arr_return['id']."'";
			}
			//修改数据表
			$arr = $obj_db->on_update(cls_config::DB_PRE."mall_order" , $arr_fields , $where);
			if($arr['code'] != 0) {
				$arr_return['code'] = $arr['code'];
				$arr_return['msg']  = cls_language::get("db_edit");
			}
		}
		return $arr_return;
	}
	static function get_number($id , $uid = 0 , $addtime = 0) {
		return $id;
	}
	/* 删除函数
	 * arr_id : 要删除的 id数组
	 * where : 删除附加条件
	 */
	static function on_delete($arr_id , $where = '') {
		$arr_return = array("code"=>0,"msg"=>"");
		$str_id = fun_format::arr_id($arr_id);
		if( empty($str_id) && empty($where) ){
			$arr_return["code"] = 22;
			$arr_return["msg"]="id".cls_language::get("not_null");
			return $arr_return;
		}
		$arr_where[] = "order_state=-10";//仅能删除取消的订单
		$obj_db = cls_obj::db_w();
		if( !empty($str_id) ) {
			(is_numeric($str_id)) ? $arr_where[] = "order_id='".$str_id."'" : $arr_where[] = "order_id in(".$str_id.")";
		}
		if( !empty($where) ) {
			if(stristr($where , " or ") && substr(trim($where),0,1) != "(") $where = "(" . $where . ")";
			$arr_where[] = $where;
		}
		$where = implode(" and " , $arr_where);
		$arr_return = $obj_db->on_delete(cls_config::DB_PRE."mall_order" , $where);
		return $arr_return;
	}


	/* 确认函数，送积分与经验
	 * arr_id : 要确认的 id数组
	 * where : 附加条件
	 */
	static function on_award($arr_id , $where = '') {
		$arr_return = array("code"=>0,"msg"=>"");
		$str_id = fun_format::arr_id($arr_id);
		if( empty($str_id) && empty($where) ){
			$arr_return["code"] = 22;
			$arr_return["msg"]="id".cls_language::get("not_null");
			return $arr_return;
		}
		$arr_where = array();
		$obj_db = cls_obj::db_w();
		if( !empty($str_id) ) {
			(is_numeric($str_id)) ? $arr_where[] = "order_id='".$str_id."'" : $arr_where[] = "order_id in(".$str_id.")";
		}
		if( !empty($where) ) {
			if(stristr($where , " or ") && substr(trim($where),0,1) != "(") $where = "(" . $where . ")";
			$arr_where[] = $where;
		}
		$arr_where[] = " order_state>0 and order_isaward=-1";
		$where = implode(" and " , $arr_where);
		$obj_db->begin("orderok");
		$obj_result = $obj_db->select("select order_id,order_user_id,order_total_pay,order_addtime,order_detail from ".cls_config::DB_PRE."mall_order where " . $where);
		while($obj_rs = $obj_db->fetch_array($obj_result) ) {
			$arr_score = array("score"=>$obj_rs['order_total_pay'] , "experience" => $obj_rs['order_total_pay']);
			if(!empty($obj_rs['order_detail'])) {
				$arr_detail = unserialize($obj_rs['order_detail']);
				if(isset($arr_detail['score_add'])) $arr_score['addscore'] = (int)$arr_detail['score_add'];
				if(isset($arr_detail['score_multiple'])) $arr_score['score'] = $arr_score['score']* (int)$arr_detail['score_multiple'];
			}
			$arr_re = tab_sys_user_action::on_action( $obj_rs["order_user_id"] , "mall_submit_order_ok" ,  $arr_score);
			if($arr_re["code"] != 0 ) {
				$obj_db->rollback("orderok");
				$arr_return["code"] = $arr_re["code"];
				$arr_return["msg"] = $arr_re["msg"];
				return $arr_return;
			}
		}
		//设置已奖励状态为：2
		$arr_return = $obj_db->on_update(cls_config::DB_PRE."mall_order" , array("order_isaward"=>1) ,  $where);
		if($arr_return["code"] != 0 ) {
			$obj_db->rollback("orderok");
			return $arr_return;
		}
		$obj_db->commit("orderok");
		return $arr_return;
	}

	/*
	 * 设置订单状态
	 */
	function on_state($arr_id , $state , $beta = '' , $msg_where = '') {
		$arr_state = self::get_perms("state");
		if(!in_array($state , $arr_state)) return array("code" => 500 , "msg" => "处理状态不存在");
		$str_id = fun_format::arr_id($arr_id);
		if( empty($str_id) && empty($msg_where) ) return array("code" => 500 , "msg" => "未指定要处理的订单");
		
		$arr_where = array();
		if(!empty($msg_where)) $arr_where[] = $msg_where;
		(is_numeric($str_id)) ? $arr_where[] = "order_id='".$str_id."'" : $arr_where[] = "order_id in(".$str_id.")";
		
		$where = " where " . implode(" and " , $arr_where);
		$arr = cls_obj::db_w()->on_exe("update " . cls_config::DB_PRE . "mall_order set order_state=" . $state . ",order_state_time='" . date("Y-m-d H:i:s" , TIME) . "',order_state_beta='" . $beta . "'" . $where);
		return $arr;
	}

	//取消订单
	function on_cancel($id , $beta) {
		$obj_db = cls_obj::db_w();
		$obj_order = $obj_db->get_one("select order_pay_val,order_state,order_user_id from " . cls_config::DB_PRE . "mall_order where order_id='" . $id . "'");
		if(empty($obj_order)) return array("code" => 500 , "msg" => "取消订单失败，订单id：" . $id . "，不存在");
		if($obj_order['order_state']>=10) return array("code" => 500 , "msg" => "订单已完成，不能取消");
		if($obj_order['order_state']<=-10) return array("code" => 500 , "msg" => "订单已无效，不需要再取消");
		$obj_db->begin('order_cancel');//开始事务
		if($obj_order['order_pay_val']>0) {//已支付，则退款到预付款中
			$repayment_beta = "取消订单，退款(订单号：" . $id . ")";
			$arr_msg = tab_sys_user_repayment::on_admin_recharge(array(
				"repayment_val" => $obj_order['order_pay_val'],
				"repayment_user_id" => $obj_order['order_user_id'],
				"repayment_about_id" => $id,
				"repayment_beta" => $repayment_beta
			));
			if($arr_msg['code']!=0) {
				$obj_db->rollback('order_cancel');
				return array("code"=>500,"msg"=>"取消订单，退款时发生错误");
			}
		}
		$arr_msg = $obj_db->on_update(
			cls_config::DB_PRE."mall_order",
			array("order_state" => -10 , "order_cancel_beta" => $beta , "order_cancel_time" => date("Y-m-d H:i:s")),
			"order_id='" . $id . "'"
		);
		if($arr_msg['code']!=0) {
			$obj_db->rollback('order_cancel');
			return $arr_msg;
		}
		$obj_db->commit('order_cancel');
		return array("code" => 0 , "msg" => "成功取消订单");
	}
	//订单设置发货
	function on_send($id , $beta) {
		$obj_db = cls_obj::db_w();
		$obj_order = $obj_db->get_one("select order_pay_val,order_state,order_user_id from " . cls_config::DB_PRE . "mall_order where order_id='" . $id . "'");
		if(empty($obj_order)) return array("code" => 500 , "msg" => "发货失败，订单id：" . $id . "，不存在");
		if($obj_order['order_state']!=1) return array("code" => 500 , "msg" => "只有等待发货状态的订单才能执行发货操作");
		$arr_msg = $obj_db->on_update(
			cls_config::DB_PRE."mall_order",
			array("order_state" => 2 , "order_sendbeta" => $beta , "order_sendtime" => date("Y-m-d H:i:s")),
			"order_id='" . $id . "'"
		);
		return $arr_msg;
	}
	//订单设置收货
	function on_receive($id , $msg_where = '') {
		$obj_db = cls_obj::db_w();
		$where = " where order_id='" . $id . "'";
		if(!empty($msg_where)) $where .= " and " . $msg_where;
		$obj_order = $obj_db->get_one("select order_pay_val,order_state,order_user_id from " . cls_config::DB_PRE . "mall_order" . $where);
		if(empty($obj_order)) return array("code" => 500 , "msg" => "收货失败，订单id：" . $id . "，不存在");
		if($obj_order['order_state']!=2) return array("code" => 500 , "msg" => "只有等待收货状态的订单才能执行收货操作");
		$arr_msg = $obj_db->on_update(
			cls_config::DB_PRE."mall_order",
			array("order_state" => 10 , "order_receivetime" => date("Y-m-d H:i:s")),
			"order_id='" . $id . "'"
		);
		return $arr_msg;
	}
}