<?php
/**
 * 物流推送
 *
 *
 *
 *
 * by Jeff Wan
 */

defined('InShopNC') or exit('Access Invalid!');

require_once (BASE_CORE_PATH . '/framework/function/http.php');

class deliveryLogic
{
    const oms_url = 'http://oapi.lrlz.com/lrlzApiRest/router/rest';
    //const oms_url = 'http://oapitest.lrlz.com/lrlzApiRest/router/rest';


    private static $appkey = '2015panda';
    private static $appPassWord = 'nEs5vu86JSjh89WPW4de2d3e87rwli3e8rw';

    private function sign($data) {
        return md5(self::$appkey . self::$appPassWord . $data);
    }

    public function putOrder($pay_sn, $trade_no,$log_fail = true)
    {
        Log::record(__METHOD__ . " {$pay_sn} {$trade_no}",Log::DEBUG);
        // 调试模式下不能推送到oms
        if(defined('OMS_PUSH_OFF') && OMS_PUSH_OFF == true) {
            return false;
        }

        $order_list = Model('order')->getNormalOrderList(array('pay_sn'=> $pay_sn), $this->page, '*', 'order_id desc', '', array('order_address', 'order_goods'),true);
        if(empty($order_list)) {
            Log::record("putOrder:cannot get order list when pay_sn={$pay_sn},trade_no={$trade_no} ",Log::DEBUG);
            return false;
        }

        $order_sn = '';
        $delivery_order_list = array();
        foreach ($order_list as $order_info)
        {
            if ($order_info['order_state'] === '20')
            {
                $nick_name = $order_info['reciver_name'];

                $delivery_order = array();
                $order_sn = $order_info['order_sn'];
                $delivery_order['tid'] = $order_info['order_sn'];
                $delivery_order['total_fee'] = $order_info['order_amount'];
                $delivery_order['discount_fee'] = '';
                $delivery_order['post_fee'] = $order_info['shipping_fee'];
                $delivery_order['created'] = date('Y-m-d H:i:s', $order_info['add_time']);
                $delivery_order['pay_time'] = date('Y-m-d H:i:s',$order_info['payment_time']);
                $delivery_order['buyer_message'] = '';
                $delivery_order['express_code'] = '';
                $delivery_order['pay_account_type'] = $order_info['payment_code'] == 'wxpay' ? '微信支付': '支付宝';
                $delivery_order['pay_account_id'] = '';
                $delivery_order['pay_account_no'] = $trade_no;
                $delivery_order['buyer_nick'] = $nick_name;
                $delivery_order['buyer_email'] = $order_info['buyer_email'];
                $delivery_order['trade_memo'] = '';
                $delivery_order['receiver_name'] = $order_info['reciver_name'];

                $delivery_area =  explode("\t", $order_info['reciver_info']['area']);
                $delivery_order['receiver_state'] = $delivery_area[0];
                $delivery_order['receiver_city'] = $delivery_area[1];
                $delivery_order['receiver_district'] = $delivery_area[2];

                Log::record("{$delivery_order['receiver_state']} {$delivery_order['receiver_city']} {$delivery_order['receiver_district']}",Log::DEBUG);

                $delivery_order['receiver_address'] = $order_info['reciver_info']['street'];
                $delivery_order['receiver_zip'] = '000000';
                $delivery_order['receiver_mobile'] = $order_info['reciver_info']['mob_phone'];
                $delivery_order['receiver_phone'] = $order_info['reciver_info']['tel_phone'];
                $delivery_order['order_size'] = count($order_info['extend_order_goods']);


                $delivery_order['orderList'] = array();

                foreach($order_info['extend_order_goods'] as $key => $goods)
                {
                    $delivery_goods = array();
                    $delivery_goods['oid'] =  $order_info['order_sn'] . $key;
                    $delivery_goods['tid'] =  $order_info['order_sn'];
                    $delivery_goods['title'] =  $goods['goods_name'];
                    $delivery_goods['price'] =  $goods['goods_price'];
                    $delivery_goods['num'] =  $goods['goods_num'];
                    $goods_serial = Model('goods')->getGoodsInfo(array('goods_id'=>$goods['goods_id']));
                    $delivery_goods['outer_sku_id'] = $goods_serial['goods_serial'];
                    $delivery_goods['outer_sku_properties_name'] = $goods['goods_name'];
                    $delivery_goods['buyer_nick'] = $nick_name;
                    array_push($delivery_order['orderList'] , $delivery_goods);
                }
                array_push($delivery_order_list, $delivery_order);
            }
        }
        // 订单状态不对
        if (empty($delivery_order_list) || count($delivery_order_list) == 0) {
            Log::record("putOrder: pay_sn={$pay_sn}, 错误原因: 订单状态不对",Log::ERR);
            return false;
        }

        $data = array('type' => 'PUT_TRADE', 'data' => $delivery_order_list);
        $body = json_encode($data,JSON_UNESCAPED_UNICODE);
        $sign = $this->sign($body);
        $headers = array('v_appkey: '.self::$appkey, 'v_sign: '.$sign, 'Content-Type: application/json');
        $resp = http_post_data(self::oms_url,urlencode($body),$headers);

        if($resp === false)
        { //网络出现异常时,后台重新推送
            if($log_fail) {
                $log = array();

                $log['pay_sn'] = $pay_sn;
                $log['order_sn']  = $order_sn;
                $log['trade_no'] = $trade_no;
                $log['push_time'] = time();
                $log['order_status'] = 0;

                Model('omsfail')->insert($log);
            }

            return false;
        }

        $success = $this->check($resp,$err_state,$reson);
        if($success == false)
        {
            Log::record("post data={$resp}",Log::ERR);
            if($log_fail) {
                $log = array();

                $log['pay_sn'] = $pay_sn;
                $log['order_sn']  = $order_sn;
                $log['trade_no'] = $trade_no;
                $log['push_time'] = time();
                $log['reson'] = $reson;
                $log['order_status'] = $err_state;
                $log['oms_response'] = $resp;

                Model('omsfail')->insert($log);
            }
            return false;
        } else {
            return true;
        }
    }

    public function handleCallback($param)
    {
        $model_order = Model('order');
        $condition = array('order_sn' => $param['order_sn']);
        $order_info = $model_order->getOrderInfo($condition,array('order_common','order_goods'));
        $model_express = Model('express');
        $express_info = $model_express->getExpressInfoByOMS($param['oms_code']);
        $data['reciver_name'] = $order_info['reciver_name'];
        $data['reciver_info'] = $order_info['reciver_info'];
        $data['deliver_explain'] = $order_info['deliver_explain'];
        $data['daddress_id'] = intval($order_info['daddress_id']);
        $data['shipping_express_id'] =intval($express_info['express_id']);
        $data['shipping_code']  = $param['shipping_code'];
        $logic_order = Logic('order');
        $result = $logic_order->changeOrderSend($order_info, 'seller', $order_info['buyer_name'], $data);
        return $result;
    }

    public function cancel_oms($order_sn)
    {
        $param = array('type' => 'TRADE_INTERCEPT','data' => array('tids' => $order_sn,'remark' => '用户退款'));
        $body = json_encode($param,JSON_UNESCAPED_UNICODE);
        $sign = $this->sign($body);
        $headers = array('v_appkey: '.self::$appkey, 'v_sign: '.$sign, 'Content-Type: application/json');
        $resp = http_post_data(self::oms_url,urlencode($body),$headers);
        if($resp === false) {
            Log::record(__METHOD__ . " NET Error",Log::ERR);
            return false;
        }
        else {
            Log::record($resp,Log::DEBUG);
        }

        return true;
    }

    /**
     * @param $pay_sn
     * @param $trade_no
     * @param $result
     * @param $order_sn
     * @return mixed
     */
    private function check($resp,&$err_state,&$reson)
    {

        $err_state = 0;

        //1：成功 0 ：失败
        // 1：新订单 2：等待仓库处理 99：已拦截 90：库存不足 7：已发货
        // -99：发货失败 -2：订单关闭 -3：订单已存在(没有进行拦截的订单不予更新) -1：异常订单 -2：订单关闭
        $result = json_decode($resp, true);
        if (!empty($result) && is_array($result))
        {
            if ($result['apiCode'] == 'success')
            {
                if (!empty($result['data']) && is_array($result['data']) && count($result['data']) > 0)
                {
                    // 填充错误理由
                    $reson = $result['data'][0]['errorMessge'];
                    if (!empty($result['data'][0]['status'])) {
                        $status = intval($result['data'][0]['status']);
                        if ($status == 1 || $status == 2 || $status == 3 || $status == 7 || $status == 99) {
                            return true;
                        }
                    } else {
                        $msg = $result['data'][0]['errorMessge'];
                        if (strstr($msg, '订单已存在')) {
                            return true;
                        } else {
                            $err_state = 2;
                        }
                    }
                }
            }
        }

        return false;
    }
}