<?php
/**
 * 平台自有配送
 * 版本：1.0
 * 日期：2018-07-19
 */
namespace Common\Vendor\Distribute;
class Local{
    private $config;
    /**
     * 构造函数
     */
    public function __construct($config){
        $this->config = !empty($this->config) && !empty($config)? array_merge($this->config, $config):!empty($config)?$config:$this->config;
    }
    /**
     * 新增订单
     * @param array(
     *      [shop_no]=>门店编号不能为空,
     *      [origin_id]=>第三方订单ID不能为空,
     *      [city_code]=>订单所在城市的code不能为空,
     *      [cargo_price]=>订单金额不能为空, 
     *      [expected_fetch_time]=>期望取货时间不能为空, 
     *      [receiver_name]=>收货人姓名不能为空, 
     *      [receiver_address]=>收货人地址不能为空, 
     *      [receiver_lat]=>收货人地址维度不能为空, 
     *      [receiver_lng]=>收货人地址经度不能为空, 
     *      )
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function add_order($data){
        $data=$data[0];
        $return=array('status'=>0,'info'=>array());
        if(empty($data)){return $return;}
        if($data['type'] == 20){
            $data['type'] = 2;
            $pao_order = M('PaotuiInfo')->where(array('order_id'=>$data['id']))->find();
        }else{
            $pao_order = array();
            $data['type'] = 1;
        }
        $datas = array(
            'origin_id'=> $order_sn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
            'order_sn'=> $data["order_sn"],
            'type'=>$data['type'],     //1外卖，2跑腿
            'cargo_price'=>$data['goods_allmoney'],
            'uid'=> $data['uid'],
            'consignee'=> $data['consignee'],
            'address'=> $data['address'],
            'getaddress'=>idtoname($data['location_id'],'ShopsLocation','address'),
            'tips'=> 0,
            'mobile'=> $data['mobile'],
            'email'=> $data['email'],
            'xpoint'=> $data['xpoint'],
            'ypoint'=> $data['ypoint'],
            'info'=> $data['temp'],
            'location_id'=> $data['location_id'],
            'shop_id'=> $data['shop_id'],
            'shipping_status'=> 1,//配送状态1待接单,2已接单,3配送中4已送达
            'addtime'=>NOW_TIME,
            'status'=>2,
            'shopaddress'=>$pao_order['city'].$pao_order['district'].$pao_order['shopaddress'],
            'q_xpoint'=>$pao_order['xpoint'],
            'q_ypoint'=>$pao_order['ypoint'],
            'ordertypes'=>$pao_order['type'],
        );
        if(!$datas['shop_id'] && $datas['type']!=2){$return['msg'] = '门店编号不能为空!';}
        if(!$datas['origin_id']){$return['msg'] = '第三方订单ID不能为空!';}
        if(!$datas['cargo_price']){$return['msg'] = '订单金额不能为空!';}
        if(!$datas['consignee']){$return['msg'] = '收货人姓名不能为空!';}
        if(!$datas['address']){$return['msg'] = '收货人地址不能为空!';}
        if(!$datas['ypoint']){$return['msg'] = '收货人地址纬度不能为空!';}
        if(!$datas['xpoint']){$return['msg'] = '收货人地址经度不能为空!';}
        if($return['msg']){
            $return['status'] = 0;
            return $return;
        }
        //请求接口
        $reqStatus = M("LocalOrder")->add($datas);
        if($reqStatus>0){
            //添加关联表
            $map=array();$map['id']=$reqStatus;
            $sdata[0] = M('LocalOrder')->field("id,origin_id,order_sn,accept_time,fetch_time,finish_time,cancel_time,statusCode,cancel_from,cancel_reason")->where($map)->find();
            $sdata[0]['delivery_fee']=$data['delivery_fee'];
            $this->notify_order($sdata);
            $return['status'] = 1;
            $return['info']['order_id'] = $reqStatus;
        }
        return $return;
    }
    /**
     * 重新推单，暂时接口默认为重新生成订单
     */
    public function readd_order($data){
        $datas = $data[0];
        $sav['is_delete'] = 1;
        M('TakeawayOrder')->where(array('order_code'=>$datas['order_sn']))->save($sav);
        return $this->add_order($data);
    }
    /**
     * 第三方回调
     */
    public function notify_order($data){
        $data = $data[0];
        if(empty($data['update_time']))$data['update_time']=NOW_TIME;
        $adds=array();
        $adds['order_code'] = $data['origin_id'];
        $adds['order_id'] = $data['order_sn'];
        $adds['order_status'] = $data['shipping_status'];
        $adds['cancel_reason'] = $data['cancel_reason'];
        $adds['cancel_from'] = $data['cancel_from'];
        if($data['add_time'])$adds['add_time'] = $data['add_time'];
        $adds['update_time'] = $data['update_time'];
        $adds['dm_id'] = intval($data['knight_id']);
        $adds['dm_name'] = $data['knightname'];
        $adds['dm_mobile'] = $data['knightphone']; 
        $adds['delivery_fee'] = $data['delivery_fee'];  
        $adds['delivery_money'] = $data['delivery_fee'];  
        if($data['accept_time'])$adds['accept_time'] = $data['accept_time'];      
        $adds['marking'] = 'Local';
        $map=array();
        $map['order_code']=$data['origin_id'];
        $map['marking']='Local';
        $count = M('TakeawayOrder')->where($map)->count();
        if($count<=0){
            $adds['add_time'] =NOW_TIME;
            $adds['expire_time'] =NOW_TIME+(60*60*24*7);
            $res = M('TakeawayOrder')->add($adds);
        }else{
            //if($data['shipping_status'] == 1)$adds['accept_time'] = $adds['update_time'];//待接单时间
            //if($data['shipping_status'] == 2)$adds['accept_time'] = $data['accept_time'];//接单时间
            if($data['shipping_status'] == 3)$adds['fetch_time'] = $data['fetch_time'];//开始配送时间
			// 备份 start
            // if($data['shipping_status'] == 4){//已完成时间
                // $adds['finish_time'] = $data['finish_time'];
                // $save_data['shipping_status'] = 4;
                // $save_data['status'] = 3;
                // M('OrderInfo')->where(array('order_sn='=>$data['order_sn']))->save($save_data);
            // };
            // if($data['shipping_status'] == 5)$adds['cancel_time'] = $adds['update_time'];//已取消时间
            // if($data['shipping_status'] == 7)$adds['expire_time'] = $adds['update_time'];//已过期时间
            // $res = D('TakeawayOrder')->where(array('order_code'=>$data['origin_id']))->save($adds);
			// 备份 end
			// 修改 start
			if($data['shipping_status'] == 4){
				//已完成时间
                $adds['finish_time'] = $data['finish_time'];
                $save_data = array();$save_data['shipping_status'] = 4;
                $save_data['status'] = 3;$save_data['finish_time'] = $data['finish_time'];
				$map = array();$map['order_sn'] =$data['order_sn'];$map['shipping_status'] =array('neq',4);
                M('OrderInfo')->where($map)->save($save_data);
            }
            if($data['shipping_status'] == 5)$adds['cancel_time'] = $adds['update_time'];//已取消时间
            if($data['shipping_status'] == 7)$adds['expire_time'] = $adds['update_time'];//已过期时间
			$map = array();$map['order_code'] = $data['origin_id'];
            $res = D('TakeawayOrder')->where($map)->save($adds);
			// 修改 end
        }
        if($res) {
            $return['status'] = 1;
        }else{
            $return['msg'] = "同步订单信息失败";
        }   
        return $return;
    }
    /**
     * 订单详情查询
     * @param $order_id:第三方订单号
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function details_order($orderid){
        $return = array("status"=>0,'info'=>array());
        $orderid = $orderid[0];
        $map=array();
        $map['order_sn'] = $orderid;
        $reqStatus = M('LocalOrder')->where($map)->order("id desc")->find();
        if(!$reqStatus){
            $return['info']['errorCode'] = "无此订单";return;
        }
        $map=array();
        $map['order_id'] = $orderid;
        $map['marking'] = 'Local';
        $order_status=M('TakeawayOrder')->where($map)->order("id desc")->find();
        $three_ship_status=array('1'=>'待接单',2=>'待取货',3=>'配送中',4=>'已送达',5=>'已取消',7=>'已过期',8=>'指派单');
        //配送状态1待接单,2已接单,3配送中4已送达
        $reqStatus['statusMsg'] =$three_ship_status[$order_status['order_status']];
        $reqStatus['transporterName'] = $order_status['dm_name'];
        $reqStatus['transporterPhone'] = $order_status['dm_mobile'];        
        
        if($order_status['add_time'])$reqStatus['createTime'] = time_format($order_status['add_time']);
        if($order_status['accept_time'])$reqStatus['acceptTime'] = time_format($order_status['accept_time']);
        if($order_status['fetch_time'])$reqStatus['fetchTime'] = time_format($order_status['fetch_time']);
        if($order_status['finish_time'])$reqStatus['finishTime'] = time_format($order_status['finish_time']);
        
        if($reqStatus['knight_id'] != 0){
            $knights = M('Knight')->field("truename,umobile")->where(array('id'=>$reqStatus['knight_id']))->find();
            $reqStatus['transporterName'] = $knights['truename'];
            $reqStatus['transporterPhone'] = $knights['umobile'];
            $reqStatus['deliveryFee'] = $reqStatus['cargo_price'];
            $reqStatus['createTime'] = time_format($reqStatus['addtime']);
            $reqStatus['acceptTime'] = time_format($reqStatus['accept_time']);
            $reqStatus['fetchTime'] = time_format($reqStatus['fetch_time']);
            $reqStatus['finishTime'] = time_format($reqStatus['finish_time']);
        }
        $return['info'] = $reqStatus;
        $return['status'] = 1;
        return $return;
    }    
    /**
     * 取消订单：当商户将订单推送给配送开放平台后，可根据需要调用同步取消订单接口对订单进行取消操作。目前，商户只能在“配送中”     
     * 状态前进行取消，一旦订单状态已经进入“配送中”状态，之后将不允许商户再取消该订单。
     * @param $order_sn  第三方订单号
     */
    public function cancel_order($order_sn){
        $order_sn = $order_sn[0];
        $sav['order_status'] = 4;
        $sav['cancel_reason'] = $data['order_cancel_description'];
        $sav['cancel_time'] = $data['order_cancel_time'];
        $result= D('TakeawayOrder')->where(array('order_id'=>$order_sn,'is_delete'=>0))->save($sav);
        if($result!==false){
            return true;
        }else{
            return false;
        }
    }
    public function shop_add($postdata=''){return true;}//添加门店
    public function shop_update($postdata=''){return true;}//修改门店
}
?>