<?php
/* 快捷商城系统
 * 版本号：2.0
 * 官网：http://www.kjcms.cn
 * 2015-02-16
 */
class mod_ajax extends inc_mod_default {
	//保存订单
	function on_save_order() {
		$address_id = fun_get::get("address_id");
		$obj_db = cls_obj::db_w();
		$arr_cart = cls_mall::cart_list();
		if($arr_cart['num']==0) return array('code'=>500 , 'msg'=>'购物车不能为空');
		$arr_order = array();
		//验证收货信息
		$obj_info = $obj_db->get_one("select * from " . cls_config::DB_PRE . "sys_user_address where address_id='" . $address_id . "'");
		if(empty($obj_info)) return array("code"=>500 , "msg"=>"请选择配送地址");
		//验证支付信息
		$arr_paymethod = cls_config::get("paymethod" , "mall");
		$arr_order['order_pay_method'] = fun_get::get('paymethod');
		if(!in_array($arr_order['order_pay_method'] , $arr_paymethod)) return array('code' => 500 , 'msg' => '选择支付方式不存在');
		//验证配送方式
		$arr_order['order_sendinfo_id'] = (int)fun_get::get('sendinfo_id');
		if(empty($arr_order['order_sendinfo_id'])) return array('code' => 500 , 'msg' => '请选择配送方式');
		//验证商品库存
		$weight = 0;
		$is_postage = true;
		$arr_area_ids = explode(',' , $obj_info['address_area_allid']);
		$goods_postage = 0;
		foreach($arr_cart['list'] as $item) {
			if($item['num']>$item['store']) {
				return array("code" => 500 , "msg" => $item['name'] . "当前库存数量为" . $item['store'] . ",不够配送，请减少数量或选择其它同类商品");
			}
			if($item['postage']!='') {
				$arr_postage = tab_mall_goods::format_postage($item['postage']);
				$isx = false;
				foreach($arr_postage['ids'] as $areaid) {
					if(in_array($areaid , $arr_area_ids)) {
						if($arr_postage['mode'] == 1) {
							$goods_postage += $item['num']*$arr_postage['id_' . $areaid];
						} else {
							$goods_postage += $arr_postage['id_' . $areaid];
						}
					}
				}
				if($isx == false) {
					$is_postageb = false;
					$weight += $item['weight']*$item['num'];
				}
			} else {
				$is_postage = false;
				$weight += $item['weight']*$item['num'];
			}
		}

		//计算配送费用
		$arr_msg = tab_mall_sendinfo::get_sendprice($arr_order['order_sendinfo_id'] , $weight , $obj_info['address_area_allid']);
		if($arr_msg['code'] != 0) return $arr_msg;
		if($is_postage) {
			$arr_order['order_sendprice'] = $goods_postage;
		} else {
			$arr_order['order_sendprice'] = $arr_msg['price'] + $goods_postage;
		}
		if($arr_order['order_pay_method'] == 'afterpayment') {
			if( $arr_msg['payment'] != 1) return array("code" => 500 , "msg" => "当前地区不支持货到付款");
			$arr_order['order_state'] = 1;//货到付款
		}
		$arr_order['order_name'] = $obj_info['address_name'];
		$arr_order['order_address'] = $obj_info['address_address'];
		$arr_order['order_area'] = $obj_info['address_area'];
		$arr_order['order_tel'] = $obj_info['address_tel'];
		$arr_order['order_user_id'] = cls_obj::get("cls_user")->uid;
		$arr_order['order_arrivetime'] = fun_get::get("arrivetime");
		//商品合计价
		$arr_order['order_total_goods'] = $arr_cart["total"];
		$arr_order['order_detail']['goods'] = $arr_cart['list'];
		//应付 = 运费 + 商品合计
		$arr_order['order_total_pay'] = $arr_order['order_sendprice'] + $arr_order['order_total_goods'];
		$obj_db = cls_obj::db_w();
		$obj_db->begin("saveorder");
		//是否足够预付款支付
		if($arr_order['order_pay_method'] == 'repayment') {
			$repayment = cls_obj::get("cls_user")->get_repayment();
			if( $arr_order['order_total_pay'] > $repayment) {
				$obj_db->rollback("saveorder");
				return array("code"=>500 , "msg"=>"您当前预付款金额不足以本次支付");
			}
			$arr_msg = tab_sys_user_repayment::on_order_pay($arr_order['order_user_id'] , $arr_order['order_total_pay'] , 0 , "预付款支付订单");
			if($arr_msg['code']!=0) {
				$obj_db->rollback("saveorder");
				return $arr_msg;
			}
			$arr_order['order_repay'] = $arr_order['order_total_pay'];
			$arr_order['order_state'] = 1;//设置为待发货状态
		}
		$arr_order_msg = tab_mall_order::on_save($arr_order);
		//操作成功
		if($arr_order_msg['code'] != 0) {
			$obj_db->rollback("saveorder");
			return $arr_order_msg;
		}
		$arr_sold = array();
		//修改商品销售量
		foreach($arr_cart['list'] as $item){
			$arr = explode("-" , $item['id']);
			$gid = $arr[0];
			$detailid = (count($arr)>1) ? $arr[1] : 0;
			if(count($arr)==2) {
				$arr_x = $obj_db->on_exe("update ".cls_config::DB_PRE."mall_goods_detail set detail_sold=detail_sold+" . $item['num'] . " where detail_id='".$arr[1]."'");
			}
			$arr_x = $obj_db->on_exe("update ".cls_config::DB_PRE."mall_goods set goods_sold=goods_sold+" . $item['num'] . " where goods_id='".$arr[0]."'");
			$arr_sold[] = array('sold_goods_id' => $gid , 'sold_detail_id' => $detailid , 'sold_num' => $item['num'] , 'sold_user_id'=>$arr_order['order_user_id'] , 'sold_order_id' => $arr_order_msg['id'] , 'sold_price' => $item['price'] , 'sold_goods_cost' => $item['cost'] , 'sold_shop_id' => $item['shop_id'] , 'sold_datetime' => date("Y-m-d H:i:s"));
		}
		$arr = $obj_db->on_insert_all(cls_config::DB_PRE . "mall_goods_sold" , $arr_sold);
		//更新地址时间
		$arr_msg = tab_sys_user_address::on_save(array("address_id" => $obj_info['address_id'] , 'address_order_time' => TIME ) );
		$obj_db->commit("saveorder");
		//清空购物车
		cls_mall::cart_clear();
		return $arr_order_msg;
	}

	//保存收货信息
	function on_address_save() {
		$arr_fields = array(
			"address_id" => (int)fun_get::get("id"),
			"address_name" => fun_get::get("name"),
			"address_address" => fun_get::get("address"),
			"address_area" => fun_get::get("area"),
			"address_tel" => fun_get::get("tel"),
			"address_area_id" => fun_get::get("area_id"),
			"address_area_allid" => fun_get::get("area_allid"),
		);
		$arr_msg = tab_sys_user_address::on_save($arr_fields);
		return $arr_msg;
	}

	//删除收货信息
	function on_address_del() {
		$id = (int)fun_get::get("id");
		if(empty($id)) return array("code" => 500 , "msg" => "没有指定要删除的收货信息");
		$arr_msg = tab_sys_user_address::on_delete($id , "address_user_id='" . cls_obj::get("cls_user")->uid . "'");
		$arr_msg['id'] = $id;
		return $arr_msg;
	}

	//取商品评价信息
	function get_goods_comments($gid , $page , $pagesize = 20) {
		$arr = explode("-" , $gid);
		$gid = $arr[0];
		$obj_db = cls_obj::db();
		$arr_uid = array();
		$str_where = " where comment_goods_id='" . $gid . "'" ;
		$arr_return["pageinfo"] = $obj_db->get_pageinfo(cls_config::DB_PRE."mall_goods_comment" , $str_where , $page , $pagesize);
		$obj_result = $obj_db->select("SELECT comment_user_id as 'uid',comment_beta as 'beta',comment_val as 'val',comment_addtime as 'addtime',comment_pic as 'pic',comment_goods as 'goods',user_experience FROM ".cls_config::DB_PRE."mall_goods_comment a left join " . cls_config::DB_PRE . "sys_user b on a.comment_user_id=b.user_id" . $str_where . $arr_return['pageinfo']['limit']);
		while( $obj_rs = $obj_db->fetch_array($obj_result) ) {
			$obj_rs['pic'] = empty($obj_rs['pic']) ? array() : explode("|" , $obj_rs['pic']);
			$obj_rs['addtime'] = date("Y-m-d H:i" , $obj_rs['addtime']);
			$obj_rs['rate'] = $obj_rs['val']/5*100;
			if($obj_rs['rate'] > 100) $obj_rs['rate'] = 100;
			if($obj_rs['rate'] < 0) $obj_rs['rate'] = 0;
			$arr_goods = unserialize($obj_rs['goods']);
			$obj_rs['format'] = array();
			if(!empty($arr_goods['format'])) {
				foreach($arr_goods['format'] as $format) {
					$obj_rs['format'][] = $format['name'] . "=>" . $format['val'];
				}
			}
			$obj_rs['level'] = tab_sys_user::get_level($obj_rs['user_experience']);
			$arr_uid[] = $obj_rs['uid'];
			$obj_rs['name'] = '';
			unset($obj_rs['goods']);
			unset($obj_rs['user_experience']);
			$arr_return['list'][] = $obj_rs;
		}
		if(!empty($arr_uid)) {
			$user_info = cls_obj::get("cls_user")->get_user($arr_uid);
			$count = count($arr_return["list"]);
			for($i = 0 ; $i < $count ; $i++) {
				$arr_return["list"][$i]['name'] = array_search($arr_return["list"][$i]['uid'] , $user_info);
			}
		}
		$arr_return['pagebtns']   = fun_kj::get_pagebtns($arr_return['pageinfo']);
		return $arr_return;
	}
	function on_reg($user_type = ''){
		$arr_return=array("code"=>0,"msg"=>"注册成功");
		$str_pwd1 = fun_get::post('pwd1');
		$str_pwd2 = fun_get::post('pwd2');
		if($str_pwd1 != $str_pwd2){
			$arr_return["code"]=1;
			$arr_return["msg"]="两次输入密码不一致";
			return $arr_return;
		}
		$reg_switch = (int)cls_config::get("reg_switch" , "user");
		$reg_invite_code = cls_config::get("reg_invite_code" , "user");
		$reg_switch_info = cls_config::get("reg_switch_info" , "user");
		if($reg_switch == 1) {
			$arr_return["code"]=500;
			if(empty($reg_switch_info)) $reg_switch_info = "网站关闭了新用户注册功能";
			$arr_return["msg"]=$reg_switch_info;
			return $arr_return;
		} else if($reg_switch == 2) {
			$invite_code = fun_get::post('invite_code');
			if($invite_code != $reg_invite_code) {
				$arr_return["code"]=500;
				$arr_return["msg"] = "邀请码输入不正确";
				return $arr_return;
			}
		}
		$verifycode = fun_get::post("verifycode");
		$isverify = (cls_obj::get("cls_session")->get('verify_reg') > 0) ? false : true;
		$arr_user=array(
			"user_name" => fun_get::post("uname"),
			"user_pwd" => $str_pwd1,
		);
		if(cls_config::get('rule_uname','user')=='email') {
			$arr = tab_sys_verify::on_verify($arr_user['user_name'] , $verifycode ,3 ,86400 , $isverify);
			if($arr['code'] != 0) return $arr;
			cls_obj::get("cls_session")->set('verify_reg' , 1);//设置已验证标识
		} else if(cls_config::get('rule_uname','user')=='mobile') {
			$arr = tab_sys_verify::on_verify($arr_user['user_name'] , $verifycode , 4 ,600, $isverify);
			if($arr['code'] != 0) return array('code' => 500 , 'msg' => '短信验证码有误');
			cls_obj::get("cls_session")->set('verify_reg' , 1);//设置已验证标识
		} else if(cls_config::get('reg_verify' , 'user')){
		//是否需要验证码
			if(cls_verifycode::on_verify($verifycode) == false) {
				$arr_return["code"] = 11;
				$arr_return["msg"]  = cls_language::get("verify_code_err");
				return $arr_return;
			}
		}
		if(fun_is::set("email")) $arr_user['user_email'] = fun_get::post("email");
		if(!empty($user_type)) $arr_user['user_type'] = $user_type;
		//注册用户
		$arr = cls_obj::get("cls_user")->on_reg($arr_user);
		if($arr["code"] != 0){
			return $arr;
		} else {
			$arr_return['id'] = $arr['id'];
			$arr_login=array( "user_name"=>$arr_user["user_name"],"user_pwd"=>$arr_user["user_pwd"],"user_id" => $arr_return['id']);
			$arr=cls_obj::get("cls_user")->on_login($arr_login,1);
			if($arr["code"]!=0){
				return $arr;
			}
		}
		return $arr_return;
	}
	function on_findpwd_step1() {
		$verifycode = fun_get::get("verifycode");
		if(cls_verifycode::on_verify($verifycode) == false) {
			return array('code' => '11' , 'msg' => '验证码输入错误');
		}
		$uname = fun_get::get("uname");
		$arr_user = cls_obj::get("cls_user")->get_user($uname , false);
		if(empty($arr_user) || !isset($arr_user[$uname])) return array('code' => '500' , 'msg' => '输入账号不存在');
		$obj_rs = cls_obj::db()->get_one("select user_email,user_mobile from " . cls_config::DB_PRE . "sys_user where user_id='" . $arr_user[$uname] . "'");
		if(empty($obj_rs)) {
			return array('code' => '500' , 'msg' => '注册账号没有邦定个人信息');
		}
		$arr_return = array('code' => '0' , 'email' => '');
		$arr_return['is_sms'] = (fun_is::com('sms'))? "1" : "0";
		$arr_return['is_email'] = (fun_is::com('email'))? "1" : "0";
		$arr_return['is_msg'] = (fun_is::com('msg'))? "1" : "0";
		$arr = explode("@" , $obj_rs['user_email']);
		if(strlen($arr[0])>3) {
			$arr_return['email'] = str_pad(substr($arr[0],0,3),strlen($arr[0]),"*") . "@" . $arr[1];
		} else if(count($arr)>1) {
			$arr_return['email'] = str_pad(substr($arr[0],0,1),strlen($arr[0]),"*") . "@" . $arr[1];
		}
		$arr_return['mobile'] = str_pad(substr($obj_rs['user_mobile'],0,3),strlen($obj_rs['user_mobile'])-4,"*") . substr($obj_rs['user_mobile'],-4);
		return $arr_return;
	}
	function on_findpwd_step2() {
		$method = (int)fun_get::get("method");
		$uname = fun_get::get("uname");
		$arr_user = cls_obj::get("cls_user")->get_user($uname , false);
		if(empty($arr_user) || !isset($arr_user[$uname])) return array('code' => '500' , 'msg' => '输入账号不存在');

		$obj_user = cls_obj::db()->get_one("select user_id,user_email,user_mobile from " . cls_config::DB_PRE . "sys_user where user_id='" . $arr_user[$uname] . "'");
		if(empty($obj_user)) {
			return array('code' => '500' , 'msg' => '输入账号不存在');
		}
		if($method == 1) {
			$arr_key = tab_sys_verify::get_key($obj_user['user_id'],1,$obj_user['user_email']);
			if($arr_key['code']!=0) return $arr_key;
			$url = cls_config::get("url" , 'base') . "/index.php?app_act=findpwd.email&val=" . urlencode($obj_user['user_email']) . "&key=" . $arr_key['key'];
			//取邮件内容
			$obj_cont = cls_obj::db()->get_one("select article_title,article_content from " . cls_config::DB_PRE . "article where article_key='findpwdwords'");
			if(empty($obj_cont)) {
				$obj_cont['article_title'] = cls_config::get("site_title" , "sys") . "找回密码";
				$obj_cont['article_content'] = "<a href='".$url."'>请点击链接重置登录密码</a>，如果未操作，系统将保留原密码<br>如果无法点击请复制以下代码，粘贴到浏览器地址栏访问<br>" . $url;
			} else {
				$obj_cont['article_content'] = fun_get::filter($obj_cont['article_content'] , true);
				$obj_cont['article_content'] = str_replace('{$url}' , $url , $obj_cont['article_content']);
			}
			$arr = cls_obj::get("cls_com")->email('send' , array('to_mail' => $obj_user['user_email'] , 'title' => $obj_cont['article_title'] , 'content' => $obj_cont['article_content'] ,'save' => 1));
			cls_obj::get("cls_session")->set('verify_val' , $obj_user['user_email']);
			return $arr;
		} else if($method == 2) {
			$arr_key = tab_sys_verify::get_key($obj_user['user_id'],2,$obj_user['user_mobile']);
			if($arr_key['code']!=0) return $arr_key;
			$arr = cls_obj::get('cls_com')->sms("on_send" , array("tel"=>$obj_user['user_mobile'] , "cont" => "您的验证码：" . $arr_key['key'] . ",请在网页上输入此号码，如非本人操作请忽略" ) );
			cls_obj::get("cls_session")->set('verify_val' , $obj_user['user_mobile']);
			return $arr;
		} else if($method == 3) {
			$arr_fields = array(
				"msg_name" => fun_get::get('name'),
				"msg_tel" => fun_get::get('tel'),
				"msg_cont" => fun_get::get('cont'),
				"msg_type" => 1,
				"msg_user_id" => $obj_user['user_id']
			);
			$arr = cls_obj::get("cls_com")->msg('on_save',$arr_fields);
			return $arr;
		} else {
			return array("code" => 500 , "msg" =>"传递参数有误");
		}
	}

	function on_findpwd_step3() {
		$isverify = cls_obj::get("cls_session")->get('sms_verify');
		$key = fun_get::get("key");
		$uname = fun_get::get("uname");
		$uid = fun_get::get("uid");
		$pwd = fun_get::get("pwd");
		if($uid < 1 ) {
			$arr_user = cls_obj::get("cls_user")->get_user($uname , false);
			if(empty($arr_user) || !isset($arr_user[$uname])) return array('code' => '500' , 'msg' => '验证账号不存在');
			$uid = $arr_user[$uname];
		} else {
			$arr_user = cls_obj::get("cls_user")->get_user($uid);
			if(empty($arr_user) || !in_array($uid , $arr_user)) return array('code' => '500' , 'msg' => '验证账号不存在');
			$uname = array_search($uid , $arr_user);
		}
		if($isverify != $uid) return array("code"=>500 , "msg" => "验证已过期，请重新验证");
		
		$arr = cls_obj::get("cls_user")->on_update_pwd('' , $pwd , $uid , false);
		if($arr["code"] != 0){
			$arr_return['code']=500;
			$arr_return['msg']=$arr['msg'];
			return $arr_return;
		}
		//注销标识
		cls_obj::get("cls_session")->destroy('sms_verify');
		return array("code"=>0,"msg"=>'');
	}

	function on_verify_mobile() {
		$mobile = cls_obj::get("cls_session")->get('verify_val');
		$key = fun_get::get("key");
		$uname = fun_get::get("uname");
		$arr_user = cls_obj::get("cls_user")->get_user($uname , false);
		if(empty($arr_user) || !isset($arr_user[$uname])) return array('code' => '500' , 'msg' => '验证账号不存在');
		$arr = tab_sys_verify::on_verify($mobile , $key , 2);
		if($arr['code'] == 0) {
			$isverify = cls_obj::get("cls_session")->set('sms_verify' , $arr_user[$uname]);//设置已验证标识
		}
		return $arr;
	}
}