<?php

namespace Home\Model;
use Think\Model;
use Common\Model\MemberModel;
use Common\Model\OrderGoodsModel;
use Org\Sms;
use Org\Mac;

/**
 * 订单模型
 */
class OrderModel extends Model{

    protected $_validate = array(
    	array('out_trade_no', 'require', '{%order_num_empty}', self::MUST_VALIDATE , 'regex', self::MODEL_BOTH),
    	array('out_trade_no', '', '{%order_num_exsit}', self::EXISTS_VALIDATE, 'unique'),
    );

    protected $_auto = array(
        array('createtime', NOW_TIME, self::MODEL_INSERT),
    	array('status', '1', self::MODEL_INSERT),

    );


    public function createOrder($data,$level=1){
    	$data['body'] = '';
    	$goods = $data['goods'];

    	if(!$goods){
    		$this->error = L('select_laundry');
    		return false;
    	}

    	$total_fee = 0;

    	$goods_arr = array();
    	foreach ($goods as $k=>$g){
    		$info = M('Goods')->find($g['id']);
    		$goods_arr[$k]['id'] = $g['id'];
    		$goods_arr[$k]['num'] = $g['num'];
    		$goods_arr[$k]['title'] = $info['title'];
    		$goods_arr[$k]['price'] = $info['price'];
    		$goods_arr[$k]['cate'] = $info['cate'];

    		$total_fee += $info['price']*$g['num'];
    	}
    	if ($data['total_fee']!=$total_fee) {
    		$this->error = L('order_amount_error');
    		return false;
    	}
    	$data['pay_fee'] = $data['total_fee'];

    	$mem = new MemberModel();
    	$memInfo = $mem->getInfoById($data['userid']);


    	if($data['balance']){
    	    $data['balance'] = $memInfo['amount'];
    	}
    	if($data['credits']){
    		if($memInfo['credits']<$data['credits']){
    			$this->error = L('points_not_enough');
    			return false;
    		}
    	}
    	if($data['coupon_id']){
    	    if(is_numeric($data['coupon_id'])){
    	        $obj_coupon = D('MemberCoupon');
    	    }else{
    	        $obj_coupon = D('WeixinCoupon');
    	    }
    	    $coupon_info = $obj_coupon->getInfo($data['coupon_id']);
    	    if($coupon_info)
    	        $data['coupon'] = $coupon_info['money'];
    	    else
    	        $data['coupon'] = 0;
    	}
    	//优惠券
    	if($data['coupon']){
    	    $data['pay_fee'] = $data['total_fee']-$data['coupon'];
    	}
    	if($data['pay_fee']>0){
    	    //其次使用积分
    	    $ratio = C('jifen_ratio');
    	    $credits = $data['credits']/$ratio;

    	    if($data['pay_fee']>$credits){
    	        $data['pay_fee'] = $data['pay_fee']-$credits;

    	        if($data['pay_fee']<=$data['balance']){

    	            $data['balance'] = $data['pay_fee'];
    	            $data['pay_fee'] = 0;
    	        }else{
    	            $data['pay_fee'] = $data['pay_fee']-$data['balance'];
    	        }
    	    }else{
    	        $data['balance'] = 0;
    	        $data['credits'] = $data['pay_fee']*$ratio;
    	    }

    	}else{
    		$data['pay_fee'] = 0;
    		$data['credits'] = 0;
    	    $data['balance'] = 0;
    	}


    	$data['body'] = json_encode($goods_arr);

    	//file_put_contents('order.log', json_encode($data));

    	if($order = $this->create($data)){
    		if($this->add($order)){
    		    //保存洗衣明细
    		    $obj_orderGoods = new OrderGoodsModel();
    		    $obj_orderGoods->saveGoods($order);
    		    //将优惠券设为已用
    		    if($data['coupon_id']){
    		        if(is_numeric($data['coupon_id'])){
    		            $obj_coupon->setUsed($data['coupon_id']);
    		        }else{
    		            $obj_coupon->setUsed($data['coupon_id']);
    		        }
    		    }

    			//更新用户积分
    		    if($data['credits'])
    			     $mem->updateCredits($data['userid'], -$data['credits']);
    			//更新用户积分
    		    if($data['balance'])
    			     $mem->updateAmount($data['userid'], -$data['balance']);

    			$return['pay_fee'] = $data['pay_fee'];
    			$return['out_trade_no'] = $data['out_trade_no'];

    			return $return;
    		}
    		else{
    			$this->error = L('place_order_fail');
    			return false;
    		}
    	}else{
    		$this->error = L('place_order_fail');
    		return false;
    	}

    }


    public function getInfo($key,$value){
    	return $this->where(array($key=>$value))->find();
    }

    public function getPayStatus($out_trade_no){
    	$info = $this->where(array('out_trade_no'=>$out_trade_no))->field('pay_status')->find();
    	return $info['pay_status'];
    }


    public function getBox($out_trade_no){
    	$info = $this->where(array('out_trade_no'=>$out_trade_no))->find();
    	if(empty($info))
    		return '';
    	else
    		return $info['box'];
    }


    public function setBox($out_trade_no, $box, $mac_id){
    	$map['out_trade_no'] = $out_trade_no;
    	$data['box'] = $box;
    	$res = $this->where($map)->save($data);

    	if($res){
    		$where['mac_id'] = $mac_id;
    		$where['num'] = array('in',$box);
    		M('MachineBox')->where($where)->save(array('is_used'=>1));
    		return true;

    	}else{
    		return false;
    	}
    }





}
