<?php

namespace Business\Store;

use DAO\Order\DiliverymanModel;
use DAO\StoreModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;
use Yaf\Exception;


/**
 * 店主service
 *
 * @date 2018-5-11
 * @author csw
 */
class DeliveryServiceModel extends \Business\AbstractModel
{


    public $clientType = false;

    public function init()
    {
        $this->storeDao = StoreModel::getInstance();
    }

    public function selectDeliveryMan($data)
    {
        $orderDao = \DAO\Order\OrderModel::getInstance(DbNameConst::masterDBConnectName);
        $storeDao=\DAO\StoreModel::getInstance();
        $refundReturnDao=\DAO\Order\RefundReturnModel::getInstance(DbNameConst::masterDBConnectName);
        $qmDeliveryManLog = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::masterDBConnectName);
        $messageService=\Business\Message\MessageServiceModel::getInstance();
        $deliveryManDao=\DAO\Order\DiliverymanModel::getInstance();
        $orderDao->setDb($orderDao->dbName);
        if($data['orderType']==ApiConst::orderTypeRefund){
            //如果是退货orderId就是refundId
            $orderOne=  $refundReturnDao->findByRefundId($data['orderId'],$refundReturnDao->refundDetailField);
            $whereOrder['order_id']=$orderOne['orderId'];
            $orderD= $orderDao->find($whereOrder,$orderDao->getOrderDetailField());
        }else{
            $whereOrder['order_id']=$data['orderId'];
            $orderD= $orderDao->find($whereOrder,$orderDao->getOrderDetailField());
        }

//        if( $orderD['diliveryman_id']== $data['id']){
//            ErrorModel::throwException(CodeConfigModel::alreadyExsitQmDeliveryLog);
//        }
//        if(!$data['distributionFee']){
//            ErrorModel::throwException(CodeConfigModel::paramsError);
//        }
        $orderDao->db->doTransaction();
        $orderData['diliveryman_id'] = $data['id'];
        if($data['orderType']==ApiConst::orderTypeRefund){
            $returnWhere['refund_id']=$data['orderId'];
            $orderRes= $refundReturnDao->update($returnWhere,$orderData);
        }else{
            $orderData['order_state']=ApiConst::orderStateWaitRecieve;
            $orderData['send_time']=TIMESTAMP;
            $orderRes = $orderDao->updateByOrderId($orderData, $data['orderId']);
        }

        if ($orderRes===false) {
            $orderDao->db->doRollback();
            ErrorModel::throwException(CodeConfigModel::updateOrderFail);
        }
        $qmDeliveryManLogData['diliveryman_id'] = $data['id'];
        $qmDeliveryManLogData['store_id'] = $data['storeId'];
        $qmDeliveryManLogData['order_id'] = $data['orderId'];
        $qmDeliveryManLogData['delivery_state'] = ApiConst::deliveryStateWait;
        $qmDeliveryManLogData['distribution_fee'] =$data['distributionFee'];
        $qmDeliveryManLogData['order_type'] = $data['orderType'];
        if($data['orderType']==ApiConst::orderTypeRefund){
            $qmDeliveryManLogData['shipping_fee']=$orderD['needShippingFee'];
        }else{
            $qmDeliveryManLogData['shipping_fee'] =    $orderD['shippingFee'];
        }
        $qmDeliveryManLogData['order_sn'] =    $orderD['orderSn'];
        $qmDeliveryManLogData['get_time'] = TIMESTAMP;
       // $qmDeliveryWhere['diliveryman_id']= $qmDeliveryManLogData['diliveryman_id'];
        $qmDeliveryWhere['order_id']=$qmDeliveryManLogData['order_id'];
        $qmDeliveryWhere['order_type']=$qmDeliveryManLogData['order_type'];
        $isRepeat=$qmDeliveryManLog->find($qmDeliveryWhere);
        if($isRepeat){
             $res=$qmDeliveryManLog->update($qmDeliveryWhere,$qmDeliveryManLogData);
        }else{
            $res = $qmDeliveryManLog->insert($qmDeliveryManLogData);
        }
        if (!res) {
            $orderDao->db->doRollback();
            ErrorModel::throwException(CodeConfigModel::selectDeliveryFail);
        }
        $orderDao->db->doCommit();
        $deliveryMan=$deliveryManDao->findById($orderD['diliverymanId']);
        $deliveryManMemberId=$deliveryMan['memberId'];
        $deliveryMan=$deliveryManDao->findById($data['id']);
        $oringeDeliveryManMemberId=$deliveryMan['memberId'];
        $deliveryManMemberIds=array($deliveryManMemberId,$oringeDeliveryManMemberId);
        $orderDao->deleteOrderCache(null, $data['orderId'], $data['storeId'], true,false,$deliveryManMemberIds);
        $storeDao->deleteStoreCache($data['storeId'],$data['orderId']);
        $storeDao->deleteStoreRefundCache($data['storeId'],$data['orderId']);
        $orderDao->deleteOrderCache($orderD['buyerId'],$orderD['orderId']);
        //配送员推送
        $push=\Our\Push::getInstance();
        if($data['orderType']==ApiConst::orderTypeRefund){
            $push->sendDelivery($oringeDeliveryManMemberId,$orderD['orderId'],$orderOne['orderGoodsId']);
        }else{
            $push->sendDelivery($oringeDeliveryManMemberId,$orderD['orderId']);
        }

        $messageService->addMessageCenterToDb();
        return $res;
    }

    public function addDeleiveryMan($storeId,$memberMobile,$trueName=''){
        $memberDao=\DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        $deliveryManDao=\DAO\Order\DiliverymanModel::getInstance(DbNameConst::masterDBConnectName);
        $member=$memberDao->getByMemberMobile($memberMobile);
        $storeDao=\DAO\StoreModel::getInstance();
        $memberMobile=$member['memberMobile'];
        if(strlen($memberMobile)>ApiConst::telephoneLen || !$memberMobile){
                ErrorModel::throwException(CodeConfigModel::notExsitDeliveryMan);
        }
        $where['store_id']=$storeId;
        $where['member_id']=$member['memberId'];
        $res=$deliveryManDao->getByWhere($where);
        if($res){
            $res=$res[ApiConst::zero];
        }
        if($res && !$res['isDel']){
            ErrorModel::throwException(CodeConfigModel::alreadyExsitDeliveryMan);
        }
        if($res['isDel']==ApiConst::deleteStateOne){
            $updateData['is_del']=ApiConst::zero;
            $updateData['true_name']=$trueName;
            $updateData['update_time']=TIMESTAMP;
            $deliveryManWhere['id']=$res['id'];
            $resData= $deliveryManDao->update($deliveryManWhere,$updateData);
            $memberData['diliveryman_id'] =$res['id'];
            $resData=$res['id'];
        }else{
            $trueName=$trueName?$trueName:$member['memberName'];
            $deliveryManData['true_name']=$trueName;
            $deliveryManData['mobile']=$memberMobile;
            $deliveryManData['scores']=ApiConst::five;
            $deliveryManData['store_id']=$storeId;
            $deliveryManData['add_time']=TIMESTAMP;
            $deliveryManData['update_time']=TIMESTAMP;
            $deliveryManData['member_id']=$member['memberId'];
            $deliveryManData['bind_status']=ApiConst::one;
            $deliveryManData['is_del']=ApiConst::zero;
            $resData=$deliveryManDao->insert($deliveryManData);
            $memberData['diliveryman_id']=$resData;
        }
        if(!$resData){
            ErrorModel::throwException(CodeConfigModel::addDeliveryManError);
        }
        $memberDao->saveInfo($memberData,$member['memberId']);
        $storeDao->deleteStoreCache($storeId);
        $storeDao->deleteStoreRefundCache($storeId);
//        $memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();
//        $memberDb0Redis->tableHSet(trim($member['diliveryman_id']),$resData,ApiConst::tenDaySecond);
        return $resData;

    }

    /**
     * 登录业务
     *
     * @var \Business\User\LoginV2Model
     */
    private
    static $_instance = null;

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

        return self::$_instance;
    }

}
