<?php
// +----------------------------------------------------------------------
// | yershop网店管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.yershop.com All rights reserved.
// +----------------------------------------------------------------------
// | 版权申明：yershop网店管理系统不是一个自由软件，是贝云网络官方推出的商业源码，严禁在未经许可的情况下
// | 拷贝、复制、传播、使用yershop网店管理系统的任意代码，如有违反，请立即删除，否则您将面临承担相应
// | 法律责任的风险。如果需要取得官方授权，请联系官方http://www.yershop.com
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Db;
/**
 * 文档基础模型
 */
class Order extends Model{

    public function getPageList($num,$order){
       
	     if($_REQUEST){
			foreach ($_REQUEST as $key=>$value){
				if($value){
					$value=safe_replace($value);
					$map[$key]  = array('like', '%'.$value.'%');
				 }
			}
        }
		if (isset($map['start_time']) ) {
			  unset($map['start_time']);
              $map['create_time'] = array('egt',strtotime($_POST['start_time']));
        }
        if (isset($map['end_time']) ) {
			unset($map['end_time']);
            $map['create_time'] = array('elt',strtotime($_POST['end_time']));
        }
		if(input('status')){
		   $map['status'] = input('status');
		}
		$map["uid"]=is_login();
		$p=input("page")?input("page"):1;
		$p=safe_replace($p);
        $res["list"]= Db::name("order")->where($map)->limit($num)->page($p)->order($order)->select();
		foreach($res["list"] as $n=> $val){
                $res["list"][$n]['sales']=Db::name("sales")->where('orderId=\''.$val['orderId'].'\'')->select();
		}
		$list = Db::name("order")->where($map)->order($order)->paginate($num);
		$res["page"] = $list->render();
		$res["info"] = $map;
		return $res;
    }
    public function add(){
       
	  	$uid=session_uid(); 
		$id=input('post.id');
		if(!$id){
			$this->error= "未选择商品";return false;
		}
	   	$ids=explode(",",$id);
        $map[]=["uid",'=',$uid];	
        $map[]=["sku_id","in",$ids];		
		$cart = Db::name("cart")->where($map)->select();
		if(!$cart){
			$this->error="商品不存在错误";return false;
		}
		$sum = 0;$price = 0.00;
		$sn=$this->orderId();
        $list= Db::name("cart")->where($map)->Distinct(true)->field('shop_id')->select();
		foreach($list as $k=> $v){
			unset($data);
            $data["shop_id"]= $v["shop_id"];
		    $data["uid"]= $uid;
		    $item=Db::name("cart")->where($data)->select();
            $saleslist="";$total=0;$ship_price=0.00;
			$total=0.00;$xji=0;$sum = 0;$price = 0.00;
		    foreach ($item as $key=>$val) {
			    $id=$val["sku_id"];
				$val["sku_id"]=$val["id"];
                unset($val['id']);			 
				unset($val['path']);unset($val['key']);
				$csd=$val['cart_shop_id'];
				unset($val['cart_shop_id']);
				$xji=$val['num']*$val['price'];
				$val["title"]=get_goods($val['goods_id'],"title");
				$val["total"]=$xji;
				$total+=$xji;
                //$ship_price+=get_goods($val['goods_id'],"spress");;
				$val["ship_price"]=get_goods($val['goods_id'],"spress");
				$val["orderId"]=$sn;
				Db::name("sales")->insert($val);
			    $saleslist .="{$val["title"]} {$val['specifications']} 数量{$val['num']} 单价{$val['price']} 小计$xji</br>";//标识号
				  Db::name("cart")->where($data)->delete();
                  Db::name("cart_shop")->where('id',$csd)->delete();
				  //$id=$val["sku_id"]; 
				  //dump($id);
				  $key="cart.".$id;
		          session($key,null);
				  //dump(session($key));
		    }
		
			$data["total"]=$total;
			$data["ship_price"]=$ship_price;
		    $data["total_money"]=$total+$ship_price;
		    $data["saleslist"]=$saleslist;
            $data['status']=0;
		    $data["orderId"]=$sn;
		    $data["create_time"]=time();
		    $res=Db::name("order")->insertGetId($data);     
		 }
		 return $sn;	
    }
	//立即购买
	 public function buy() {
		
		$uid=session_uid(); 
		$num=safe_replace(input('num'));
		if(!($num && is_numeric($num))){
		   $this->error='分类ID错误！';return false;
		}
		$goodsid=input('post.goodsid'); // 用intval过滤$_POST['id']
        $path=input('post.path');
		if($path){
		    $map['path']=safe_replace($path);
		}
		if($goodsid){
		    $map['goods_id']=safe_replace($goodsid);
		}
		$info=db("sku")->where($map)->find();
        if(!$info){
		   $this->error='sku不存在！';return ;
		}
		if(!$info['num']){
		   $this->error='sku库存数量为0！';return false;
		}
		$sum = 0;$price = 0.00;
		$sn=$this->orderId();
	    $val["sku_id"]=$info["id"];
		$total=$num*$info['price'];
		$val["title"]=get_goods($info['goods_id'],"title");
		$val["total"]=$total;
		$val["price"]=$info['price'];
        $val["num"]=$num;
		$val["orderId"]=$sn;
		$val["goods_id"]=$goodsid;
		$val["uid"]=$uid; 
		$val["shop_id"]=get_goods($info['goods_id'],"shop_id");
		 db("sales")->insert($val);
		 $arr=explode(',',$info['path']);$specifications="";
						   foreach($arr as $v){
						     $specifications.="&nbsp;".get_specs_title($v) ;
						   }
		 $saleslist =$val["title"] .$specifications ."数量".$val['num']."单价".$val['price']." 小计".$total."</br>";//标识号 
		 $ship_price=get_goods($info['goods_id'],"spress");
		 $data["total"]=$total;
         $data["num"]=$num;
		 $data["ship_price"]=$ship_price;
		 $data["total_money"]=$total+$ship_price;
		 $data["saleslist"]=$saleslist;
         $data["uid"]=$uid;	 
		 $data["shop_id"]=get_goods($info['goods_id'],"shop_id");
         $data['status']=-1;
		 $data["order_type"]=0;//普通订单
		 $data["orderId"]=$sn;
		 $data["create_time"]=time();
		 $res=db("order")->insertGetId($data);
		return $sn;

    }


	//积分兑换
	 public function score() {
		
		$uid=session_uid(); 
		$num=safe_replace(input('num'));
		if(!($num && is_numeric($num))){
		   $this->error='分类ID错误！';return false;
		}
		$goodsid=input('post.goodsid'); // 用intval过滤$_POST['id']
        $path=input('post.path');
		if($path){
		    $map['path']=safe_replace($path);
		}
		if($goodsid){
		    $map['goods_id']=safe_replace($goodsid);
		}
		$info=db("sku")->where($map)->find();
        if(!$info){
		   $this->error='sku不存在！';return ;
		}
		if(!$info['num']){
		   $this->error='sku库存数量为0！';return false;
		}

		$total_fee=get_goods($info['goods_id'],"score");;
		$total=$num*$total_fee;
        $where["id"]=$uid;
		$ucenter= db("ucenterMember")->where($where)->find(); 
		$account=$ucenter["score"];
			
		 //积分支付
		if($account<$total){
		    $this->error='积分不足！';return false;
		}
		$sum = 0;$price = 0.00;
		$sn=$this->orderId();
	    $val["sku_id"]=$info["id"];
	
		$val["title"]=get_goods($info['goods_id'],"title");
		$val["total"]=$total;
		$val["price"]=$info['price'];
        $val["num"]=$num;
		$val["orderId"]=$sn;
		$val["goods_id"]=$goodsid;
		$val["uid"]=$uid;
		 db("sales")->insert($val);
		 $arr=explode(',',$info['path']);$specifications="";
						   foreach($arr as $v){
						     $specifications.="&nbsp;".get_specs_title($v) ;
						   }
		 $saleslist =$val["title"] .$specifications ."数量".$val['num']."单价".$val['price']." 小计".$total."</br>";//标识号 
		 $ship_price=get_goods($info['goods_id'],"spress");
		 $data["total"]=$total;
         $data["num"]=$num;
		 $data["ship_price"]=$ship_price;
		 $data["total_money"]=$total+$ship_price;
		 $data["saleslist"]=$saleslist;
         $data["uid"]=$uid;	
         $data['status']=-1;	
		 $data["order_type"]=1;//积分订单
		 $data["orderId"]=$sn;
		 $data["create_time"]=time();
		 $res=db("order")->insertGetId($data);
		return $res;

    }

 public function upData(){

        $uid=session_uid(); 
		$map["uid"]=$uid;
		$orderId=safe_replace(input('orderId'));
		$addressid=safe_replace(input('address_id'));
		$addressid=intval($addressid);
        if(!($addressid&& is_numeric($addressid))){
		   $this->error='未选择地址！';return false;
		}
        $express=safe_replace(input('express'));
		
        if(!$express){
		   //$this->error='请选择配送方式！';return false;
		}			
		$where["id"]=$addressid;
		$where["uid"]=$uid;
		$adr= Db::name("address")->where($where)->find();
		if(!$adr){
			$this->error= "地址不存在";return false;
		}
		$map["orderId"]=$orderId;	
		$list= Db::name("order")->where($map)->select(); 
		if(!$list){
			$this->error= "订单不存在";return false;
		}
		unset($map);
		$save["addressid"]=$addressid;
		$save["username"]=$adr["username"];
        $save["mobile"]=$adr["mobile"];
		$coupon_money=0.00;$total_money=0.00;
        $save["address"]=$adr["province"].$adr["city"].$adr["area"].$adr["address"];
        foreach ($list as $n=>$val) {
			    $shop_id=$val['shop_id'];
				$couponid=(int)input("coupon".$shop_id)?(int)input("coupon".$shop_id):0;
				//$where[]=["shop_id",'=',$val["shop_id"]];
				unset($where);
			    $where[]=["status",'=',0];
				$where[]=["id",'=',$couponid];
				//$where[]=["uid",'=',$uid];
				$couponMoney=0;
				$couponId=0;
				
				$coupon=Db::name('user_coupon')->where($where)->find();
				
				if($couponid>0&&!$coupon){
					$this->error= "优惠券不存在";return false;
					
				}
				if($coupon){
					$couponMoney=$coupon['money'];
			        $couponId=$couponid;
					$update['status']=1;
					Db::name('user_coupon')->where($where)->update($update);
					
				}
			 
			   $coupon_money+=$couponMoney;
			   $save["coupon_money"]=$couponMoney;
               $save["coupon_id"]=$couponId;
			   
			   
               $save["message"]=safe_replace(input("message".$shop_id));
               $save["is_invoice"]=safe_replace(input("is_invoice"));
               $save["invoice_content"]=safe_replace(input("invoice_content"));
               $save["invoice_header"]=safe_replace(input("invoice_header"));
			   $save["invoice_type"]=safe_replace(input("invoice_type"));
			   $order_code=$this->orderId().$val["shop_id"];
			   $save["order_code"]=$order_code;
			    $save["express"]=$express;
			  	$save["submit_time"]=time();
	         	$save["expire_time"]=time() +7200;;//待支付
				$save["total_money"]=$val["total_money"]-$couponMoney;
				$total_money+=$save["total_money"];
				
				
	        	$save["status"]=0;//待支付
               unset($map);
               $map["id"]=$val["id"]; $field="order_code,address,mobile,status,
			   username,submit_time,expire_time,coupon_id,coupon_money,address_id,paytype,express,score,message,
		total_money,invoice_header,invoice_content,is_invoice,invoice_type,update_time";
		        Db::name('order')->where($map)->field($field)->update($save);
			  
			   unset($map);
			   unset($save);
               $map["shop_id"]=$shop_id;
               //$map["uid"]=$uid; 
                $map["orderId"]=$orderId; 
			  $orderId=safe_replace(input('orderId'));//dump($orderId);exit;
					       $update["order_code"]=$order_code;
						    $res=db('sales')->where($map)->field('order_code')->setField($update);
						 	$map["order_code"]=$order_code;
						 if(!db('sales')->where($map)->find()){
						  //dump(db('sales')->where($map)->find());	
						 }
					
		}  
	   
		$data["out_trade_no"]=$orderId;
		$data["total_money"]=$total_money;
		$data["coupon_money"]=$coupon_money;
		$data["uid"]=session_uid();
		$data["create_time"]=time()+7200;
		$data["paytype"]=0;
		$data["type"]=2;
		$data["model"]="order";//模型为订单
		$id=Db::name("pay")->insertGetId($data);
		return $id;

}
 public function  getTotalSn($sn=""){
        if(!session_uid()) {
		    $this->redirect("User/login");
		}			
		$uid=session_uid();	
		$map['uid']=$uid;//用户id
		$map["orderId"]=$sn;
		$total=0.0;$ship_price=0.00;$total_money=0.0;
        $data = Db::name("order")->where($map)->select();
        foreach ($data as $k=>$val) {
            $ship_price += $val['ship_price'];
            $total+= $val['total']; 
			$total_money+= $val['total_money'];
        }
		$info["total"]=sprintf("%01.2f", $total);
		$info["ship_price"]=sprintf("%01.2f", $ship_price);
		$info["total_money"]=sprintf("%01.2f", $total_money);
        return $info;
     }
   public function orderId_old(){
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'input', 'J');
		$orderId = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%04d%02d', rand(1000, 9999),rand(0,99));
		return $orderId;
	}

    // 生成支付订单号
   public function orderId(){
        if ( is_login() ) {
		      $uid=is_login();
		      $code=date('Ymd',time()).time().$uid;
	       return $code;
		}
    }
	public function confirm(){
		
       	$id=safe_replace(input("id"));
		if(!$id){
			 $this->error="未选择数据！";return false;
		}
		$map[]=['id',"in",$id];
		$map[]=['uid','=',session_uid()];
		$map[]=["status",'=',2];
		$list=Db::name("order")->where($map)->select();
        if (!$list) {
			$this->error="订单不存在或存在不支持确认的订单";
		}
		$data["status"]=3;  
		$data["confirm_time"]=time() ;//确认时间 
		unset($map["status"]); 
		$res=Db::name("order")->where($map)->update($data);
       	if($res) { 
			unset($data);
              foreach ($list as $k=>$item) {
                  $where["id"]=$item["shop_id"];
                  $shop=Db::name("shop")->where($where)->find();
				  $uid=$shop["uid"];
				  $where2["id"]=$uid;
				  $user=Db::name("user")->where($where2)->find();
			      $data["account"]=$user["account"]+$item["total_money"];
                  Db::name("user")->where($where)->field('account')->update($data);
                }
			
			return true;
		}else{
		   return false;
		}	
     }
}
