<?php

namespace Business\Order;

use Error\CodeConfigModel;
use Error\ErrorModel;
use Order\OrderConfirmUtil;
use Our\ApiConst;
use Our\ArrayConst;
use Our\Common;
use Our\DbNameConst;
use Our\ExpressConst;
use Our\ImageConst;
use Our\NameConst;
use Our\PageConst;
use Our\Push;

/**
 * 店铺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,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";
    private $orderGoodsField = "order_id as orderId,rec_id as recId,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";


    private $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_group as goodsGroup';
    }

    /**
     * 订单,获得订单列表
     *
     * @date 2018-5-15
     * @author ccw
     */
    public function getList($memberId, $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);
        $where['delete_state'] = ApiConst::undeleteOrder;
        $where['buyer_id'] = $memberId;
        //$where['lock_state'] = ApiConst::zero;
        if ($orderState != false) {
            $where['order_state'] = array('in', explode(',', $orderState));
        }

        //获得订单列表
        $orders = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'getList'), array($where, $this->orderField, $pageIndex, $pageSize, $order = array('add_time' => '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->orderGoodsField), \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 new \stdClass();
            }
        } else {
            return new \stdClass();
        }


    }

    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);
            }
        }

    }



    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);
        $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);
        //$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);
        //商店相关信息
        $this->store = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($this->order['storeId'], $this->storeField), \Our\ApiConst::oneDaySecond);
        $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['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());
        } else {
            $returnData['diliverymanId'] = ApiConst::zero;
            $returnData['deliveryman'] = new \stdClass();
        }
        $returnData['totalGoodsNum'] = $orderGoodsDao->getGoodsCount($this->orderGoodsList);
        $returnData['offlinePayway'] = $this->store['offlinePayway'] ? $this->store['offlinePayway'] : '';
        $returnData['reciverInfo'] = $this->address;
        $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);
        $memberDao=\DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $order = $orderDao->findByOrderId($orderId);
        //判断订单目前状态是否允许取消
        $isAllowCancel = $orderDao->isAllowCancel($order);
        if ($isAllowCancel) {
            $res=$orderDao->updateStatusByOrderId($orderId, ApiConst::orderStateCancel);
            if($res){
                if ($memberId) {
                    $orderDao->deleteOrderCache($memberId, $orderId);
                    $memberDao->fromOrderStateToOrderState($memberId,$order['order_state'],ApiConst::orderStateCancel);
                }
            }
            return $res;
        } else {
            ErrorModel::throwException(CodeConfigModel::notAllowCancel);
        }

    }

    //确认收货
    public function confirmRecieve($orderId, $memberId)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
       // $orderDao->deleteOrderCache($memberId, $orderId);
        $order = $orderDao->findByOrderId($orderId);
        //判断订单目前状态是否允许取消
        $isAllowConfirm = $orderDao->isAllowConfirm($order);
        if ($isAllowConfirm) {
            $res = $orderDao->updateStatusByOrderId($orderId, ApiConst::orderStateComplete, TRUE);
            if ($res) {
                $orderDao->deleteOrderCache($memberId, $orderId);
                \Our\RedisHelper::memberTotalFromStateToState($memberId,$order['order_state'],ApiConst::orderStateComplete);
                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());
        $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'] = $goodsCommonDao->getGoodsImgSrc($orderGoods['goodsImage'], ArrayConst::goodsImageExt[ApiConst::goodsSmallSize]);
            $return['goodsAttr'] = $goodsDao->getFormatGoodsAttr($orderGoods['goodsSpec']);
            $return['orderPrice'] = $order['orderAmount'];
            $return['expressInfo'] = $order['shippingHtml'] ? unserialize($order['shippingHtml']) : array();
            $return['shippingStatus'] = $order['shippingStatus'];
            $return['sendTime'] = $order['sendTime'];
            $return['rechedTime'] = $order['shippingSign'];
            $return['shippingArrivalTime'] = $order['shippingArrivalTime'];
            return $return;
        } else {
            return new \stdClass();
        }

    }
    //推送接单消息到店铺
    public function pushRecieveWaitOrder(){
        $baseConfDir=\Our\Common::getConfig('out.config');
        $savePath=$baseConfDir . \Our\PathConst::orderWaitRecieveTaskAddTime;
        $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();
        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);
        $pageBegin=PageConst::taskPageBegin;
        $push = Push::getInstance();
        do {
            $orders = $orderDao->getRecieveOrders(ApiConst::orderStateWaitRecieve,$addTime,$pageBegin,PageConst::taskPageSize,'send_time');
            foreach ($orders['list'] as $order) {
                $push->reacheRemind($order['buyerId'],$order['orderId'],$order['orderSn']);
            }
            $pageBegin++;
        }while(!empty($orders['list']));
        $push->sendTcpMessage();
        file_put_contents($savePath,TIMESTAMP);
    }
    //订单任务脚本关闭订单
    public function changeOrderStatus()
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $orders = $orderDao->getOrdersByOrderState(ApiConst::orderStateWaitConfirm, 'add_time', ApiConst::orderStateWaitConfirmBeyond, $this->orderMessageField);
        if (!empty($orders)) {
            foreach ($orders as $order) {
                $orderDao->deleteOrderCache($order['buyerId'], $order['orderId']);
                \Our\RedisHelper::memberTotalFromStateToState($order['buyerId'],$order['orderState'],ApiConst::orderStateClose);
            }
            $res = $orderDao->updateOrdersByorderState(ApiConst::orderStateWaitConfirm, ApiConst::orderStateClose, 'add_time', ApiConst::orderStateWaitConfirmBeyond, $this->orderMessageField);
            if ($res) {
                $push = Push::getInstance();
                $push->pushOrderCloseMessage($orders);
            }
        }
    }

    //订单任务脚本自动确认收货
    public function canformRecieveOrder()
    {
        $orderDao = \DAO\Order\OrderModel::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::express));
        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']);
                    }
                } else {
                    $limitTime = TIMESTAMP - ApiConst::orderWaitRecieveThreeDays;
                    if ($order['acceptTime'] < $limitTime) {
                        array_push($expressOrderIds, $order['orderId']);
                        $orderDao->deleteOrderCache($order['buyerId'], $order['orderId']);
                    }
                }
                \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);
        $where['order_state'] = ApiConst::orderStateWaitRecieve;
        $where['shipping_type'] = ApiConst::express;
        $where['shipping_status'] = array('lt', ApiConst::shippingStatusArrive);
        $orders = $orderDao->getListByCon($where, $orderDao->getOrderShippingField());
        $orderIds = array_column($orders, 'orderId');
        $shippingExpressIds = $orderCommonDao->getAllByOrderIds($orderIds, $orderCommonDao->getShippingFields(), 'orderId');
        $expesses = array_column(ExpressConst::expresses, 'eCode', 'id');
        foreach ($orders as $order) {
            $url = Common::format(ExpressConst::expressUrl . "?appkey={0}", ExpressConst::expressKey);
            $type = $expesses[$shippingExpressIds[$order['orderId']]];
            $number = $order['shippingCode'];
            $post = array('type' => $type,
                'number' => $number
            );
            $result = Common::sendurl($url, '', $post, 'post');
            $jsonarr = json_decode($result, true);
            if ($jsonarr['status'] != 0) {
                continue;
            }

            $result = $jsonarr['result'];
            //if($result['issign'] == 1) echo '<li>已签收</li>';
            //else echo '<li>未签收'.'</li>';
            $data = array();
            //deliverystatus	int	物流状态 1在途中 2派件中 3已签收 4派送失败(拒签等)
            if ($result['deliverystatus'] == 3) {
                $data['shipping_over'] = 1;
            }
            if ($result['list']) {
                $data['shipping_sign'] = strtotime($result['list'][0]['time']);//签收时间
                $data['shipping_html'] = serialize($result['list']);
                $data['shipping_status'] = $result['deliverystatus'];
            }//$output;
            //更新订单物流
            $result = $orderDao->update(array('order_id' => $order['orderId']), $data);
            if ($result !== false) {
                echo '物流信息更新成功订单号:' . $order['orderSn'] . "\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);

        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::salveDBConnectName);
        $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::salveDBConnectName);
        $orderCommonDao = \DAO\Order\OrderCommonModel::getInstance(DbNameConst::salveDBConnectName);
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::salveDBConnectName);
        $diliverymanId = $memberDao->getInfo($memberId, 'diliveryman_id');
        if (empty($diliverymanId)) {
            ErrorModel::throwException(CodeConfigModel::commonError);
        }

        $qmDeliveryLogList = $QmDeliveryLogDao->getListByDeliverymanIdAndTypeCache($diliverymanId, $type, $pageIndex, $pageSize);
        $orderIds = array_column($qmDeliveryLogList['list'], 'orderId');
        $where['delete_state'] = ApiConst::undeleteOrder;
        //$orderIds=implode(',',$orderIds);
        $where['order_id'] = array('in', $orderIds);
        $where['lock_state'] = ApiConst::zero;

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

        //获得订单商品列表
        if (!empty($orderIds)) {
            $orderGoods = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderGoodsDao, 'getOrderGoodsByOrderIds'), array($orderIds, $this->orderGoodsField), \Our\ApiConst::oneDaySecond, array($memberId));
            $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) {
                $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;
                $delivery['orderGoods'] = $orderGoods;
                $delivery['street'] = $delivery['reciverInfo']['address'] . $delivery['reciverInfo']['street'];
                $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'] : '';
                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 new \stdClass();
        }

    }

    /**
     * 获得配送详情
     *
     * @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);
        $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);
        }
        $orderId = $delivery['orderId'];
        //订单

        $order = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderDao, 'findByOrderId'), array($orderId), \Our\ApiConst::oneDaySecond);
        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'], $this->storeField), \Our\ApiConst::oneDaySecond);
        $orderGoods=$goodsDao->convert($this->orderGoodsList);
        if(empty($orderGoods)){
            $orderGoods=array();
        }
        $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' => $reciverInfo['street'],
            'lng'=>$reciverInfo['lng'],
            'lat'=>$reciverInfo['lat'],
            'subAddress' => isset($reciverInfo['sub_address']) ? $reciverInfo['sub_address'] : '',
            'orderGoods' => $orderGoods,
            'shippingFee'=>$this->order['shippingFee'],

        );
        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->findByIdCache($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']);
            }
            $orderDao->deleteOrderCache($memberid, $qmDeliveryManLog['orderId']);
            $qmDeliverymanLogDao->deleteOrderCache($deliverymanId, $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);
        }
        $return = array();
        $totalOrderAmount = array_sum(array_column($orderList, 'order_amount'));
        $orderTips = \Our\DescribeConst::paySuccessTips;
        $orderSubTips = \Our\DescribeConst::paySuccessSubTips;
        $orderContents = array();
        $storeDao = \DAO\StoreModel::getInstance();
        $orderIds = array();
        $orderNos = array();
        $orderState = \Our\ApiConst::one;
        foreach ($orderList as $order) {
            $orderNos[] = $order['order_sn'];
            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::payOnline && $order['order_state'] == \Our\ApiConst::orderStateWaitConfirm) {//已下单的待线上支付订单
                $orderTips = \Our\DescribeConst::addOrderSuccessTips;
                $store = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($order['store_id']), \Our\ApiConst::oneHour);
                $orderContent['storeName'] = $store['store_name'];
                if ($order['payment_type'] == \Our\ApiConst::payOffline) {
                    $orderContent['payway'] = $store['offline_payway'];
                } else if ($order['payment_type'] == \Our\ApiConst::payAog) {
                    $orderContent['payway'] = \Our\DescribeConst::afterPay;
                }
                $orderContent['orderAmount'] = $order['order_amount'];
            }
            $orderIds[] = $order['order_id'];
        }
        $return['orderState'] = $orderState;
        /*$return['paySn'] = $data['paySn'];
        if(!$orderState){
            $orderConfirmUtil = \Order\OrderConfirmUtil::getInstance();
            $paySn = $orderConfirmUtil->makeNewPaySnForOrderWithOldPaySn($data['paySn'],$memberId);
            $return['paySn'] = $paySn;
        }*/
        $return['orderNos'] = $orderNos;
        $return['totalOrderAmount'] = $totalOrderAmount;
        $return['orderTips'] = $orderTips;
        $return['orderSubTips'] = $orderSubTips;
        $return['orderContents'] = $orderContents;
        $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'] = $coupon['cash_money'];
                                $temp['subTitle'] = \Our\DescribeConst::noLimitCoupon;
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::fullMinusCouponType) {//满额减免券
                                $temp['title'] = $coupon['cash_money'];
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullAvailable, $orderAmount);
                            } else if ($coupon['coupon_type'] == \Our\ApiConst::discountCouponType) {
                                $temp['title'] = $coupon['discount'];
                                $temp['subTitle'] = \Our\Common::format(\Our\DescribeConst::couponFullDiscount, $orderAmount, $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 = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$storeDao, 'getInfoById'), array($temp['storeId'], 'store_name'), \Our\ApiConst::oneHour);
                                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);
        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;
    }

    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}
