<?php

namespace Business\Order;

use Business\Store\StoreServiceModel;
use DAO\Order\OrderCommonModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Order\OrderConfirmUtil;
use Our\ApiConst;
use Our\ArrayConst;
use Our\Common;
use Our\DbNameConst;
use Our\DescribeConst;
use Our\ExpressConst;
use Our\ImageConst;
use Our\NameConst;
use Our\PageConst;
use Our\Push;
use Our\RedisHelper;
use Our\WechatCommon;

/**
 * 店铺service
 *
 * @date 2018-5-15
 * @author zhz
 */
class OrderServiceModel extends \Business\AbstractModel
{
    private $orderField = "order_id as orderId,order_sn as orderSn,store_name as storeName,evaluation_state as evaluationState,add_time as addTime,store_id as storeId,goods_amount as goodsAmount,shipping_fee as shippingFee,order_amount as orderAmount,shipping_type as shippingType,payment_type as paymentType,payment_time as paymentTime,order_state as orderState,shipping_fee as shippingFee,refund_state as refundState,order_type as orderType,is_receive_payment as isReceivePayment,gmt_update as gmtUpdate";
    private $orderGoodsField = "order_id as orderId,rec_id as recId,store_id as storeId,goods_id as goodsId,goods_name as goodsName,goods_price as goodsPrice,goods_num as goodsNum,goods_image as goodsImage,goods_pay_price as goodsPayPrice,sale_act_id as saleActId,sale_id as saleId,comment_state as commentState,is_refund as isRefund,goods_spec as goodsSpec,refund_state_name as refundStateName,refund_id as refundId";

    private $addressField = " mob_phone as MobPhone,tel_phone as TelPhone,address as address,area_info as areaInfo,lng,lat,address_id as addressId,subaddress as subAddress";

    private $storeField = "offline_payway as offlinePayway";

    private $orderMessageField = "order_id as orderId,order_sn as orderSn,store_name as storeName,add_time as addTime,store_id as storeId,goods_amount as goodsAmount,shipping_fee as shippingFee,order_amount as orderAmount,shipping_type as shippingType,payment_type as paymentType,order_state as orderState,shipping_fee as shippingFee,refund_state as refundState,order_type as orderType,is_receive_payment as isReceivePayment,buyer_id as buyerId,buyer_name as buyerName,accept_time as acceptTime";


    public $order;
    //地址
    private $address;
    //收货人地址
    //收货人信息
    private $orderCommon;
    //定单商品表
    private $orderGoodsList;
    private $diliveryman;
    //商店相关信息
    private $store;

    public function init()
    {

    }


    private function getGoodsDetailField()
    {
        return $this->orderGoodsField . ',goods_commonid as goodsCommonId,goods_commonid as goodsCommonid,goods_group as goodsGroup';
    }

    /**
     * 获取小程序表单
     * User: King <358887571@qq.com>
     * Date: 2018/12/27 0027
     * Time: 下午 3:15
     */
    private function getLitAccesstoken(){
        $model_wx  = \DAO\MbWxModel::getInstance();
        $weixin = $model_wx->getOne('id,lit_appid,lit_appsecret,lit_accesstoken,lit_expirestime', 'id=1');
        $access_token = '';
        if (!$weixin['lit_expirestime'] || $weixin['lit_expirestime'] < time()) {
            $access_info = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $weixin['lit_appid'] . '&secret=' . $weixin['lit_appsecret']), true);
            if (isset($access_info['access_token'])) {
                $access_token = $access_info['access_token'];

                $update_data = array();
                $update_data['lit_accesstoken'] = $access_info['access_token'];
                $update_data['lit_expirestime'] = TIMESTAMP + $access_info['expires_in'] - 1800;

                $where = array('id' => $weixin['id']);
                $result = $model_wx->update($update_data, $where);
            }
        } else {
            $access_token = $weixin['lit_accesstoken'];
        }
        return $access_token;
    }

    /**
     * 发送付款消息
     * @param $order
     * @param $msg_tpl
     * User: King <358887571@qq.com>
     * Date: 2019/1/3 0003
     * Time: 上午 11:01
     */
    public function sendPaymentMessage($order, $msg_tpl) {
        $model = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $model_member = \DAO\MemberModel::getInstance(DbNameConst::salveDBConnectName);
        $model_order_goods = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $wechatCommon = WechatCommon::getInstance();
        $access_token = $wechatCommon->getAccessToken();
        if($access_token && ($member = $model_member->getOneByMemberId($order['buyer_id'], array('member_id', 'member_wxappopenid')
            ))) {
            $where = array('order_id'=>$order['order_id']);
            $goods_datas = $model_order_goods->getOrderGoods($where, 'order_id, goods_name');
            $goods_str = '';
            if(count($goods_datas)>1) {
                $goods_str .= $goods_datas[0]['goods_name'].'等' .count($goods_datas).'件商品';
            } else {
                $goods_str .= $goods_datas[0]['goods_name'];
            }
            $req_data = array('touser'=>$member['member_wxappopenid'], 'template_id'=> $msg_tpl,
                'form_id'=> $order['prepay_id'],
                'page'=> 'pages/orders/detail/index?id='.$order['order_id'],
                'data'=>array(
                    'keyword1'=>array('value'=>$order['order_sn']),
                    'keyword2'=>array('value'=>$order['store_name']),
                    'keyword3'=>array('value'=>$goods_str),
                    'keyword4'=>array('value'=>number_format($order['order_amount']/100, 2).'元'),
                    'keyword5'=>array('value'=>date('Y-m-d H:i',$order['payment_time'])),
                    'keyword6'=>array('value'=>'已付款'),
                ));
            $json = $wechatCommon->sendTemplateMessage($access_token, $req_data);

            \Our\Log::getInstance()->write($order['order_id'].'payment'.json_encode($json), '/data/log/apptest');
            if($json['errmsg']=='ok') {
                $model->updateByOrderId(array('msg_status'=>2), $order['order_id']);
//                echo 'order[' . $order['order_id'] .'] send payment succ'."\n";
                return true;
            }
        }
        return false;
    }

    public function sendShippingMessage($order, $msg_tpl) {
        $model = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $model_member = \DAO\MemberModel::getInstance(DbNameConst::salveDBConnectName);
        $model_order_goods = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $wechatCommon = WechatCommon::getInstance();
        $access_token = $wechatCommon->getAccessToken();
        $common_model = \DAO\Order\OrderCommonModel::getInstance();
        if($access_token && ($member = $model_member->getOneByMemberId($order['buyer_id'], array('member_id', 'member_wxappopenid')
            ))) {
            $sub_data = $common_model->findByOrderId($order['order_id'], 'reciver_name, reciver_info');
            $address = '';
            if($sub_data['reciver_info']) {
                $reciver_info = unserialize($sub_data['reciver_info']);
                $address = $reciver_info['address'].$reciver_info['subaddress'];
            }
            $where = array('order_id'=>$order['order_id']);
            $goods_datas = $model_order_goods->getOrderGoods($where, 'order_id, goods_name');
            $goods_str = '';
            if(count($goods_datas)>1) {
                $goods_str .= $goods_datas[0]['goods_name'].'等' .count($goods_datas).'件商品';
            } else {
                $goods_str .= $goods_datas[0]['goods_name'];
            }
            $req_data = array('touser'=>$member['member_wxappopenid'], 'template_id'=> $msg_tpl,
                'form_id'=> $order['prepay_id'],
                'page'=> 'pages/orders/detail/index?id='.$order['order_id'],
                'data'=>array(
                    'keyword1'=>array('value'=>date('Y-m-d H:i', $order['add_time'])),
                    'keyword2'=>array('value'=>date('Y-m-d H:i', $order['send_time'])),
                    'keyword3'=>array('value'=>$order['order_sn']),
                    'keyword4'=>array('value'=>$address),
                    'keyword5'=>array('value'=>$order['store_name']),
                    'keyword6'=>array('value'=>$goods_str),
                    'keyword7'=>array('value'=>number_format($order['order_amount']/100, 2).'元'),
                ));
//                    \Our\Log::getInstance()->write(json_encode($req_data), '/data/log/apptest');

            $json = $wechatCommon->sendTemplateMessage($access_token, $req_data);
            if($json['errmsg']=='ok') {
                $model->updateByOrderId(array('msg_status'=>3), $order['order_id']);
//                echo 'order[' . $order['order_id'] .'] send shipping succ'."\n";
                return true;
            }

        }
        return false;

    }

    public function sendReceiveMessage($order, $msg_tpl) {
        $model = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $model_member = \DAO\MemberModel::getInstance(DbNameConst::salveDBConnectName);
        $model_order_goods = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $wechatCommon = WechatCommon::getInstance();
        $access_token = $wechatCommon->getAccessToken();
        $store_model = \DAO\StoreModel::getInstance();
        if($access_token && ($member = $model_member->getOneByMemberId($order['buyer_id'], array('member_id', 'member_wxappopenid')
            ))) {
            $where = array('order_id'=>$order['order_id']);
            $goods_datas = $model_order_goods->getOrderGoods($where, 'order_id, goods_name');
            $goods_str = '';
            if(count($goods_datas)>1) {
                $goods_str .= $goods_datas[0]['goods_name'].'等' .count($goods_datas).'件商品';
            } else {
                $goods_str .= $goods_datas[0]['goods_name'];
            }
            $store_data = $store_model->getFieldsInfo(array('store_id'=>$order['store_id']), 'store_phone');
            $shipping_type = '';
            switch ($order['shipping_type']) {
                case 1:
                    $shipping_type .= '商家配送';
                    break;
                case 2:
                    $shipping_type .= '快递配送';
                    break;
                default:
                    $shipping_type .= '到店自提';
                    break;
            }
            $req_data = array('touser'=>$member['member_wxappopenid'], 'template_id'=> $msg_tpl,
                'form_id'=> $order['prepay_id'],
                'page'=> 'pages/orders/detail/index?id='.$order['order_id'],
                'data'=>array(
                    'keyword1'=>array('value'=>$order['order_sn']),
                    'keyword2'=>array('value'=>date('Y-m-d H:i', $order['send_time'])),
                    'keyword3'=>array('value'=>date('Y-m-d H:i', $order['finnshed_time'])),
                    'keyword4'=>array('value'=>$order['store_name']),
                    'keyword5'=>array('value'=>$store_data['store_phone']),
                    'keyword6'=>array('value'=>$goods_str),
                    'keyword7'=>array('value'=>number_format($order['order_amount']/100, 2).'元'),
                    'keyword8'=>array('value'=>$shipping_type),
                    'keyword9'=>array('value'=>'您购买的商品已被签收，如不是您本人签收，请尽快联系商家'),
                ));
//                    \Our\Log::getInstance()->write(json_encode($req_data), '/data/log/apptest');

            $json = $wechatCommon->sendTemplateMessage($access_token, $req_data);
            if($json['errmsg']=='ok') {
                $model->updateByOrderId(array('msg_status'=>4), $order['order_id']);
//                echo 'order[' . $order['order_id'] .'] send reciver succ'."\n";
                return true;
            }

        }
        return false;
    }

    /**
     * 发送模板消息
     *
     * User: King <358887571@qq.com>
     * Date: 2018/12/28 0028
     * Time: 上午 11:31
     */
    public function sendTemplateMessage()
    {
        $model = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $settingDAO = \DAO\SettingModel::getInstance();
        $wxapp_templates = $settingDAO->getListCache(array('wxapp_order_paysucc_tpl', 'wxapp_order_shipping_tpl', 'wxapp_order_receive_tpl'));

        //付款7天内付款消息通知
        $where  = array('msg_status'=>array('elt', 1), 'payment_type'=>5, 'order_state'=>array('egt',20), 'prepay_id'=>
            array('neq',
            ''), 'payment_time'=>array('between', TIMESTAMP-7*24*60*60, TIMESTAMP-10));
        if($list = $model->getList($where, 'order_id,order_sn, store_name, buyer_id, order_amount, payment_time, order_state, prepay_id', 0, 10, array('payment_time'=>'asc'))) {
            echo 'order count: '.count($list['list'])."\n";
            $msg_tpl = $wxapp_templates['wxapp_order_paysucc_tpl'];
            foreach ($list['list'] as $order) {
//                \Our\Log::getInstance()->write('order:'.json_encode($order), '/data/log/apptest');
                $this->sendPaymentMessage($order, $msg_tpl);
            }
        }
        echo "do payment\n";
        //付款7天内订单发货通知
        $where  = array('msg_status'=>2, 'payment_type'=>5, 'shipping_type'=> array('in', array(1, 2)), 'order_state'=>
            array('egt', 30), 'prepay_id'=>
            array('neq',
                ''), 'payment_time'=>array('gt', TIMESTAMP-7*24*60*60), 'send_time'=>array('lt',
            TIMESTAMP-10));
        if($list = $model->getList($where, 'order_id,order_sn,store_id,store_name,buyer_id,order_amount,add_time, send_time, order_state, prepay_id', 0, 10, array('send_time'=>'asc'))) {
            echo ' order num: '.count($list['list'])."\n";
            $msg_tpl = $wxapp_templates['wxapp_order_shipping_tpl'];
            foreach ($list['list'] as $order) {
//                \Our\Log::getInstance()->write('order:'.json_encode($order), '/data/log/apptest');
                $this->sendShippingMessage($order, $msg_tpl);
            }
        }
        echo "do shipping\n";

        //付款7天内订单确认收货通知
        $where  = array('msg_status'=>3, 'payment_type'=>5, 'order_state'=>
            array('egt', 40), 'prepay_id'=>
            array('neq',
                ''), 'payment_time'=>array('gt', TIMESTAMP-7*24*60*60), 'finnshed_time' => array('lt', TIMESTAMP-15));
        if($list = $model->getList($where, 'order_id,order_sn,store_id,store_name,buyer_id, shipping_type,order_amount,add_time, send_time, finnshed_time, order_state, prepay_id', 0, 10, array('finnshed_time'=>'asc'))) {
            echo ' order num: '.count($list['list'])."\n";
            $msg_tpl = $wxapp_templates['wxapp_order_receive_tpl'];
            foreach ($list['list'] as $order) {
                if($order['shipping_type']==0) {
                    $order['send_time'] = $order['finnshed_time'];
                }
                $this->sendReceiveMessage($order, $msg_tpl);
            }
        }
        echo "do reciver\n";

    }

    public function getOrderIndexWhere($memberId, $keyword, $pageIndex, $pageSize)
    {
//        $query1= array('match' => array('buyerId' => $memberId));
//        $res1['must']=$query1;
//        $query2[]= array('match' => array('orderSn' => $keyword"));
//        $query2[]= array('match' => array('storeName' => $keyword));
//        $query2[]= array('match' => array('goodsName' => $keyword));
//        $res1['should']=$query2;
        //     $allQuery['bool']=$res1;
        $query1[] = array('match' => array('buyerId' => $memberId));
        $query1[] = array('match' => array('deleteState' => ApiConst::undeleteOrder));
        $res1['must'][0] = $query1;
        // $query2[]= array('match' => array('orderSn' => $keyword"));
        $query2[] = array('match' => array('storeName' => $keyword));
        $query2[] = array('match' => array('goodsName' => $keyword));
        $query2[] = array('match' => array('orderSn' => "$keyword"));
        //   $query2[] = array('wildcard' => array('orderSn' => "*{$keyword}*"));
        $res1['must'][1]['bool']['should'] = $query2;
        $allQuery['bool'] = $res1;
        // echo json_encode($allQuery);exit;
        // echo json_encode($allQuery);exit;
        //array_push($allQuery['bool'],$res2);
        // echo json_encode($allQuery);exit;
        //  echo json_encode($allQuery);exit;
        $elasticTool = \Elastics\ElasticsToolModel::getInstance(NameConst::ordersIndex);
        $res = $elasticTool->searchMatch($allQuery, $pageIndex, $pageSize);
        $orderIdsField = array_column($res['list'], 'orderId');
        $orderIds = implode(',', $orderIdsField);
        if ($orderIds) {
            $where = Common::format(" order_id in({0})",  $orderIds);
        }else{
            $where=false;
        }
        return $where;
    }

    /**
     * 订单,获得订单列表
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getList($memberId, $keyWord = false, $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize, $orderState = false)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        //$refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        if ($keyWord !== false) {
            $where = $this->getOrderIndexWhere($memberId, $keyWord, $pageIndex, $pageSize);
            if($where===false){
                return Array(
                    'orders'=>[],
                    'totalCount'=>ApiConst::zero,
                );
            }
        } else {
            $where['delete_state'] = ApiConst::undeleteOrder;

            $where['buyer_id'] = $memberId;
            //$where['lock_state'] = ApiConst::zero;

            if ($orderState != false) {
                if($orderState==ApiConst::orderStateComplete){
                    $where['evaluation_state']=ApiConst::waitEvaluation;
                    $where['order_state']=array('eq',ApiConst::orderStateComplete);
                }elseif($orderState==ApiConst::orderStateWaitRecieveOne || $orderState==ApiConst::orderStateWaitRecieve){
                    $where['shipping_type']=array('eq',ApiConst::bySeller);
                    $where['order_state'] =array('in',array(ApiConst::orderStateWaitSend,ApiConst::orderStateWaitRecieve));
                }elseif($orderState==ApiConst::orderStateWaitSendOne){
                    $where['shipping_type']=array('eq',ApiConst::bySelf);
                    $where['order_state']=array('eq',ApiConst::orderStateWaitRecieve);
                }else{
                    $where['order_state'] = array('eq', $orderState);
                }
            }
        }

        //获得订单列表
        $orders = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'getList'), array($where, $this->orderField, $pageIndex, $pageSize, $order = array('gmt_update' => 'desc')), \Our\ApiConst::oneDaySecond, array($memberId));
        if (!empty($orders['list'])) {
            $orderIds = array_column($orders['list'], 'orderId');
            //获得订单商品列表
            if (!empty($orderIds)) {
                $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderIds, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond, array($memberId));
                $orderMerge = Common::intergrateOneToMany($orders['list'], $orderGoods, 'orderId', 'orderId', 'orderGoods');
                foreach ($orderMerge as &$value) {
                    $value['orderStateName'] = $orderDao->getStatusText($value);
                    $value['orderText'] = $orderDao->getText($value, ApiConst::orderListDescribe);
//                    if ($value['lock_state'] == 0) {
//                        $value['refunStateName'] = NameConst::emptyString;
//                    } else {
//                        if(!empty($value['orderGoods'])){
//
//                        }
//                        $value['refunsStateName'] = $refundReturnDao->getStatusText($value['orderId']);
//                    }
                    if (!empty($value['orderGoods'])) {
                        $value['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($value['orderGoods']);
                    } else {
                        $value['totalGoodsNum'] = ApiConst::zero;
                    }
                    //$value['blId'] = isset($value['blId']) ? (!is_null($value['blId']) ? $value['blId'] : ApiConst::zero) : ApiConst::zero;
                    if (isset($value['orderGoods'])) {
                        $value['orderGoods'] = $goodsDao->convert($value['orderGoods']);
                    } else {
                        $value['orderGoods'] = array();
                    }
                }
                $returnData['orders'] = $orderMerge;
                $returnData['totalCount'] = $orders['totalCount'];
                return $returnData;
            } else {
                return Array(
                    'orders'=>[],
                    'totalCount'=>ApiConst::zero,
                );
            }
        } else {
            return Array(
                'orders'=>[],
                'totalCount'=>ApiConst::zero,
            );
        }


    }

    public function getDeleteField()
    {
        return $this->orderField . ',delete_state as deleteState';
    }

    public function delete($memberId, $orderId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $order = $orderDao->findByMemberIdAndOrderId($memberId, $orderId, $this->getDeleteField());
        if (empty($order)) {
            ErrorModel::throwException(CodeConfigModel::orderNotExist);
        }
        if ($orderDao->getOrderOperateState(NameConst::delete, $order)) {
            if ($orderDao->deleteByOrderId($order['orderId'])) {
                $orderDao->deleteOrderCache($memberId, $orderId);
                $memberDao->deleteTotalCache($memberId);
                return true;
            } else {
                ErrorModel::throwException(CodeConfigModel::orderDeleteError);
            }
        }else{
            ErrorModel::throwException(CodeConfigModel::notAllowCancel);
        }

    }


    private function getDeliveryManFields()
    {
        return array(
            'qrcode_path' => 'qrcodePath',
            'true_name' => 'trueName',
            'mobile' => 'mobile',
        );
    }

    /**
     * 订单,获得订单详情
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getOrderDetail($orderId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $addressDao = \DAO\AddressModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $diliverymanDao = \DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        $storeDao = \DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        //订单
        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond,array($orderId));
        if(!$order){
            ErrorModel::throwException(CodeConfigModel::orderNotExist);
        }
        $fields = $orderDao->getFields();
        $this->order = $orderDao->getConvertOrder($order, $fields);
        //收货人地址
        //收货人信息
        $this->orderCommon = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderCommonDao, 'findByOrderId'), array($orderId, $orderCommonDao->orderCommonField), \Our\ApiConst::oneDaySecond,array($orderId));
        //$this->orderCommon = $orderCommonDao->findByOrderId($orderId, $this->orderCommonField);
        $reciverInfo = $this->orderCommon['reciverInfo'];
        $reciverInfo = unserialize($reciverInfo);
        $reciverInfo['true_name'] = $this->orderCommon['reciverName'];
        $this->address = $orderCommonDao->getReciverInfo($reciverInfo);
//        if ($this->orderCommon['daddressId'] > ApiConst::zero) {
//            $this->address = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$addressDao, 'getAddressByAddressId'), array($this->orderCommon['daddressId'], $this->addressField), \Our\ApiConst::oneDaySecond);;
//            $this->address['lat'] = $this->address['lat'] ? $this->address['lat'] : ApiConst::zero;
//            $this->address['lng'] = $this->address['lng'] ? $this->address['lng'] : ApiConst::zero;
//            $this->address['subAddress'] = $this->address['subAddress'] ? $this->address['subAddress'] : '';
//        } else {
//            $this->address = new \stdClass();
//        }
        //定单商品表

        $this->orderGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderId, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond, array($orderId));
        //商店相关信息
//         $this->store=$storeDao->get($this->order['storeId']);
//        $this->store=Common::convertUnderline($this->store[0]);
        $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($this->order['storeId'], $storeDao->detailField), \Our\ApiConst::sevenDaySecond,array($this->order['storeId']));
        $returnData = $this->order;
        //配送员信息
        $this->diliveryman = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$diliverymanDao, 'findById'), array($returnData['diliverymanId']), \Our\ApiConst::oneDaySecond);
        //地址
        $returnData['shippingName'] = $orderDao->getShippingName($returnData['shippingType']);
        $returnData['orderMessage'] = $this->orderCommon['orderMessage'];
        $returnData['shippingFeeName'] = $orderDao->getFreightFeeName($returnData['shippingType']);
        $returnData['dlyoPickupCode'] = substr($returnData['orderSn'], ApiConst::positionPickupCodeBegin);
        $returnData['paymentName'] = $orderDao->getPayTypeName($returnData['paymentType']);
        $returnData['discountAmount'] = $returnData['goodsAmount'] - $returnData['orderAmount'] + $returnData['shippingFee'];
        $returnData['orderText'] = $orderDao->getStatusDetailText($this->order);
        $returnData['orderExtentText'] = $orderDao->getText($this->order, ApiConst::orderDetailDescribe);
        $returnData['couponId'] = $returnData['couponId'] ? $returnData['couponId'] : ApiConst::zero;
        $returnData['shippingTime'] = $this->orderCommon['shippingTime'];
        if ($returnData['diliverymanId']) {
            $returnData['deliveryman'] = $diliverymanDao->convert($this->diliveryman, $this->getDeliveryManFields());
            if(empty($returnData['deliveryman']['qrcodePath'])){
                $returnData['deliveryman']['qrcodePath']='';
            }
        } else {
            $returnData['diliverymanId'] = ApiConst::zero;
            $returnData['deliveryman'] = new \stdClass();
        }

        if(CURRENTVERSION!=NameConst::versionDefault){
            if(!in_array($this->order['paymentType'],ArrayConst::payTypeOnlines)){
                $returnData['offlinePayway']=$storeDao->convertOfflinePayway($this->store['offlinePayway']);
            }else{
                $returnData['offlinePayway']=new \stdClass();
            }

        }else{
            $returnData['offlinePayway']='';
        }

        $returnData['storeMemberId']=$this->store['memberId'];
        $returnData['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($this->orderGoodsList);
        // $returnData['offlinePayway'] =$this->store['offlinePayway'] ? $this->store['offlinePayway'] : '';
        $this->address['address']=$orderCommonDao->convertReceiveAddress($this->address['address']);
        $returnData['reciverInfo'] = $this->address;
        $returnData['reciverInfo']['mobPhone']=!empty($returnData['reciverInfo']['mobPhone'])?$returnData['reciverInfo']['mobPhone']:'';
        $returnData['reciverInfo']['telPhone']=!empty($returnData['reciverInfo']['telPhone'])?$returnData['reciverInfo']['telPhone']:'';
        $returnData['reciverInfo']['lng']=!empty($returnData['reciverInfo']['lng'])?$returnData['reciverInfo']['lng']:ApiConst::zero;
        $returnData['reciverInfo']['lat']=!empty($returnData['reciverInfo']['lat'])?$returnData['reciverInfo']['lat']:ApiConst::zero;
        $refundStateName = $orderDao->getRefundText($this->order);
        $returnData['orderGoods'] = $goodsDao->convert($this->orderGoodsList, $refundStateName);
        return $returnData;
    }


    /**
     * 取消订单
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function cancel($orderId, $memberId = false)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $order = $orderDao->findByOrderId($orderId,$orderDao->getOrderDetailField());
        $waitReceiveCount=ApiConst::zero;
        $waitDeliveryCount=ApiConst::zero;
        $waitGetCount=ApiConst::zero;
        if(in_array($order['orderState'],array(ApiConst::orderStateWaitSend,ApiConst::orderStateWaitRecieve))){
            if($order['shippingType']==ApiConst::bySelf){
                $waitGetCount=ApiConst::reduceOne;
            }
            if($order['shippingType']==ApiConst::bySeller){
                $waitDeliveryCount=ApiConst::reduceOne;
            }
        }
        if($order['orderState']==ApiConst::orderStateWaitConfirm){
            $waitReceiveCount=-1;
        }


        $storeDao=\DAO\StoreModel::getInstance();
        //判断订单目前状态是否允许取消
        $isAllowCancel = $orderDao->isAllowCancel($order);
        //$isAllowCancel = true;
        if ($isAllowCancel) {
            $orderDao->db->doTransaction();
            $res = $orderDao->updateStatusByOrderId($orderId, ApiConst::orderStateCancel,false,ApiConst::cancelOrderBySelf);
            $orderDao->setDb($orderDao->dbName);
            if ($res) {
                $updateOrder=$this->updateOrderGoodsStoregeByOrderIds(array($orderId));
                if(!$updateOrder){
                    $orderDao->db->doRollback();
                    ErrorModel::throwException(CodeConfigModel::updateGoodsStorageFail);
                };
                $order['refundOrderNo']=$refundReturnDao->getRefundsn($order['storeId']);
                if($order['paymentTime']>ApiConst::zero && in_array($order['paymentType'],ArrayConst::orderPayTypeOnlines)){
                    $resultRefund=$refundReturnDao->refundMoney($order);
                    if($resultRefund){
                        $where['order_id']=$order['orderId'];
                        //$orderGoodsUpdateData['refund_state_name']='退款成功';
                        $orderGoodsUpdateData['is_refund']=ApiConst::refundSuccess;
                        $orderGoodsDao->update($where,$orderGoodsUpdateData);

                    }else{
                        $orderDao->db->doRollback();
                        ErrorModel::throwException(CodeConfigModel::cancelRefundMoneyError);
                    }
                }
                $orderDao->db->doCommit();
                $push=\Our\Push::getInstance();
                $pushData=array('storeId'=>$order['storeId'],
                    'type'=>ApiConst::messageWaitReceive,
                    'waitReceiveCount'=>$waitReceiveCount,
                    'waitDeliveryCount'=>$waitDeliveryCount,
                    'waitGetCount'=>$waitGetCount,
                    'orderCount'=>ApiConst::reduceOne,
                    'waitRefundProccessCount'=>ApiConst::zero,
                    'waitRefundReceiveCount'=>ApiConst::zero,
                    'refundCount'=>ApiConst::zero,
                    'alertCount'=>ApiConst::zero,
                    'params'=>array('c'=>'shopkeeper',
                        'm'=>'orderDetail',
                        'orderId'=>$order['orderId']));
                $push->addOneToClient($pushData);
                $push->sendTcpMessage();
                //\Our\RedisHelper::rpush('client_push',array('storeId'=>$order['storeId'],'type'=>ApiConst::messageWaitReceive,'op'=>NameConst::reduce,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'orderDetail','orderId'=>$order['orderId'])));
                if ($memberId) {
                    $orderDao->deleteOrderCache($memberId, $orderId, $order['storeId'],true);
                    $storeDao->deleteStoreCache($order['storeId'],$orderId);
                    // $memberDao->fromOrderStateToOrderState($memberId,$order['order_state'],ApiConst::orderStateCancel);
                }
            }
            return $res;
        } else {
            ErrorModel::throwException(CodeConfigModel::notAllowCancel);
        }

    }

    public function cancelOne(){
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderData['storeId']=11;
        $orderData['subMchId'] = '1517943841';
        $orderData['paySn'] =  '280595075137008428';
        $orderData['transactionId'] = '4200000191201811099414332980';
        $orderData['buyerId'] = 428;
        $resultRefund=$refundReturnDao->refundMoney($orderData);
    }

    //确认收货
    public function confirmRecieve($orderId, $memberId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        // $orderDao->deleteOrderCache($memberId, $orderId);
        $order = $orderDao->findByOrderId($orderId);
        $storeDao=\DAO\StoreModel::getInstance();
        //$orderDao->deleteOrderCache($memberId, $orderId, $order['store_id'],true,true);
        //判断订单目前状态是否允许取消
        $isAllowConfirm = $orderDao->isAllowConfirm($order);
        if ($isAllowConfirm) {
            $res = $orderDao->updateStatusByOrderId($orderId, ApiConst::orderStateComplete, TRUE);
            if ($res) {
                if($order['shipping_type']==ApiConst::bySelf){
                    $type=ApiConst::messageWaitGet;
                }else{
                    $type=ApiConst::messageWaitSend;

                }
                $push=\Our\Push::getInstance();
                $pushData=array('storeId'=>$order['store_id'],
                    'type'=>ApiConst::messageWaitReceive,
                    'waitReceiveCount'=>ApiConst::zero,
                    'waitDeliveryCount'=>($type==ApiConst::messageWaitSend)?ApiConst::reduceOne:ApiConst::zero,
                    'waitGetCount'=>($type==ApiConst::messageWaitGet)?ApiConst::reduceOne:ApiConst::zero,
                    'orderCount'=>ApiConst::reduceOne,
                    'waitRefundProccessCount'=>ApiConst::zero,
                    'waitRefundReceiveCount'=>ApiConst::zero,
                    'refundCount'=>ApiConst::zero,
                    'alertCount'=>ApiConst::zero,
                    'params'=>array('c'=>'shopkeeper',
                        'm'=>'orderDetail',
                        'orderId'=>$order['order_id']));
                $push->addOneToClient($pushData);
                $push->sendTcpMessage();
                if($order['prepay_id'] != '') {
                    $order['finnshed_time'] =TIMESTAMP;
                    if($order['shipping_type']==0) {
                        $order['send_time'] =TIMESTAMP;
                    }
                    $settingDAO = \DAO\SettingModel::getInstance();
                    $wxapp_templates = $settingDAO->getListCache(array('wxapp_order_receive_tpl'));
                    $msg_tpl = $wxapp_templates['wxapp_order_receive_tpl'];

                    $this->sendReceiveMessage($order, $msg_tpl);    //发送收货小程序模板消息
                }

                //  \Our\RedisHelper::rpush('client_push',array('storeId'=>$order['storeId'],'type'=>$type,'op'=>NameConst::reduce,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'orderDetail','orderId'=>$order['orderId'])));
                $orderDao->deleteOrderCache($memberId, $orderId, $order['store_id'],true,true);
                $storeDao->deleteStoreCache($order['storeId'],$order['orderId']);
                return true;
            } else {
                ErrorModel::throwException(CodeConfigModel::receiveError);
            }
        } else {
            ErrorModel::throwException(CodeConfigModel::notAllowComplete);
        }
    }

    public function getOrderExpressField()
    {
        return $this->orderField . ',shipping_html as shippingHtml,shipping_code as shippingCode,send_time as sendTime,shipping_sign as shippingSign,shipping_status as shippingStatus,shipping_arrival_time as shippingArrivalTime';
    }

    //获得物流信息
    public function getExpressInfo($orderId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoods = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $expressDao = \DAO\Order\ExpressModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsCommonDao = \DAO\GoodsCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $shippingExpress = $orderCommonDao->findByOrderId($orderId, 'shipping_express_id as shippingExpressId');
        if (!empty($shippingExpress)) {
            $shippingExpressInfo = $expressDao->getInfoById($shippingExpress['shippingExpressId'], $expressDao->detailField);
        } else {
            $shippingExpressInfo = new \stdClass();
        }

        $order = $orderDao->findByOrderId($orderId, $this->getOrderExpressField());
        if(empty($order)){
            return new \stdClass();
        }
        $eCode=$shippingExpressInfo['eCode'];
        $shippingCode=$order['shippingCode'];
        $order['shippingHtml']=$order['shippingHtml'] ? unserialize($order['shippingHtml']) : array();;
        $expressResult=Common::aliyunExpressApi($shippingCode,$eCode);
        if($order['shippingOver']!=ApiConst::one){
            if($expressResult['status']==ApiConst::getExpressSuccess){
                $order['shippingHtml']=$expressResult['result']['list'];
                $listData['orderId']=$order['orderId'];
                $listData['expressInfo']=$expressResult['result'];
                RedisHelper::rpush(NameConst::expressList,$listData);
            }
        }
        $orderGoods = $orderGoods->getOneByOrderId($orderId, $this->orderGoodsField);
        if (!empty($order) && !empty($orderGoods)) {
            $return['shippingCode'] = $order['shippingCode'];
            $return['expressName'] = $shippingExpressInfo['eName'];
            $return['expressImage'] = Common::getStaticFile($shippingExpressInfo['eImage'], ImageConst::expressPath);
            $return['goodsName'] = $orderGoods['goodsName'];
            $return['goodsId'] = $orderGoods['goodsId'];
            $return['goodsImage'] = \Our\ImageUtil::getGoodsImgUrl($orderGoods['goodsImage'], ArrayConst::goodsImageExt[ApiConst::goodsSmallSize]);
            $return['goodsAttr'] = $goodsDao->getFormatGoodsAttr($orderGoods['goodsSpec']);
            $return['orderPrice'] = $order['orderAmount'];
            $return['expressInfo'] = !empty($order['shippingHtml'])?$order['shippingHtml']:[];
            $return['shippingStatus'] = $order['shippingStatus'];
            $return['sendTime'] = $order['sendTime'];
            $return['rechedTime'] = $order['shippingSign'];
            $return['shippingArrivalTime'] = $order['shippingArrivalTime'];
            return $return;
        } else {
            return new \stdClass();
        }

    }

    public function pushRecieveOrder($order){
        $push =new Push();
        $push->recieveWait($order['storeId'], $order['orderId'], $order['orderSn']);
        $pushData=array('storeId'=>$order['storeId'],
            'type'=>ApiConst::messageWaitReceive,
            'waitReceiveCount'=>ApiConst::one,
            'waitDeliveryCount'=>ApiConst::zero,
            'waitGetCount'=>ApiConst::zero,
            'orderCount'=>ApiConst::one,
            'waitRefundProccessCount'=>ApiConst::zero,
            'waitRefundReceiveCount'=>ApiConst::zero,
            'refundCount'=>ApiConst::zero,
            'alertCount'=>ApiConst::zero,
            'params'=>array('c'=>'shopkeeper',
                'm'=>'orderDetail',
                'orderId'=>$order['orderId']));
        $push->addOneToClient($pushData);
        // \Our\RedisHelper::rpush('client_push',array('storeId'=>$order['storeId'],'type'=>ApiConst::messageWaitReceive,'op'=>NameConst::add,'num'=>ApiConst::one,'params'=>array('c'=>'shopkeeper','m'=>'orderDetail','orderId'=>$order['orderId'])));
        $push->sendTcpMessage();
        $messageService=\Business\Message\MessageServiceModel::getInstance(\Our\DbNameConst::masterDBConnectName);
        $messageService->addMessageCenterToDb();
        return true;
    }
    //推送接单消息到店铺
    public function pushRecieveWaitOrder()
    {
        $baseConfDir = \Our\Common::getConfig('out.config');
        $savePath = $baseConfDir . \Our\PathConst::orderWaitRecieveTaskAddTime;
        $messageService=\Business\Message\MessageServiceModel::getInstance();
        $addTime = file_get_contents($savePath);
        $addTime = $addTime ? $addTime : ApiConst::zero;
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $pageBegin = PageConst::taskPageBegin;
        $push = Push::getInstance();
        do {
            $orders = $orderDao->getRecieveOrders(ApiConst::orderStateWaitConfirm, $addTime, $pageBegin, PageConst::taskPageSize);
            foreach ($orders['list'] as $order) {
                $push->recieveWait($order['storeId'], $order['orderId'], $order['orderSn']);

            }
            $pageBegin++;
        } while (!empty($orders['list']));
        $push->sendTcpMessage();
        $messageService->addMessageCenterToDb();
        file_put_contents($savePath, TIMESTAMP);
    }

    //推送确认收货消息到用户 和配送
    public function pushConfirmOrder()
    {
        $baseConfDir = \Our\Common::getConfig('out.config');
        $savePath = $baseConfDir . \Our\PathConst::orderConfirmTaskAddTime;
        $addTime = file_get_contents($savePath);
        $addTime = $addTime ? $addTime : ApiConst::zero;
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliverymanLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
        $pageBegin = PageConst::taskPageBegin;
        $push = Push::getInstance();
        do {
            $orders = $orderDao->getRecieveOrders(ApiConst::orderStateWaitRecieve, $addTime, $pageBegin, PageConst::taskPageSize, 'send_time');
            foreach ($orders['list'] as $order) {
                if($order['shippingType']==ApiConst::bySelf){
                    $push->reacheRemind($order['buyerId'], $order['orderId'], $order['orderSn']);
                }
                if($order['shippingType']==ApiConst::express && $order['shippingOver']==ApiConst::shippingOver){
                    $push->reacheRemind($order['buyerId'], $order['orderId'], $order['orderSn']);
                }
            }

            $pageBegin++;
        } while (!empty($orders['list']));
        $push->sendTcpMessage();
        file_put_contents($savePath, TIMESTAMP);
    }
    public function refundReturnMessage(){

    }
    public function changeOrderStateCancelUnconditional($orderInfo)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $refundReturnDao = \DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao=\DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        // $orderGoods=$orderGoodsDao->getOrderGoodsByOrderIds($orderInfo['orderId']);
        try {
            $orderId = $orderInfo['orderId'];
            $update=array();
            $refundSn = $refundReturnDao->getRefundsn($orderInfo['storeId']);
            //生成退款记录
            $update['order_id'] = $orderInfo['orderId'];
            $update['order_sn'] = $orderInfo['orderSn'];
            $update['refund_sn'] = $refundSn;
            $update['store_id'] = $orderInfo['storeId'];
            $update['store_name'] = $orderInfo['storeName'];
            $update['buyer_id'] = $orderInfo['buyerId'];
            $update['buyer_name'] = $orderInfo['buyerName'];
            $update['goods_id'] = ApiConst::zero;
            $update['goods_name'] = '订单商品全部退款';
            $update['refund_amount'] = $orderInfo['orderAmount'];
            $update['seller_state'] = 2;
            $update['refund_state'] = 3;
            $update['goods_state'] = 5;
            $update['add_time'] = time();
            $waitDiff=(ApiConst::orderStateWaitConfirmBeyond/ApiConst::oneMinSecond);
            $update['reason_info'] = '用户付款' . $waitDiff . '分钟内，店铺未接单,自动取消订单';
            $update['buyer_message'] = '用户付款' . $waitDiff. '分钟内，店铺未接单,自动取消订单';
            $update['is_suc_refund'] = 1;
            //$res = $refundReturnDao->addRefundReturn($update);
            $res=true;
            if (!$res) {
                echo '退款记录:' . json_encode($orderInfo) . '写入失败!!' . "\r\n";
            }else{
//                $param['refundOrderNo'] = $refundSn;
//                //这个有可能多次退款的时候要变
//                $param['outTradeNo'] = $orderInfo['paySn'];
//                $param['totalFee'] = $orderInfo['orderAmount'];
//                $param['refundFee'] = $orderInfo['orderAmount'];//全额退款
//                $param['storeId']=$orderInfo['storeId'];
//                $param['buyerId']=$orderInfo['buyerId'];
//                if (intval($orderInfo['paymentType']) == ApiConst::wxAppPayType) {
//                    $wxpay = \Payment\WxPay::getInstance();
//                    $refund_return = $wxpay->refund($param);
//                    echo "微信返回:".json_encode($refund_return);
//                    if (!($refund_return['return_code'] == 'SUCCESS' && $refund_return['result_code'] == 'SUCCESS')) {
//                        echo '微信退款操作执行失败！'.$orderInfo['orderId']."\r\n";
//                        return false;
//                    }
//                } else if (intval($orderInfo['paymentType']) == ApiConst::alipay) {
//                    $aliPay=\Payment\Alipay::getInstance();
//                    $return = $aliPay->refund($param);
//                    echo "支付宝返回:".json_encode($return);
//                    $resultCode = $return->code;
//                    if(!empty($resultCode)&&$resultCode == 10000){
//                        return true;
//                    } else {
//                        echo '支付宝退款操作执行失败:'.$orderInfo['orderId']."\r\n";
//                        return false;
//                    }
//                }
                $orderInfo['refundOrderNo']=$refundSn;
                $refundRes=$refundReturnDao->refundMoney($orderInfo);
                if($refundRes){
                    $where['order_id']=$orderInfo['orderId'];
                    //$orderGoodsUpdateData['refund_state_name']='退款成功';
                    $orderGoodsUpdateData['is_refund']=1;
                    $orderGoodsDao->update($where,$orderGoodsUpdateData);
                    echo " 退款操作操作成功:".$orderId;
                    return true;
                }else{
                    echo $refundReturnDao->errorMessage."orderId:".$orderId;
                    return false;
                }
                $orderDao->update(array('order_id' =>$orderInfo['orderId']),array('order_note'=>$refundReturnDao->errorMessage));


            }


        } catch (Exception $e) {
           echo $e->getMessage().$e->getCode();
            return false;
        }
    }

    public $baseDir;

    //订单任务脚本关闭订单
    public function cancelOrderTask()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::masterDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $orderConfirmUtilDao=OrderConfirmUtil::getInstance(DbNameConst::masterDBConnectName);
        $beginTime = file_get_contents($this->baseDir . \Our\PathConst::orderCancelTime);
        $beginTime = $beginTime ? $beginTime : ApiConst::zero;
        $endTime = TIMESTAMP - ApiConst::orderCancelBeyondTime;
        $storeDao=\DAO\StoreModel::getInstance();
        $orders = $orderDao->getMustCecelOrders($beginTime, $endTime, $orderDao->getOrderDetailField());
        if (!empty($orders)) {

            foreach ($orders as $order) {

                //更新订单信息
                $updateData = array('order_state' => ApiConst::orderStateCancel,'is_effective'=>ApiConst::cancelOrderAuto);
                $update = $orderDao->update(array('order_id' => $order['orderId']),$updateData);
//                $updateCommonData['order_message']=DescribeConst::cancelOrderMessage;
//                $res=$orderCommonDao->update(array('order_id'=>$order['orderId']),$updateCommonData);
//                if(!$update || !$res){
//                    echo '订单:'.$order['orderId'].'没取消成功!';
//                }
                if(!$update){
                    echo '订单:'.$order['orderId'].'没取消成功!';
                }
                //$orderGoodsUpdateData['refund_state_name']='退款成功';
                $orderGoodsUpdateData['is_refund']=1;
                $whereOrderGoods['order_id']=$order['orderId'];
                $orderGoodsUpdateRes=$orderGoodsDao->update($whereOrderGoods,$orderGoodsUpdateData);
                if(!$orderGoodsUpdateRes){
                    echo '订单:'.$order['order_id'].'is_refund'.'没更新成功';
                }
                $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
                $storeDao->deleteStoreCache($order['storeId'],$order['orderId']);
            }
            $orderIds = array_column($orders, 'orderId');
            //更新商品库存
            $orderGoods = $orderGoodsDao->getOrderGoodsByOrderIds($orderIds, $this->getGoodsDetailField());
            $storeCartsList=array();
            $storeCarts=array();
            $storeCarts['storeCarts']=array();
            foreach($orderGoods as $orderGood){
                $orderGood['type']=!empty($orderGood['goodsGroup'])? \Our\ApiConst::addBundingToCart:\Our\ApiConst::addGoodsToCart;
                $orderGood['goodsNum']=$orderGood['goodsNum'];
                $orderGood['goodsList']=\Our\Common::isSerialized($orderGood['goodsGroup'])?unserialize($orderGood['goodsGroup']):array();
                array_push($storeCarts['storeCarts'],$orderGood);
            }
            if(!empty($storeCarts['storeCarts'])){
                array_push($storeCartsList,$storeCarts);
            }
            // $orderDao->updateNotRecieveOrders(ApiConst::orderStateWaitConfirm, ApiConst::orderStateClose, 'add_time', ApiConst::orderStateWaitConfirmBeyond, $this->orderMessageField);
            try{
                $orderConfirmUtilDao->updateGoodsStorage($storeCartsList,\Our\ApiConst::plus);
            }catch(\Exception $ex){
                $orderidsStr=implode(',',array_column($orders,'orderId'));
                echo '商品库存更新失败:'.$ex->getMessage().$ex->getCode().":".$orderidsStr;
            }
//            //发送消息
//            $push = Push::getInstance();
//            $push->pushOrderCloseMessage($orders);

        }
        file_put_contents($this->baseDir . \Our\PathConst::orderCancelTime, $endTime);
    }
    public function changeOrderStatusSecond($bTime=false)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $endTime = file_get_contents($this->baseDir . \Our\PathConst::orderCloseWaitRecieveOrder);
        $endTime = $endTime ? $endTime : ApiConst::zero;
        $beginTime = $endTime - ApiConst::tenDaySecond;
        $storeDao=\DAO\StoreModel::getInstance();
        if($bTime){
            $beginTime=0;
        }
        // $beginTime=0;
        $orders = $orderDao->getMustCecelRecieveOrders($beginTime, $endTime, $orderDao->getOrderDetailField());
        $newOrders=array();
        $orderIds=array();
        if (!empty($orders)) {
            foreach ($orders as $order) {
                $orderDao->setDb(DbNameConst::masterDBConnectName);
                $orderDao->db->doTransaction();
                //更新订单信息
                $updateData = array('order_state' => ApiConst::orderStateClose,'refund_amount'=>$order['orderAmount'],'gmt_update'=>TIMESTAMP,'is_effective'=>ApiConst::closeOrder);
                $update = $orderDao->update(array('order_id' => $order['orderId']),$updateData);
                if($update){
                    if ($order['paymentTime'] > ApiConst::zero && in_array($order['paymentType'], ArrayConst::orderPayTypeOnlines)) {
                        $isRefunMoney= $this->changeOrderStateCancelUnconditional($order);
                        if(!$isRefunMoney){
                            $orderDao->db->doRollback();
                            continue;
                        }
                    }
                    array_push($orderIds,$order['orderId']);
                    $this->updateOrderGoodsStoregeByOrderIds($orderIds);
                    array_push($newOrders,$order);
                    $orderIds=array();
                    $orderDao->db->doCommit();
                    $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
                    $storeDao->deleteStoreCache($order['storeId'],$order['orderId']);
                    $push=\Our\Push::getInstance();
                    $pushData=array('storeId'=>$order['storeId'],
                        'type'=>ApiConst::messageWaitReceive,
                        'waitReceiveCount'=>ApiConst::reduceOne,
                        'waitDeliveryCount'=>0,
                        'waitGetCount'=>0,
                        'orderCount'=>ApiConst::reduceOne,
                        'waitRefundProccessCount'=>ApiConst::zero,
                        'waitRefundReceiveCount'=>ApiConst::zero,
                        'refundCount'=>ApiConst::zero,
                        'alertCount'=>ApiConst::zero,
                        'params'=>array('c'=>'shopkeeper',
                            'm'=>'orderDetail',
                            'orderId'=>$order['orderId']));
                    $push->addOneToClient($pushData);
                }
//                $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
//                $storeDao->deleteStoreCache($order['storeId'],$order['orderId']);
//                $push=\Our\Push::getInstance();
//                $pushData=array('storeId'=>$order['storeId'],
//                    'type'=>ApiConst::messageWaitReceive,
//                    'waitReceiveCount'=>ApiConst::reduceOne,
//                    'waitDeliveryCount'=>0,
//                    'waitGetCount'=>0,
//                    'orderCount'=>ApiConst::reduceOne,
//                    'waitRefundProccessCount'=>ApiConst::zero,
//                    'waitRefundReceiveCount'=>ApiConst::zero,
//                    'refundCount'=>ApiConst::zero,
//                    'alertCount'=>ApiConst::zero,
//                    'params'=>array('c'=>'shopkeeper',
//                        'm'=>'orderDetail',
//                        'orderId'=>$order['orderId']));
//                $push->addOneToClient($pushData);

            }

//            $orderIds = array_column($orders, 'orderId');
//            $this->updateOrderGoodsStoregeByOrderIds($orderIds);
            //发送消息
            $push = Push::getInstance();
            $push->pushOrderCloseMessage($newOrders);

        }
        file_put_contents($this->baseDir . \Our\PathConst::orderCloseWaitRecieveOrder, $endTime);
    }
    public function changeOrderStatus()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $beginTime = file_get_contents($this->baseDir . \Our\PathConst::orderCloseWaitRecieveOrder);
        $beginTime = $beginTime ? $beginTime : ApiConst::zero;
        $endTime = TIMESTAMP - ApiConst::orderStateWaitConfirmBeyond;
        $storeDao=\DAO\StoreModel::getInstance();
        // $beginTime=0;
        $orders = $orderDao->getMustCecelRecieveOrders($beginTime, $endTime, $orderDao->getOrderDetailField());
        $newOrders=array();
        $orderIds=array();
        if (!empty($orders)) {
            foreach ($orders as $order) {
                 $orderDao->setDb(DbNameConst::masterDBConnectName);
                $orderDao->db->doTransaction();
                //更新订单信息
                $updateData = array('order_state' => ApiConst::orderStateClose,'refund_amount'=>$order['orderAmount'],'gmt_update'=>TIMESTAMP,'is_effective'=>ApiConst::closeOrder);
                $update = $orderDao->update(array('order_id' => $order['orderId']),$updateData);
                if($update){
                    if ($order['paymentTime'] > ApiConst::zero && in_array($order['paymentType'], ArrayConst::orderPayTypeOnlines)) {
                        $isRefunMoney= $this->changeOrderStateCancelUnconditional($order);
                        if(!$isRefunMoney){

                            $orderDao->db->doRollback();
                            continue;
                        }
                    }

                    array_push($orderIds,$order['orderId']);
                    $this->updateOrderGoodsStoregeByOrderIds($orderIds);
                    array_push($newOrders,$order);
                    $orderIds=array();
                    $orderDao->db->doCommit();
                    $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
                    $storeDao->deleteStoreCache($order['storeId'],$order['orderId']);
                    $push=\Our\Push::getInstance();
                    echo json_encode($order);
                    $pushData=array('storeId'=>$order['storeId'],
                        'type'=>ApiConst::messageWaitReceive,
                        'waitReceiveCount'=>ApiConst::reduceOne,
                        'waitDeliveryCount'=>0,
                        'waitGetCount'=>0,
                        'orderCount'=>ApiConst::reduceOne,
                        'waitRefundProccessCount'=>ApiConst::zero,
                        'waitRefundReceiveCount'=>ApiConst::zero,
                        'refundCount'=>ApiConst::zero,
                        'alertCount'=>ApiConst::zero,
                        'params'=>array('c'=>'shopkeeper',
                            'm'=>'orderDetail',
                            'orderId'=>$order['orderId']));
                    $push->addOneToClient($pushData);
                }
//                $orderDao->deleteOrderCache($order['buyerId'],(string)$order['orderId'],$order['storeId'],true);
//                $storeDao->deleteStoreCache($order['storeId'],$order['orderId']);
//                $push=\Our\Push::getInstance();
//                $pushData=array('storeId'=>$order['storeId'],
//                    'type'=>ApiConst::messageWaitReceive,
//                    'waitReceiveCount'=>ApiConst::reduceOne,
//                    'waitDeliveryCount'=>0,
//                    'waitGetCount'=>0,
//                    'orderCount'=>ApiConst::reduceOne,
//                    'waitRefundProccessCount'=>ApiConst::zero,
//                    'waitRefundReceiveCount'=>ApiConst::zero,
//                    'refundCount'=>ApiConst::zero,
//                    'alertCount'=>ApiConst::zero,
//                    'params'=>array('c'=>'shopkeeper',
//                        'm'=>'orderDetail',
//                        'orderId'=>$order['orderId']));
//                $push->addOneToClient($pushData);

            }

//            $orderIds = array_column($orders, 'orderId');
//            $this->updateOrderGoodsStoregeByOrderIds($orderIds);
            //发送消息
            $push = Push::getInstance();
            $push->pushOrderCloseMessage($newOrders);

        }
        file_put_contents($this->baseDir . \Our\PathConst::orderCloseWaitRecieveOrder, $endTime);
    }
    public $errorMessage;
    public function updateDateGoodsStoregeByOrderGoods($orderGoods,$type=ApiConst::plus,$updateSaleNumFlag=true){
        $orderConfirmUtilDao=OrderConfirmUtil::getInstance(DbNameConst::masterDBConnectName);
        $storeCartsList=array();
        $storeCarts=array();
        $convertGoods=array();
        $storeCartses=array();
        $storeCarts['storeCarts']=array();
        foreach($orderGoods as $orderGood){
            $orderGood['type']=!empty($orderGood['goodsGroup'])? \Our\ApiConst::addBundingToCart:\Our\ApiConst::addGoodsToCart;
            $orderGood['goodsNum']=$orderGood['goodsNum'];
            $orderGood['goodsList']=\Our\Common::isSerialized($orderGood['goodsGroup'])?unserialize($orderGood['goodsGroup']):array();
            array_push($storeCarts['storeCarts'],$orderGood);
            $storeCartses[$orderGood['storeId']]=$storeCarts;
        }
//        if(!empty($storeCartses)){
//            array_push($storeCartsList,$storeCartses);
//        }
        $storeCartsList=$storeCartses;
        // $orderDao->updateNotRecieveOrders(ApiConst::orderStateWaitConfirm, ApiConst::orderStateClose, 'add_time', ApiConst::orderStateWaitConfirmBeyond, $this->orderMessageField);
        try{
            $orderConfirmUtilDao->updateGoodsStorage($storeCartsList,$type,$updateSaleNumFlag);
            return true;
        }catch(\Exception $ex){
            $orderGoodsIds=array_column($orderGoods,'goodsId');
            $orderidsStr=implode(',',$orderGoodsIds);
            $this->errorMessage='商品库存更新失败:'.$ex->getMessage().$ex->getCode().":".$orderidsStr;
           // echo '商品库存更新失败:'.$ex->getMessage().$ex->getCode().":".$orderidsStr;
            return false;
        }
    }
    public function updateOrderGoodsStoregeByOrderIds($orderIds,$orderGoodsId=false){
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
        //更新商品库存
        $orderGoodses = $orderGoodsDao->getOrderGoodsByOrderIds($orderIds, $this->getGoodsDetailField());
        $orderGoods=array();
        if(!empty($orderGoodsId)){
            foreach($orderGoodses as $orderGood){
                    if($orderGood['recId']==$orderGoodsId){
                        array_push($orderGoods,$orderGood);
                    }
            }
        }
        if(empty($orderGoods)){
            $orderGoods=$orderGoodses;
        }
       return $this->updateDateGoodsStoregeByOrderGoods($orderGoods);

    }

    public function updateGoodsStoregeByGoodsIds($storeId,$goodsid,$num=ApiConst::zero,$type=ApiConst::plus){
        if(is_array($goodsid)){
            $goodsids=array($goodsid);
            $convertGoodsId=Common::convertArrKey($goodsid,'goodsId');
            $where['goods_id']=array('in',$goodsids);
        }else{
            $where['goods_id']=$goodsid;
        }
        $where['store_id']=$storeId;
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::masterDBConnectName);
        $goodses=$goodsDao->getList($where,$goodsDao->goodsDetailField);
        if(!empty($goodses)){
            if(is_array($goodsid)){
                foreach($goodses as &$goods){
                    $goods['goodsNum']=$convertGoodsId[$goods['goodsId']]['num'];
                }
            }else{
                foreach($goodses as &$goods){
                    $goods['goodsNum']=$num;
                }
            }
            if($this->updateDateGoodsStoregeByOrderGoods($goodses,$type,false)){
                return true;
            }
        }
        return false;
    }

    //订单任务脚本自动确认收货
    public function canformRecieveOrder()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $memberDao=\DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliverymanLogsDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::masterDBConnectName);
        $orders = $orderDao->getOrdersByOrderState(ApiConst::orderStateWaitRecieve, 'accept_time', ApiConst::orderWaitRecieveTwentyFourHours, $this->orderMessageField, array(ApiConst::bySeller, ApiConst::bySelf));
        if (!empty($orders)) {
            $sellerTypeOrderIds = $orderDao->getShippingTypeSellerOrdersByOrders($orders);
            $qmDeliverymanLogs = $qmDeliverymanLogsDao->getFinishDeliveryByOrderId($sellerTypeOrderIds);
            if (!empty($qmDeliverymanLogs)) {
                $qmDeliverymanLogsOrderIds = array_column($qmDeliverymanLogs, 'orderId', 'orderId');
            }
            $sellerOrderIds = array();
            $expressOrderIds = array();
            foreach ($orders as $order) {
                //如果是配送订单
                if ($order['shippingType'] == ApiConst::bySeller) {
                    if (isset($qmDeliverymanLogsOrderIds[$order['orderId']])) {
                        array_push($sellerOrderIds, $order['orderId']);
                        $orderDao->deleteOrderCache($order['buyerId'], $order['orderId'], $order['storeId'], true);
                    }
                }
                if($order['shippingType'] == ApiConst::bySelf){
                    $limitTime = TIMESTAMP - ApiConst::orderWaitRecieveThreeDays;
                    if ($order['acceptTime'] < $limitTime) {
                        array_push($expressOrderIds, $order['orderId']);
                        $orderDao->deleteOrderCache($order['buyerId'], $order['orderId'], $order['storeId'],true);
                    }
                }
//                } else {
//                    $limitTime = TIMESTAMP - ApiConst::orderWaitRecieveThreeDays;
//                    if ($order['acceptTime'] < $limitTime) {
//                        array_push($expressOrderIds, $order['orderId']);z
//                        $orderDao->deleteOrderCache($order['buyerId'], $order['orderId'], $order['storeId'],true);
//                    }
//                }
                $memberDao->deleteTotalCache($order['buyerId']);
                \Our\RedisHelper::memberTotalFromStateToState($order['buyerId'], $order['orderState'], ApiConst::orderStateComplete);
            }
            $updateOrderIds = array_merge($sellerOrderIds, $expressOrderIds);
            echo '更新的订单id为：';
            var_dump($updateOrderIds);
            $orderDao->updateStatusByOrderId($updateOrderIds, ApiConst::orderStateComplete, TRUE);
        }
    }

    public function updateOrderExpress()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        while($result=RedisHelper::lpop(NameConst::expressList)){
            if($result){
                $expressInfo=$result['expressInfo'];
            }
            if ($expressInfo['deliverystatus'] == 3) {
                $data['shipping_over'] = 1;
            }
            if ($expressInfo['list']) {
                $data['shipping_sign'] = strtotime($expressInfo['list'][0]['time']);//签收时间
                $data['shipping_html'] = serialize($expressInfo['list']);
                $data['shipping_status'] = $expressInfo['deliverystatus'];
            }
            //$output;
            //更新订单物流
            $result = $orderDao->update(array('order_id' => $result['orderId']), $data);
            if ($result !== false) {
                echo '物流信息更新成功订单号:' . $result['orderId'] . "\r\n";
            }
        };
    }

    /**
     * 订单,获得配送订单列表
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getQmDeliveryLogList($memberId, $type = ApiConst::orderTypeBuy, $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize)
    {
        $qmDeliveryLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
        $qmDeliveryMan=\DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $refundReturnDao=\DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::salveDBConnectName);
        $qmMans=$qmDeliveryMan->getListByMemberId($memberId,true);
        $diliverymanIds=array_column($qmMans,'id');
        $diliverymanId = $memberDao->getInfo($memberId, 'diliveryman_id');
        if (empty($diliverymanIds)) {
            ErrorModel::throwException(CodeConfigModel::commonError);
        }
        $qmDeliveryLogList = $qmDeliveryLogDao->getListByDeliverymanIdAndTypeCache($diliverymanIds, $type,$pageIndex, $pageSize,array('get_time' => 'desc'),$memberId);
        $orderIds=Array();
        foreach($qmDeliveryLogList['list'] as $qmDeliveryLog){
            if($qmDeliveryLog['orderType']==ApiConst::orderTypeRefund){
                    $refundids[]=$qmDeliveryLog['orderId'];
            }else{
                $orderIds[]=$qmDeliveryLog['orderId'];
            }
        }
        if(!empty($refundids)){
            $refundWhere['refund_id']=array('in',$refundids);
            $refundOrders=$refundReturnDao->getList($refundWhere,$refundReturnDao->refundDetailField,ApiConst::zero,ApiConst::pageSize);
            $refundOrders=$refundReturnDao->convertCommonList($refundOrders['list'],'orderGoodsId');
            $refundReturnOrders=$refundReturnDao->convertCommonList($refundOrders,'refundId');
            $refundOrderIds=array_column($refundOrders, 'orderId');
        }
        if(!empty($refundOrderIds)){
            $orderIds=array_merge($refundOrderIds,$orderIds);
        }
       // $orderIds = array_column($qmDeliveryLogList['list'], 'orderId');
        //  echo json_encode($orderIds);exit;
        // $where['delete_state'] = ApiConst::undeleteOrder;

        $orderIds=implode(',',$orderIds);


        //获得订单商品列表
        if (!empty($orderIds)) {
            $where =Common::format(" order_id in({0})",$orderIds);
            // $where['lock_state'] = ApiConst::zero;

            //获得订单列表
            //  $orders=$orderDao->getList($where, $this->orderField, $pageIndex, $pageSize, $order = array('add_time' => 'desc'));
            $orders = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'getList'), array($where, $this->orderField, ApiConst::zero, $pageSize, $order = array('add_time' => 'desc')), \Our\ApiConst::oneDaySecond, array($diliverymanId));
            $goodsDao = \DAO\GoodsModel::getInstance();
            $orderIds = array_column($orders['list'], 'orderId');
            $orderCommons = $orderCommonDao->getAllByOrderIdsCache($orderIds, $diliverymanId, $orderCommonDao->orderCommonField);

            $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderIds, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond, array($diliverymanId.'_'));
            $orderMerge = Common::intergrateOneToMany($orders['list'], $orderGoods, 'orderId', 'orderId', 'orderGoods');
            $orderMerge = Common::intergrateOneToOne($orderMerge, $orderCommons, 'orderId', 'orderId');

            $orderMerge = $orderDao->convertOrderList($orderMerge);
            $convertResult = array();
            //$orderGoods = $goodsDao->convert($orderGoods);
            foreach ($qmDeliveryLogList['list'] as &$value) {
                if($value['orderType']==ApiConst::orderTypeRefund){
                    $delivery=$orderMerge[$refundReturnOrders[$value['orderId']]['orderId']];
                }else{
                    $delivery = $orderMerge[$value['orderId']];
                }
                $delivery['id'] = $value['id'];
                $delivery['reciverInfo'] = unserialize($delivery['reciverInfo']);
                $delivery['mobPhone'] = $delivery['reciverInfo']['mob_phone'];
                $delivery['getTime'] = $value['getTime'];
                $delivery['finishTime'] = $value['finishTime'];
                $delivery['mobPhone'] = $delivery['mobPhone'] ? $delivery['mobPhone'] : '';
                $delivery['finishTime'] = $delivery['finishTime'] ? $delivery['finishTime'] : ApiConst::zero;
                if($value['orderType']==ApiConst::orderTypeRefund){
                    //因为$value['orderId']=refundId
                    $orderMergeGoods=$goodsDao->convert($orderMerge[$refundReturnOrders[$value['orderId']]['orderId']]['orderGoods'],false,$refundOrders);
                    $delivery['orderGoods'] =$orderMergeGoods?$orderMergeGoods:array();
                }else{
                    $delivery['orderGoods'] = !empty($goodsDao->convert($orderMerge[$value['orderId']]['orderGoods']))?$goodsDao->convert($orderMerge[$value['orderId']]['orderGoods']):array();
                }

                $delivery['street'] =$orderCommonDao->convertReceiveAddress($delivery['reciverInfo']['address']);
                $delivery['lng'] = $delivery['reciverInfo']['lng'] ? $delivery['reciverInfo']['lng'] : 0.0;
                $delivery['lat'] = $delivery['reciverInfo']['lat'] ? $delivery['reciverInfo']['lat'] : 0.0;
                $delivery['subAddress'] = isset($delivery['reciverInfo']['sub_address']) ? $delivery['reciverInfo']['sub_address'] : '';
                $delivery['distributionFee']=$value['distributionFee'];
                unset($delivery['goodsAmount']);
                // unset($delivery['orderState']);
                unset($delivery['refundState']);
                unset($delivery['goodsAmount']);
                unset($delivery['reciverInfo']);
                array_push($convertResult, $delivery);
            }
            $returnData['orders'] = $convertResult;
            $returnData['totalCount'] = $orders['totalCount'];
            return $returnData;
        } else {
            return array('orders'=>array(),'totalCount'=>ApiConst::zero);
        }

    }

    public function updateOrderAmount($storeId,$orderId,$newOrderAmount,$memberName)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orderLogDao=\DAO\Order\OrderLogModel::getInstance(DbNameConst::masterDBConnectName);
        $orderDetail=$orderDao->getByOrderId($orderId,$orderDao->getOrderDetailField());
        $messageService=new \Business\Message\MessageServiceModel();
        $orderDetail=$orderDetail[ApiConst::arrBegin];
        $storeDao=\DAO\StoreModel::getInstance();
        if($orderDetail['storeId']!=$storeId){
            ErrorModel::throwException(CodeConfigModel::orderNotExist);
        }
        if($orderDetail['isReceivePayment'] != ApiConst::noreceivePayment){
            ErrorModel::throwException(CodeConfigModel::notAllowUpdataOrderAmount);
        }
        $data['order_amount']=$newOrderAmount;
        $res=$orderDao->updateByOrderId($data,$orderId);
        $push=\Our\Push::getInstance();
        $push->updateOrderAmount($orderDetail['buyerId'], $orderDetail['orderId'], $orderDetail['orderSn']);
        $push->sendTcpMessage();
        $messageService->addMessageCenterToDb();
        $orderDao->deleteOrderCache($orderDetail['memberId'], $orderId, $storeId, true);
        $storeDao->deleteStoreCache($storeId,$orderId);
        $orderLogDao->add($orderDetail['orderId'],ArrayConst::logMsgType[ApiConst::sellerUpdateOrderAmount],DescribeConst::sellerLog,$memberName,$orderDetail['orderState']);
        return $res;
    }

    /**
     * 获得配送详情
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getDeliveryDetail($deliveryId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $addressDao = \DAO\AddressModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $refundReturnDao=\DAO\Order\RefundReturnModel::getInstance();
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $diliverymanDao = \DAO\Order\DiliverymanModel::getInstance(DbNameConst::salveDBConnectName);
        $goodsDao = \DAO\GoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $qmDeliverymanLog = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
        $storeDao = \DAO\StoreModel::getInstance(DbNameConst::salveDBConnectName);
        $delivery = $qmDeliverymanLog->findByIdCache($deliveryId);
        if (empty($delivery)) {
            ErrorModel::throwException(CodeConfigModel::notExsitDeliver);
        }
        if($delivery['orderType']==ApiConst::orderTypeRefund){
            $refundReturn=$refundReturnDao->findByRefundId($delivery['orderId'],$refundReturnDao->refundDetailField);
            $orderId = $refundReturn['orderId'];
        }else{
            $orderId = $delivery['orderId'];
        }

        //订单

        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond,array($orderId));
        if (empty($order)) {
            ErrorModel::throwException(CodeConfigModel::notExsitOrder);
        }
        $fields = $orderDao->getFields();
        $this->order = $orderDao->getConvertOrder($order, $fields);
        //收货人地址
        //收货人信息
        $this->orderCommon = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderCommonDao, 'findByOrderId'), array($orderId, $orderCommonDao->orderCommonField), \Our\ApiConst::oneDaySecond);
        $reciverInfo = unserialize($this->orderCommon['reciverInfo']);

        //定单商品表
        $this->orderGoodsList = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderId, $this->getGoodsDetailField()), \Our\ApiConst::oneDaySecond);
        if (empty($this->orderGoodsList)) {
            ErrorModel::throwException(CodeConfigModel::notExistOrderGoods);
        }
        //商店相关信息
        $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($this->order['storeId'],$storeDao->detailField), \Our\ApiConst::oneDaySecond);
        $convertRefundReturn=Array();
        $convertRefundReturn[$refundReturn['orderGoodsId']]=$refundReturn;
        if($delivery['orderType']==ApiConst::orderTypeRefund){
            $orderGoods = $goodsDao->convert($this->orderGoodsList,false,$convertRefundReturn);
        }else{
            $orderGoods=$goodsDao->convert($this->orderGoodsList);
        }

        if (empty($orderGoods)) {
            $orderGoods = array();
        }
        if($delivery['deliveryState']==ApiConst::deliveryStateWait||$delivery['deliveryState']==ApiConst::deliveryStateWaitTen){
            $delivery['deliveryState']=ApiConst::deliveryStateWait;
        }
        // $reciverInfo['sub_address']
        $returnData = array(
            'orderId' => $this->order['orderId'],
            'storeName' => $this->order['storeName'],
            'orderSn' => $this->order['orderSn'],
            'orderAmount' => $this->order['orderAmount'],
            'deliveryState' => $delivery['deliveryState'],
            'orderType' => $delivery['orderType'],
            'id' => $deliveryId,
            'finishTime' => $delivery['finishTime'],
            'getTime' => $delivery['getTime'],
            'reciverName' => $this->orderCommon['reciverName'],
            'mobPhone' => $reciverInfo['mob_phone'],
            'street' =>$orderCommonDao->convertReceiveAddress($reciverInfo['address']),
            'lng' => isset($reciverInfo['lng']) ? $reciverInfo['lng'] : ApiConst::zero,
            'lat' => isset($reciverInfo['lat']) ? $reciverInfo['lat'] : ApiConst::zero,
            'subAddress' => isset($reciverInfo['sub_address'])?$reciverInfo['sub_address']:'',
            'orderGoods' => $orderGoods,
            'shippingFee' => $this->order['shippingFee'],
            'distributionFee'=>$delivery['distributionFee'],
            'isReceivePayment'=>$this->order['isReceivePayment']

        );
        return $returnData;
    }

//确认送达操作
    public function finishDeliveryOrder($id, $memberid)
    {
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliverymanLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::masterDBConnectName);
        //$deliverymanId = $memberDao->getInfo($memberid, 'diliveryman_id');
        $qmDeliveryManLog = $qmDeliverymanLogDao->findById($id);
        if ($qmDeliveryManLog['deliveryState'] == ApiConst::deliveryStateWait && $qmDeliveryManLog['id'] == $id) {
            $updateResult = $qmDeliverymanLogDao->updateStatusById($id);
            $orderDao = \DAO\Order\OrderModel::getInstance();
            $order = $orderDao->findByOrderId($qmDeliveryManLog['orderId'], $orderDao->getOrderDetailField());
            if ($updateResult) {
                $push = Push::getInstance();
                $push->reacheRemind($order['buyerId'], $order['orderId'], $order['orderSn']);
                $push->sendTcpMessage();
            }
            $orderDao->deleteOrderCache($memberid, $qmDeliveryManLog['orderId'], $order['storeId'],true,true,true,$memberid);
            $qmDeliverymanLogDao->deleteOrderCache($memberid, $id);
            return $updateResult;
        } else {
            return false;
        }
    }

    /**
     * @param $data
     * @param $memberId
     */
    public function getOrderPayResult($data, $memberId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance();
        $orderList = $orderDao->getListByCon(array('pay_sn' => $data['paySn'], 'buyer_id' => $memberId));
        if (!$orderList) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::noOrderListForPaySn);
        }

        $storeDao = \DAO\StoreModel::getInstance();
        $orderPayModel = \DAO\Order\OrderPayModel::getInstance();
        $paySn = $data['paySn'];
        $oldOrderPay = $orderPayModel->find(array('pay_sn'=>$paySn));
        $orderStateArray = array_column($orderList,'order_state');

        \Our\Log::getInstance()->write(json_encode($orderStateArray),'/data/log/apptest');
        if(isset($data['wxLitePayFlag'])&&$data['wxLitePayFlag']==\Our\ApiConst::one){//微信小程序支付时
            $oldOrderPay['pay_type'] = \Our\ApiConst::wxLitePayType;
        }
        if(in_array(\Our\ApiConst::orderStateWaitPay,$orderStateArray)&&in_array($oldOrderPay['pay_type'],array(\Our\ApiConst::wxAppPayType,\Our\ApiConst::wxLitePayType))&&((isset($data['payFlag'])&&$data['payFlag']==\Our\ApiConst::one)||!isset($data['payFlag']))){
            \Our\Log::getInstance()->write($data['payFlag'],'/data/log/apptest');
            if($oldOrderPay['pay_type']==\Our\ApiConst::wxLitePayType){
                $wxLitePay = \Payment\WxLitePay::getInstance();
                $storeId = $orderList[0]['store_id'];
                $mchIdArray = $storeDao->getStoreWxMchId($storeId);
                if($mchIdArray['errorCode']>0){
                    \Error\ErrorModel::throwException($mchIdArray['errorCode']);
                }
                $subMchId = $mchIdArray['mchId'];
                $payResult = $wxLitePay->getOrderPayResult($paySn,$subMchId);
            }else{
                $wxPay = \Payment\WxPay::getInstance();
                $storeId = $orderList[0]['store_id'];
                $mchIdArray = $storeDao->getStoreWxMchId($storeId);
                if($mchIdArray['errorCode']>0){
                    \Error\ErrorModel::throwException($mchIdArray['errorCode']);
                }
                $subMchId = $mchIdArray['mchId'];
                $payResult = $wxPay->getOrderPayResult($paySn,$subMchId);
            }
            \Our\Log::getInstance()->write('支付结果'.$payResult,'/data/log/apptest');
            if($payResult){
                $orderConfirmUtil =  \Order\OrderConfirmUtil::getInstance();
                $return = $orderConfirmUtil->updateOrderToPayed(array('paySn'=>$paySn,'pay_type'=>$oldOrderPay['pay_type']));
                if(!$return['flag']){
                    \Error\ErrorModel::throwException($return['errorCode']);
                }else{
                    $orderList = $orderDao->getListByCon(array('pay_sn' => $data['paySn'], 'buyer_id' => $memberId));
                }
            }
        }
        $return = array();
        $totalOrderAmount = array_sum(array_column($orderList, 'order_amount'));
        $orderTips = \Our\DescribeConst::paySuccessTips;
        $orderSubTips = \Our\DescribeConst::paySuccessSubTips;
        $orderContents = array();
        $orderIds = array();
        $orderNos = array();
        $orderState = \Our\ApiConst::one;
        $dlyoPickupCode = \Our\NameConst::emptyString;
        foreach ($orderList as $order) {
            $orderNos[] = $order['order_sn'];
            if($order['shipping_type']==\Our\ApiConst::bySelf){
                $dlyoPickupCode = substr($order['order_sn'], ApiConst::positionPickupCodeBegin);
            }
            if ($order['order_state'] == \Our\ApiConst::orderStateWaitPay) {
                $orderTips = \Our\DescribeConst::payFailedTips;
                $orderSubTips = \Our\DescribeConst::payFailedSubTips;
                $orderState = \Our\ApiConst::zero;
                break;
            } else if (($order['payment_type'] == \Our\ApiConst::payOffline||$order['payment_type'] == \Our\ApiConst::payAog) && $order['order_state'] == \Our\ApiConst::orderStateWaitConfirm) {//已下单的待线上支付订单
                $orderTips = \Our\DescribeConst::addOrderSuccessTips;
                $store = $storeDao->get($order['store_id'],false);
                $orderContent['storeName'] = $store['store_name'];
                if ($order['payment_type'] == \Our\ApiConst::payOffline) {
                    $orderContent['imageUrls'] = array();
                    if(\Our\Common::isSerialized($store['offline_payway'])){
                        $paywayArray = unserialize($store['offline_payway']);
                        $orderContent['payway'] = $paywayArray['payway'];
                        if($paywayArray){
                            foreach($paywayArray['images'] as $image){
                                if($image){
                                    $orderContent['imageUrls'][] = \Our\Common::getStaticFile($image, \Our\ImageConst::storeLabel);
                                }
                            }
                        }
                    }else{
                        $orderContent['payway'] = $store['offline_payway'];
                    }
                } else if ($order['payment_type'] == \Our\ApiConst::payAog) {
                    $orderContent['payway'] = \Our\DescribeConst::afterPay;
                }
                $orderContent['orderAmount'] = $order['order_amount'];
                $orderContents[]=$orderContent;
            }
            $orderIds[] = $order['order_id'];
        }
        $waitOnelinePayAmount = \Our\ApiConst::zero;
        if($orderState==\Our\ApiConst::zero){
            foreach ($orderList as $order) {
                if ($order['order_state'] == \Our\ApiConst::orderStateWaitPay) {
                    $waitOnelinePayAmount += $order['order_amount'];
                }
            }
        }
        $return['orderState'] = $orderState;
        if(isset($data['wxLitePayFlag'])&&$data['wxLitePayFlag']==\Our\ApiConst::one){
            $return['paySn'] = $data['paySn'];
            if(!$orderState&&!((isset($data['payFlag'])&&$data['payFlag']==\Our\ApiConst::one))){
                $orderConfirmUtil = \Order\OrderConfirmUtil::getInstance();
                $paySn = $orderConfirmUtil->makeNewPaySnForOrderWithOldPaySn($data['paySn'],$memberId);
                $return['paySn'] = $paySn;
            }
        }

        $return['orderNos'] = $orderNos;
        $return['totalOrderAmount'] = $totalOrderAmount;
        $return['waitOnlinePayAmount'] = $waitOnelinePayAmount;
        $return['orderTips'] = $orderTips;
        $return['orderSubTips'] = $orderSubTips;
        $return['orderContents'] = $orderContents;
        $return['dlyoPickupCode'] =$dlyoPickupCode;
        $return['coupons'] = $this->getGiftCouponsByOrderIds($orderIds, $memberId);
        return $return;
    }


    /**
     * 获取当前订单是否有可用优惠券order
     * @param $orderIds
     * @param $memberId
     * @return array
     * @throws \Our\Exception
     */
    public function getGiftCouponsByOrderIds($orderIds, $memberId)
    {
        $returnCoupons = array();
        if ($orderIds) {
            $memberCouponDao = \DAO\Coupon\MemberCouponModel::getInstance();
            $whereSql = ' coupon_state =' . \Our\ApiConst::couponUnused . ' and member_id =' . $memberId . ' and out_time > ' . time() . ' and gift_order_id in (' . implode(',', $orderIds) . ')';
            $memberCouponArray = $memberCouponDao->getMemberCouponsByMemberId($whereSql, $memberId);
            if ($memberCouponArray) {
                $couponDao = \DAO\Coupon\CouponModel::getInstance();
                $couponIds = array_column($memberCouponArray, 'coupon_id');
                if ($couponIds) {
                    $couponDao->setDb();
                    $coupons = $couponDao->getListByCouponIds($couponIds, $memberId);
                    $storeDao = \DAO\StoreModel::getInstance();
                    if ($coupons) {
                        foreach ($coupons as $temp) {
                            $couponList[$temp['id']] = $temp;
                        }
                        foreach ($memberCouponArray as $memberCoupon) {
                            $coupon = $couponList[$memberCoupon['coupon_id']];

                            $temp = array();
                            $temp['type'] = $coupon['coupon_type'];
                            $temp['couponId'] = $coupon['id'];
                            $orderAmount = intval($coupon['order_amount']);
                            if ($coupon['type'] == \Our\ApiConst::noLimitCoupon) {//无门槛优惠券
                                $temp['type'] = \Our\ApiConst::noLimitCouponType;
                                $temp['title'] = intval($coupon['cash_money']);
                                $temp['subTitle'] = \Our\DescribeConst::noLimitCoupon;
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullMinusCouponType) {//满额减免券
                                $temp['title'] = intval($coupon['cash_money']);
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullAvailable, $orderAmount);
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::discountCouponType) {
                                $temp['title'] = $coupon['discount'];
                                if($orderAmount>0){
                                    $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponTitleFullDiscount,$orderAmount,$coupon['discount']);
                                }else{
                                    if(in_array($coupon['type'],array(\Our\ApiConst::goodsCoupon,\Our\ApiConst::goodsClassCoupon))){
                                        $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponDiscount , $coupon['discount']);
                                    }else{
                                        $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponTitleFullDiscountNoAmoutLimit , $coupon['discount']);
                                    }
                                }
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullForCouponCouponType) {
                                $temp['title'] = \Our\DescribeConst::specialCoupon;
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullForCoupon, $orderAmount);
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullForGiftCouponType) {
                                $temp['title'] = \Our\DescribeConst::specialCoupon;
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullForGift, $orderAmount);
                            }
                            $temp['storeId'] = $coupon['store_id'];
                            if ($temp['storeId']) {
                                $storeInfo = $storeDao->get($temp['storeId'],false);
                                if (!$storeInfo) {
                                    continue;
                                }
                                $temp['storeName'] = $storeInfo['store_name'];
                            } else {
                                $temp['storeName'] = \Our\DescribeConst::wholePlatform;
                            }
                            $temp['startTime'] = $memberCoupon['add_time'];
                            $temp['endTime'] = $memberCoupon['out_time'];
                            $returnCoupons[] = $temp;
                        }
                    }
                }

            }

        }
        return $returnCoupons;
    }

    public function goToPay($memberId, $orderId)
    {
        $this->checkOrderForPay($memberId, $orderId);
        $orderConfirmUtil = \Order\OrderConfirmUtil::getInstance();
        $paySn = $orderConfirmUtil->makeNewPaySnForOrderWithOrderId($orderId, $memberId);
        return $paySn;
    }

    public function checkOrderForPay($memberId, $orderId)
    {
        if (!$orderId) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyOrderIdForPay);
        }
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond,array($orderId));
        if (!$order) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyOrderForPay);
        }
        if ($order['buyer_id'] != $memberId) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::noRightForOrder);
        }
        if (!($order['payment_type'] == \Our\ApiConst::payOnline && $order['order_state'] == \Our\ApiConst::orderStateWaitPay)) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::wrongPayForOrder);
        }
        return $order;
    }
   public function testPush($msg){
       echo $msg.'abcde';
       return true;
   }
    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;
    public static function realeaseInstance(){
        if(!empty(self::$_instance)){
            self::$_instance=null;
        }
    }
    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}
