<?php

namespace DAO\Order;

use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\ArrayConst;
use Our\Common;
use Our\DbNameConst;
use Our\DescribeConst;
use Our\NameConst;
use Our\OrderConst;


/**
 * 订单相关
 * @date 2018-5-14
 * @author csw
 */
class DrawGoodsModel extends \DAO\AbstractModel
{


    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_order';

    private $countField = '(sum(order_amount)) as orderTotal,count(*) as orderCount';
    /**
     * 主键
     *
     * @var string
     */
    public $_primaryKey = 'order_id';
    public $errorMessage;

    public function init()
    {
        //$this->setDb();
    }

    public function getOrderDetailField()
    {
        return 'order_id as orderId,coupon_id as couponId,refund_amount as refundAmount,order_sn as orderSn,pay_sn as paySn,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,payment_time as paymentTime,finnshed_time as finnshedTime,need_shipping_fee as needShippingFee,payment_code as paymentCode,buyer_id as buyerId,buyer_name as buyerName,refund_condition as refundCondition,delay_time as delayTime,gmt_update as gmtUpdate';
    }

    public function getOrderShippingField()
    {
        return "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,shipping_code as shippingCode";
    }

    public function getCount($where, $isArray = true)
    {
        $this->setDb();
        if (!$isArray) {
            $str = '$count =  $this->db->from($this->_tableName)->where(delete_state = 0)';
            foreach ($where as $v) {
                $str .= "->where('$v')";
            }
            $str .= "->fetchNum();";
            eval($str);
            return intval($count);
        }
        $where['delete_state'] = 0;
        return $this->db->from($this->_tableName)->where($where)->fetchNum();
    }

    public function getCounts($where, $field, $group = false, $limit = [])
    {
        $this->setDb();
        $this->db->select($field)->from($this->_tableName)->where($where)->group($group);
        if($limit) {
            $this->db->limit($limit[0],$limit[1]);
        }
        return $this->db->fetchAll();
    }

    public function getOrderCounts($where, $field)
    {
        $this->setDb();
        return $this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
    }

    public function getShopKeeperCountByStoreId($storeId)
    {
        $refundReturnDao=\DAO\Order\RefundReturnModel::getInstance(DbNameConst::salveDBConnectName);
        $begin = strtotime(date("Y-m-d"), time());
        $end = TIMESTAMP;
        $notInState=ApiConst::orderStateCancel.','.ApiConst::orderStateClose;
        $where = Common::format(" store_id={0} and order_state not in ({1})", $storeId,$notInState);
        $orderTotal = $this->getOrderCounts($where, $this->countField);
        $refundAmount=$refundReturnDao->getRefundSuccessMoneyByStoreId($storeId);
        $orderTotal['orderTotal']=$orderTotal['orderTotal']-$refundAmount;
        $where .= Common::format(" and gmt_update between {0} and {1}", $begin, $end);
        $todayTotal = $this->getOrderCounts($where, $this->countField);
        $todayRefund=$refundReturnDao->getRefundSuccessMoneyByStoreId($storeId,$begin,$end);
        $todayTotal['orderTotal']=$todayTotal['orderTotal']-$todayRefund;
        $total['todayOrderTotal'] = isset($todayTotal['orderTotal']) ? $todayTotal['orderTotal'] : ApiConst::zero;
        $total['todayOrderCount'] = isset($todayTotal['orderCount']) ? $todayTotal['orderCount'] : ApiConst::zero;
        $total['orderTotal'] = isset($orderTotal['orderTotal']) ? (int)$orderTotal['orderTotal'] : ApiConst::zero;
        $total['orderCount'] = isset($orderTotal['orderCount']) ? $orderTotal['orderCount'] : ApiConst::zero;
        return $total;
    }


    public function getShopKeeperCountByStoreIdCache($storeId)
    {
        return \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getShopKeeperCountByStoreId'), array($storeId), \Our\ApiConst::oneDaySecond, array($storeId));
    }

    /**
     * 获取单条数据
     * @param $where
     * @return array
     */
    public function find($where, $field = '*')
    {
        $this->setDb($this->dbName);
        $data = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        return $data;
    }

    public function findByOrderId($orderId, $field = '*')
    {
        $this->setDb($this->dbName);
        $where['order_id'] = $orderId;
        return $this->find($where, $field);
    }

    public function findByMemberIdAndOrderId($memberId, $orderId)
    {
        $this->setDb($this->dbName);
        $where['order_id'] = $orderId;
        $where['buyer_id'] = $memberId;
        return $this->find($where, $this->getOrderDetailField());
    }

    //判断订单是否允许取消
    public function isAllowCancel($order)
    {
        if($order['paymentTime']==ApiConst::zero){
            if ($order['orderState'] == ApiConst::orderStateWaitPay || $order['orderState'] == ApiConst::orderStateWaitConfirm || (($order['orderState'] == ApiConst::orderStateWaitSend || $order['orderState'] == ApiConst::orderStateWaitRecieve) && $order['isReceivePayment'] == ApiConst::noreceivePayment)) {
                return true;
            } else {
                return false;
            }
        }else{
            if(($order['paymentTime']+ApiConst::tenMinSecond)<TIMESTAMP){
                return false;
            }else{
                return true;
            }
        }

    }

    //列表转换
    public function convertOrderList($list)
    {
        $convertList = array();
        foreach ($list as $order) {
            $convertList[$order['orderId']] = $order;
        }
        return $convertList;
    }

    //confirm
    public function isAllowConfirm($order)
    {
        if ($order['order_state'] == ApiConst::orderStateWaitRecieve) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 订单锁定
     *
     * @param
     * @return bool
     */
    public function editOrderLock($orderId)
    {
        $this->setDb($this->dbName);
        $order_id = intval($orderId);
        if ($order_id > ApiConst::zero) {
            $condition = array();
            $condition['order_id'] = $orderId;
            $sql = Common::format('update {0} set lock_state=lock_state+1 where order_id={1}', $this->_tableName, $orderId);
            $result = $this->db->update($this->_tableName)->query($sql);
            return $result;
        }
        return false;
    }

    //定单是否要锁
    public function getOrderLock($orderStatus)
    {
        if ($orderStatus = \Our\ApiConst::orderStateWaitRecieve) {
            return ApiConst::orderLockTwo;
        } else {
            return ApiConst::orderLockOne;
        }
    }

    /**
     * 查询店铺的总销量及订单总数
     * @param $where
     * @param $field
     * @return array
     */
    public function getOrderStats($where, $field)
    {
        $this->setDb($this->dbName);
        return $this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
    }

    /**
     * 更新数据
     * @param $data
     * @param $where
     * @return mixed
     */
    public function update($where, $data)
    {
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $data['gmt_update']=TIMESTAMP;
        return $this->db->update($this->_tableName)->where($where)->rows($data)->execute();
    }

    public function insert($data)
    {
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $data['gmt_update']=TIMESTAMP;
        $result = $this->db->insert($this->_tableName)->rows($data)->execute();
        return $result;
    }

    /**
     * 删除订单
     * @param $data
     * @param $where
     * @return mixed
     */
    public function deleteByOrderId($orderId)
    {
        $where['order_id'] = $orderId;
        $data['delete_state'] = ApiConst::deleteStateOne;
        return $this->update($where, $data);
    }

    public function updateStatusByOrderId($orderIds, $status, $isConfirm = false)
    {
        $this->setDb($this->dbName);
        if (is_array($orderIds)) {
            $where['order_id'] = array('in', $orderIds);
        } else {
            $where['order_id'] = $orderIds;
        }
        $where = $this->db->getSqlWhereByArray($where);
        $data['order_state'] = $status;
        $data['finnshed_time']=TIMESTAMP;
        if ($isConfirm) {
            $data['shipping_over'] = ApiConst::shippingOver;
        }
        return $this->update($where, $data);
    }

    //获取配送方式描述
    public function getPayTypeName($type)
    {
        $payName = '';
        switch ($type) {
            case ApiConst::offlinePay:
                $payName = DescribeConst::offPay;
                break;
            case ApiConst::wxpay:
                $payName = DescribeConst::wxPay;
                break;
            case
            ApiConst::afterSendPay:
                $payName = DescribeConst::afterPay;
                break;
            case ApiConst::alipay:
                $payName = DescribeConst::alipay;
                break;
            case ApiConst::tenpay:
                $payName = DescribeConst::tenPay;
                break;
            case ApiConst::wxProgram:
                $payName =  DescribeConst::wxProgrom;
                break;
            default:
                break;
        }
        return $payName;
    }

    //获取配送方式描述
    public function getShippingName($type)
    {
        $shippingName = '';
        switch ($type) {
            case ApiConst::bySelf:
                $shippingName = OrderConst::getOnShop;
                break;
            case ApiConst::bySeller:
                $shippingName = OrderConst::sellerSend;
                break;
            case
            ApiConst::express:
                $shippingName = OrderConst::express;
                break;
            default:
                break;
        }
        return $shippingName;
    }

    //获得运费类型名称
    public function getFreightFeeName($type)
    {
        if ($type != ApiConst::express) {
            return DescribeConst::serviceFee;
        } else {
            return DescribeConst::freightFee;

        }
    }

    /**
     * 获取订单及订单商品列表
     * @param $where
     * @param $field
     * @param $pageIndex
     * @param $pageSize
     * @return array
     */
    public function getOrders($where, $field, $pageIndex, $pageSize, $orderField = 'add_time', $sort = 'desc')
    {
        $this->setDb($this->dbName);
        $pageIndex = $pageIndex + \Our\ApiConst::one;
        $list = $this->db->select($field)->from($this->_tableName)
            ->join('han_order_common', $this->_tableName . '.order_id = han_order_common.order_id', 'left')
            ->where($where)->order($orderField, $sort)->page($pageIndex, $pageSize)->fetchAll();
        $totalCount = $this->db->select($field)->from($this->_tableName)
            ->join('han_order_common', $this->_tableName . '.order_id = han_order_common.order_id', 'left')
            ->where($where)->fetchNum();
        $returnData['orders'] = $list;
        $returnData['totalCount'] = $totalCount;
        return $returnData;
    }


    public function getList($where, $field, $pageIndex, $pageSize, $order = array('add_time' => 'desc'))
    {
        $this->setDb($this->dbName);
        if (is_array($where)) {
            $where = $this->db->getSqlWhereByArray($where);
        }
        $orders = $this->lists($where, $order, $field, $pageIndex, $pageSize);
        return $orders['list'] ? $orders : array();
    }

    public function getByOrderId($orderId, $field, $key = false)
    {
        if (is_array($orderId)) {
            $orderId = implode(',', $orderId);
            $where = Common::format(" order_id in ({0})", $orderId);
        } else {
            $where['order_id'] = $orderId;
        }
        $res = $this->getAllByWhere($where, $field);
        if (!empty($res)) {
            $returnResult=$res;
            if ($key) {
                $returnResult = array();
                foreach ($res as $re) {
                    $returnResult[$re[$key]] = $re;
                }
            }
            return $returnResult;
        } else {
            return [];
        }
    }

    public function getFieldByWhere($where,$filed){
        $this->setDb($this->dbName);
        if(is_array($where)){
            $where=$this->db->getSqlWhereByArray($where);
        }
        $res=$this->db->from($this->_tableName)->select($filed)->where($where)->fetchAll();
        if($res){
            $fie=array_column($res,$filed);
            return $fie;
        }else{
            return [];
        }
    }

    public function getSumAmountCountByMemberAndStoreId($storeIds,$memberIds)
    {
        $this->setDb($this->dbName);
        if(is_array($storeIds)){
            $storeIds=implode(',',$storeIds);
        }
        if(is_array($memberIds)){
            $memberIds=implode(',',$memberIds);
        }
        $where=Common::format(" store_id in({0}) and buyer_id in({1}) and order_state not in({2}) and refund_amount={3}",$storeIds,$memberIds,'-1,0',ApiConst::zero);
        $res=$this->db->from($this->_tableName)->where($where)->select(" buyer_id as buyerId,store_id as storeId,(SUM(order_amount)) AS orderTotal")->group('buyer_id')->group('store_id')->fetchAll();
        return $res;
    }

//待收货获取订单状态信息
    public function getOrderStatusExtent($order)
    {
        $orderText = '';
        if ($order['orderState'] == ApiConst::orderStateWaitRecieve) {
            $orderText = OrderConst::getOnShop;//默认到店自取
            if ($order['shippingType'] == ApiConst::express) {
                $orderText = OrderConst::waitRecieve;
            }
            if ($order['shippingType'] == ApiConst::bySeller) {
                $orderText = OrderConst::sendding;
            }
        }
        return $orderText;
    }

//获得列表状态信息
    public function getStatusText($order)
    {
        switch ($order['orderState']) {
            case ApiConst::orderStateCancel:
                $statusText = OrderConst::orderCancel;
                break;
            case ApiConst::orderStateWaitPay:
                $statusText = OrderConst::waitPay;
                break;
            case ApiConst::orderStateWaitConfirm:
                $statusText = OrderConst::waitConfirm;
                break;
            case ApiConst::orderStateWaitSend:
                $statusText = OrderConst::waitSend;
                break;
            case ApiConst::orderStateWaitRecieve:
                $statusText = $this->getOrderStatusExtent($order);
                break;
            case ApiConst::orderStateComplete:
                $statusText = OrderConst::complete;
                break;
            default:
                $statusText = OrderConst::close;
                break;
        }
        return $statusText;
    }

//待收货详情描述处理
    public function getStatusDetailTextExtent($order, $type = ApiConst::buyerText)
    {
        $orderText = '';
        if ($type == ApiConst::buyerText) {
            if ($order['orderState'] == ApiConst::orderStateWaitRecieve) {
                $orderText = OrderConst::waitGetFromShop;//默认到店自取
                if ($order['shippingType'] == ApiConst::express) {
                    $orderText = OrderConst::sellerSended;
                }
                if ($order['shippingType'] == ApiConst::bySeller) {
                    $orderText = OrderConst::sendding;
                }
            }
        }
        if ($type == ApiConst::storeText) {
            if ($order['orderState'] == ApiConst::orderStateWaitRecieve) {
                $orderText = OrderConst::waitGetFromShop;//默认到店自取
                if ($order['shippingType'] == ApiConst::express) {
                    $orderText = OrderConst::waitBuyerConfirmRecieve;
                }
                if ($order['shippingType'] == ApiConst::bySeller) {
                    $orderText = OrderConst::sendding;
                }
            }
        }

        return $orderText;
    }

    //获得买家文案详情
    private function getBuyerDetailText($order)
    {
        switch ($order['orderState']) {
            case ApiConst::orderStateCancel:
                $statusText = OrderConst::orderCancel;
                break;
            case ApiConst::orderStateWaitPay:
                $statusText = OrderConst::waitYouPay;
                break;
            case ApiConst::orderStateWaitConfirm:
                $statusText = OrderConst::waitSellerConfirm;
                break;
            case ApiConst::orderStateWaitSend:
                $statusText = OrderConst::waitSellerSend;
                break;
            case ApiConst::orderStateWaitRecieve:
                $statusText = $this->getStatusDetailTextExtent($order);
                break;
            case ApiConst::orderStateComplete:
                $statusText = OrderConst::orderComplete;
                break;
            default:
                $statusText = OrderConst::close;
                break;
        }
        return $statusText;
    }

    //获得店铺文案详情
    private function getStoreDetailText($order)
    {
        switch ($order['orderState']) {
            case ApiConst::orderStateCancel:
                $statusText = OrderConst::orderCancel;
                break;
            case ApiConst::orderStateWaitConfirm:
                $statusText = OrderConst::storeWaiteConfirm;
                break;
            case ApiConst::orderStateWaitSend:
                $statusText = OrderConst::storeWaiteSend;
                break;
            case ApiConst::orderStateWaitRecieve:
                $statusText = $this->getStatusDetailTextExtent($order);
                break;
            case ApiConst::orderStateComplete:
                $statusText = OrderConst::orderComplete;
                break;
            default:
                $statusText = OrderConst::close;
                break;
        }
        return $statusText;
    }

    //获取销售员订单详情描述
    public function getStatusSaleText($orderState)
    {
        switch ($orderState) {
            case ApiConst::orderStateCancel:
                $statusText = OrderConst::orderCancel;
                break;
            case ApiConst::orderStateWaitPay:
                $statusText = OrderConst::waitYouPay;
                break;
            case ApiConst::orderStateWaitConfirm:
                $statusText = OrderConst::waitSellerConfirm;
                break;
            case ApiConst::orderStateWaitSend:
                $statusText = OrderConst::waitSellerSend;
                break;
            case ApiConst::orderStateWaitRecieve:
                $statusText = OrderConst::waitRecieve;

                break;
            case ApiConst::orderStateComplete:
                $statusText = OrderConst::orderComplete;
                break;
            default:
                $statusText = OrderConst::close;
                break;
        }
        return $statusText;
    }


    //获取订单详情描述
    public function getStatusDetailText($order, $type = ApiConst::buyerText)
    {
        if (!in_array($type, array(ApiConst::buyerText, ApiConst::storeText, ApiConst::deliveryText))) {
            ErrorModel::throwException(CodeConfigModel::commonError);
        }
        if ($type == ApiConst::buyerText) {
            return $this->getBuyerDetailText($order);
        }
        if ($type == ApiConst::storeText) {

            return $this->getStoreDetailText($order);
        }
    }
    public function refundReturn($order){

    }
    //获得退款状态
    public function getRefundText($order)
    {
        $refundStateName = '';
        if ($order['paymentTime'] > ApiConst::zero) {
            if ($order['orderState'] == ApiConst::orderStateWaitSend) {
                $refundStateName = DescribeConst::refund;
            }
            if ($order['orderState'] == ApiConst::orderStateWaitRecieve && $order['shippingType'] == ApiConst::express) {
                $refundStateName = DescribeConst::refundRetund;
            }
            if ($order['orderState'] == ApiConst::orderStateWaitRecieve && $order['shippingType'] == ApiConst::bySeller) {
                $refundStateName = DescribeConst::refundRetund;
            }
            if ($order['orderState'] == ApiConst::orderStateWaitRecieve && $order['shippingType'] == ApiConst::bySelf) {
                $refundStateName = DescribeConst::refund;
            }
        }
        if ($order['paymentTime'] == ApiConst::zero) {
            if ($order['orderState'] == ApiConst::orderStateWaitRecieve && $order['shippingType'] == ApiConst::express) {
                $refundStateName = DescribeConst::refundRetund;
            }
        }
        $diff = TIMESTAMP - $order['finnshedTime'];
        if ($order['orderState'] == ApiConst::orderStateComplete) {
            if($diff < ApiConst::oneDaySecond && $order['shippingType']!=ApiConst::express){
                $refundStateName = DescribeConst::refundRetund;
            }
            if($diff < ApiConst::threeDaySecond && $order['shippingType']==ApiConst::express){
                $refundStateName = DescribeConst::refundRetund;
            }

        }
        
        return $refundStateName;

    }

    public function selectedTypeId($order)
    {
        $refundStateName = $this->getRefundText($order);
        $selectedRefundId = ApiConst::refundTypeMoney;
        if ($refundStateName == DescribeConst::refundRetund) {
            $selectedRefundId = ApiConst::refundTypeGoods;
        }
        return $selectedRefundId;
    }


    public function getText($order, $textType = ApiConst::orderListDescribe)
    {
        $text = '';
        //列表订单描述
        if ($textType == ApiConst::orderListDescribe) {
            //在未付款并且(不是线下支付或者到货付款的情况下提示此消息
            if ($order['orderState'] == ApiConst::orderStateWaitPay && $order['paymentType'] != ApiConst::offlinePay && $order['paymentType'] != ApiConst::afterSendPay) {
                $text = OrderConst::unpayMessage;
            }
            if((TIMESTAMP-$order['paymentTime'])<ApiConst::tenMinSecond){
                $text = OrderConst::payCancelMessage;
            }
//            if ($order['orderState'] == ApiConst::orderStateWaitConfirm && $order['paymentType'] != ApiConst::offlinePay && $order['paymentType'] != ApiConst::afterSendPay) {
//                if($order['orderState']==ApiConst::orderStateClose && $order['orderState']==ApiConst::orderStateCancel){
//                    $test='';
//                }else{
//                    $text = OrderConst::payCancelMessage;
//                }
//            }
        }
        //详情
        if ($textType == ApiConst::orderDetailDescribe) {
            //在未付款并且(不是线下支付或者到货付款的情况下提示此消息
            if ($order['orderState'] == ApiConst::orderStateWaitPay && $order['paymentType'] != ApiConst::offlinePay && $order['paymentType'] != ApiConst::afterSendPay) {
                $text = OrderConst::unpayDetailMessage;
            }
            if ($order['orderState'] == ApiConst::orderStateWaitConfirm && $order['paymentType'] != ApiConst::offlinePay && $order['paymentType'] != ApiConst::afterSendPay) {
                $text = OrderConst::unpayDetailMessage;
            }
        }

        return $text;
    }

    /**
     * 获取单条订单详情
     * @param $where
     * @return mixed
     */
    public function getOrderDetail($where)
    {
        $this->setDb();
        $table = $this->_tableName;
        $field = array(
            $table . '.*',
            'han_order_common' . '.*',
            'han_order_goods' . '.*',
        );
        $data = $this->db->select($field)->from($this->_tableName)
            ->join('han_order_common', $this->_tableName . '.order_id = han_order_common.order_id', 'left')
            ->join('han_order_goods', $this->_tableName . '.order_id = han_order_goods.order_id', 'left')
            ->where($where)->fetchAll();
        return $data;
    }

    /**
     * 返回是否允许某些操作
     * @param unknown $operate
     * @param unknown $order_info
     */
    public function getOrderOperateState($operate, $orderInfo)
    {

        if (!is_array($orderInfo) || empty($orderInfo)) return false;
        switch ($operate) {
            //买家取消订单
            case NameConst::buyerCancel:
                $state = ($orderInfo['orderState'] == ApiConst::orderStateWaitPay) ||
                    ($orderInfo['paymentCode'] == 'offline' && $orderInfo['orderState'] == ApiConst::orderStateWaitPay);
                $this->errorMessage = CodeConfigModel::buyerCancelError;
                break;

            //申请退款
            case NameConst::refundCancel:
                $state = $orderInfo['refund'] == ApiConst::one && !intval($orderInfo['lockState']);
                $this->errorMessage = CodeConfigModel::refundCancelError;
                break;

            //商家取消订单
            case NameConst::storeCancel:
                $state = ($orderInfo['orderState'] == ApiConst::orderStateWaitPay) ||
                    ($orderInfo['paymentCode'] == 'offline' &&
                        in_array($orderInfo['orderState'], array(ApiConst::orderStateWaitSend, ApiConst::orderStateWaitRecieve)));
                $this->errorMessage = CodeConfigModel::storeCancelError;
                break;

            //平台取消订单
            case NameConst::systemCancel:
                $state = ($orderInfo['orderState'] == ApiConst::orderStateWaitPay) ||
                    ($orderInfo['paymentCode'] == 'offline' && $orderInfo['orderState'] == ApiConst::orderStateWaitConfirm);
                $this->errorMessage = CodeConfigModel::systemCancelError;
                break;

            //平台收款
            case NameConst::systemReceivePay:
                $state = $orderInfo['orderState'] == ApiConst::orderStateWaitPay && $orderInfo['paymentCode'] == 'online';
                $this->errorMessage = CodeConfigModel::systemReceivePayError;
                break;

            //买家投诉
            case NameConst::complain:
                $state = in_array($orderInfo['orderState'], array(ApiConst::orderStateWaitSend, ApiConst::orderStateWaitRecieve)) ||
                    intval($orderInfo['finnshedTime']) > (TIMESTAMP - ApiConst::complainTimeLimit);
                $this->errorMessage = CodeConfigModel::complainError;
                break;

            case NameConst::payment:
                $state = $orderInfo['orderState'] == ApiConst::orderStateWaitPay && $orderInfo['paymentCode'] == 'online';
                $this->errorMessage = CodeConfigModel::paymentError;
                break;

            //调整运费
            case NameConst::modifyPrice:
                $state = ($orderInfo['orderState'] == ApiConst::orderStateWaitPay) ||
                    ($orderInfo['paymentCode'] == 'offline' && $orderInfo['orderState'] == ApiConst::orderStateWaitSend);
                $state = floatval($orderInfo['shipping_fee']) > 0 && $state;
                $this->errorMessage = CodeConfigModel::modifyPriceError;
                break;
            //调整商品价格
            case NameConst::spayPrice:
                $state = ($orderInfo['orderState'] == ApiConst::orderStateWaitPay) ||
                    ($orderInfo['paymentCode'] == 'offline' && $orderInfo['orderState'] == ApiConst::orderStateWaitSend);
                $state = floatval($orderInfo['goods_amount']) > 0 && $state;
                $this->errorMessage = CodeConfigModel::spayPriceError;
                break;

            //发货
            case NameConst::send:
                $state = !$orderInfo['lockState'] && $orderInfo['orderState'] == ApiConst::orderStateWaitSend;
                $this->errorMessage = CodeConfigModel::sendError;
                break;

            //收货
            case NameConst::receive:
                $state = !$orderInfo['lockState'] && $orderInfo['orderState'] == ApiConst::orderStateWaitRecieve;
                $this->errorMessage = CodeConfigModel::receiveError;
                break;

            //评价
            case NameConst::evaluation:
                $state = !$orderInfo['lockState'] && !$orderInfo['evaluationState'] && $orderInfo['orderState'] == ApiConst::orderStateComplete;
                $this->errorMessage = CodeConfigModel::evaluationError;
                break;

            //锁定
            case NameConst::lock:
                $state = intval($orderInfo['lockState']) ? TRUE : FALSE;
                $this->errorMessage = CodeConfigModel::lockError;
                break;

            //快递跟踪
            case NameConst::deliver:
                $state = !empty($orderInfo['shippingCode']) && in_array($orderInfo['orderState'], array(ApiConst::orderStateWaitRecieve, ApiConst::orderStateComplete));
                $this->errorMessage = CodeConfigModel::deliverError;
                break;

            //放入回收站
            case NameConst::delete:
                $state = in_array($orderInfo['orderState'], array(ApiConst::orderStateCancel, ApiConst::orderStateComplete,ApiConst::orderStateClose)) && $orderInfo['deleteState'] == ApiConst::zero;
                $this->errorMessage = CodeConfigModel::deleteError;
                break;

            //永久删除、从回收站还原
            case NameConst::restore:
                $state = in_array($orderInfo['orderState'], array(ApiConst::orderStateCancel, ApiConst::orderStateComplete)) && $orderInfo['deleteState'] == ApiConst::one;
                $this->errorMessage = CodeConfigModel::restoreError;
                break;

            //分享
            case NameConst::share:
                $state = true;
                $this->errorMessage = CodeConfigModel::shareError;
                break;

        }
        return $state;

    }

    //删除订单详情缓存
    public function deleteFindByOrderIdCache($orderId)
    {
        return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'findByOrderId'), array(),array($orderId));
    }

    //删除订单列表缓存
    public function deleteGetShopKeeperCountByStoreId($storeId)
    {
        return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getShopKeeperCountByStoreId'), array(),array($storeId));
    }

    //删除订单列表缓存
    public function deleteGetListByMemberId($memberId)
    {
        return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getList'), array(), array($memberId));
    }

    //删除订单缓存
    public function deleteOrderCache($memberId, $orderId = false, $stroeId = false, $deleteGetShopKeeperCountByStoreId = false, $deleteGetFavoritesCountByStoreId = false,$diliverymanId=ApiConst::zero)
    {

        if (!empty($memberId)) {
            $this->deleteGetListByMemberId($memberId);
            \DAO\MemberModel::getInstance()->deleteTotalCache($memberId);
        }
        if (!empty($stroeId)) {
            if ($deleteGetShopKeeperCountByStoreId) {
                $this->deleteGetShopKeeperCountByStoreId($stroeId);
            }
            if ($deleteGetFavoritesCountByStoreId) {
                $favoritesStoreDao = \DAO\FavoritesStoreModel::getInstance();
                $favoritesStoreDao->deleteGetFavoritesCountByStoreId($stroeId);

            }
            $this->deleteGetListByMemberId($stroeId);
            $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);

            \DAO\Store\MemberFavoritesStoreStoreMemberStatisticsModel::getInstance()->deleteCacheGetGoodsCountOrderTotalByStoreId($stroeId);
            $orderGoodsDao->deleteOrderGoodsCache($memberId, $orderId,$stroeId);
        }

        if(!empty($diliverymanId)){
            $this->deleteGetListByMemberId($diliverymanId);
            $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
            $orderGoodsDao->deleteOrderGoodsCache($diliverymanId, $orderId);
            $QmDeliveryLogDao = \DAO\Order\QmDeliverymanLogModel::getInstance(DbNameConst::salveDBConnectName);
            $QmDeliveryLogDao->deleteOrderCache($diliverymanId,$orderId);
        }

        if (!empty($orderId)) {
            $this->deleteFindByOrderIdCache($orderId);
            $orderGoodsDao = \DAO\Order\OrderGoodsModel::getInstance(DbNameConst::masterDBConnectName);
            $orderGoodsDao->deleteOrderGoodsCache($memberId, $orderId);
            $orderCommonDao= \DAO\Order\OrderCommonModel::getInstance(DbNameConst::masterDBConnectName);
            \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$orderCommonDao, 'findByOrderId'), array(),array($orderId));
//            $orderService=\Business\Order\OrderServiceModel::getInstance();
//            \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(),array(&$orderService, 'getExpressInfo'),array(),array($orderId));
        }
        return true;

    }

    //任务脚本方法
    public function getOrdersByOrderState($orderState, $timeField = 'add_time', $timeLimit = ApiConst::orderStateWaitConfirmBeyond, $field = '*', $shippingTypes = false)
    {
        $this->setDb($this->dbName);
        $where['order_state'] = $orderState;
        $limit = TIMESTAMP - $timeLimit;
        $where[$timeField] = array('lt', $limit);
        if ($shippingTypes) {
            $where['shipping_type'] = array('in', $shippingTypes);
        }
        $where = $this->db->getSqlWhereByArray($where);
        $list = $this->db->select($field)->from($this->_tableName)->where($where)->fetchAll();
        return $list;
    }
    //任务脚本方法
    public function getMustCecelRecieveOrders($beginTime=ApiConst::zero, $endTime, $field = '*')
    {
        $this->setDb($this->dbName);
        $where=Common::format(" add_time between {0} and {1} and order_state={2}",$beginTime,$endTime,ApiConst::orderStateWaitConfirm);
        $list = $this->db->select($field)->from($this->_tableName)->where($where)->order('add_time','desc')->fetchAll();
        return $list;
    }
    //任务脚本方法
    public function getMustCecelOrders($beginTime=ApiConst::zero, $endTime, $field = '*')
    {
        $this->setDb($this->dbName);
        $where=Common::format(" add_time between {0} and {1} and order_state={2}",$beginTime,$endTime,ApiConst::orderStateWaitPay);
        $list = $this->db->select($field)->from($this->_tableName)->where($where)->order('add_time','desc')->fetchAll();
        return $list;
    }
    //任务脚本方法
    public function updateNotRecieveOrders($beginTime=ApiConst::zero, $endTime, $field = '*')
    {
        $this->setDb($this->dbName);
        $where=Common::format(" payment_time between {0} and {1} and order_state={2}",$beginTime,$endTime,ApiConst::orderStateWaitConfirm);
        return $this->db->update($this->_tableName)->where($where)->rows(array('order_state' => ApiConst::orderStateClose))->execute();
    }

    //任务脚本方法
    public function getRecieveOrders($orderState, $addTime, $pageIndex, $pageSize, $timeField = 'add_time')
    {
        $this->setDb($this->dbName);
        $where['order_state'] = ApiConst::orderStateWaitConfirm;
        $where = Common::format(' order_state={0} and {1}>={2} and {1}<{3}', $orderState, $timeField, $addTime, TIMESTAMP);
        $list = $this->lists($where, array('add_time' => 'asc'), $this->getOrderDetailField(), $pageIndex, $pageSize);
        return $list;
    }


    //任务脚本方法
    public function updateOrdersByorderState($orderState, $toState, $timeField = 'add_time', $timeLimit = ApiConst::orderStateWaitConfirmBeyond)
    {
        $this->setDb($this->dbName);
        $where['order_state'] = $orderState;
        $limit = TIMESTAMP - $timeLimit;
        $where[$timeField] = array('lt', $limit);
        $where = $this->db->getSqlWhereByArray($where);
        return $this->db->update($this->_tableName)->where($where)->rows(array('order_state' => $toState,'gmt_update'=>$toState))->execute();


    }


    /**
     * 获取订单列表
     * @param $where
     * @param string $field
     * @return mixed
     */
    public function getListByCon($where, $field = \Our\NameConst::allField)
    {
        $this->setDb($this->dbName);
        if (is_array($where)) {
            $where = $this->db->getSqlWhereByArray($where);
        }
        $result = $this->db->select($field)->from($this->_tableName)->where($where)->fetchAll();
        return $result;
    }


    public function getShippingTypeSellerOrdersByOrders($orders)
    {
        $shippingTypeOrderIds = array();
        foreach ($orders as $order) {
            if ($order['shippingType'] == ApiConst::bySeller) {
                array_push($shippingTypeOrderIds, $order['orderId']);
            }
        }
        return $shippingTypeOrderIds;
    }

    public function getConvertOrder($order, $fields = array())
    {
        $convertResult = array();
        foreach ($fields as $key => $field) {
            $convertResult[$key] = $order[$field];
        }
        return $convertResult;
    }

    public function getFields()
    {
        return array(
            'orderId' => 'order_id',
            'orderSn' => 'order_sn',
            'storeId' => 'store_id',
            'storeName' => 'store_name',
            'addTime' => 'add_time',
            'paymentTime' => 'payment_time',
            'finnshedTime' => 'finnshed_time',
            'goodsAmount' => 'goods_amount',
            'orderAmount' => 'order_amount',
            'shippingType' => 'shipping_type',
            'shippingFee' => 'shipping_fee',
            'paymentType' => 'payment_type',
            'orderState' => 'order_state',
            'refundState' => 'refund_state',
            'refundAmount' => 'refund_amount',
            'diliverymanId' => 'diliveryman_id',
            'deliveryDistance' => 'delivery_distance',
            'shippingArrivalTime' => 'shipping_arrival_time',
            'couponId' => 'coupon_id',
            'orderType' => 'order_type',
            'buyerId' => 'buyer_id',
            'deliveryTime' => 'delivery_time',
            'evaluationState'=>'evaluation_state',
        );
    }

    public function getOrderAndOrderGoods($where, $field, $group = false, $limit = [], $order = [])
    {
        $this->setDb($this->dbName);
        $str = '$result = $this->db->select($field)->from($this->_tableName)->where($where)';
        $str .= "->join('han_order_goods','han_order.order_id = han_order_goods.order_id','inner')";

        $group && $str .= '->group($group)';
        $limit && $str .= '->limit($limit[0],$limit[1])';
        $order && $str .= '->order($order[0],$order[1])';
        $str .= '->fetchAll();';
        eval($str);
        return $result;
    }

    public function getAllByWhere($where, $field)
    {
        $this->setDb($this->dbName);
        if (is_array($where)) {
            $where = $this->db->getSqlWhereByArray($where);
        }
        return $this->db->select($field)->from($this->_tableName)->where($where)->fetchAll();
    }

    public function updateCancelUnpayedOrderTimeCache($time)
    {
        \Redis\Db5\OrderRedisModel::getInstance()->tableCacheSet(\Our\NameConst::cancelUnPayedOrderTimePrefix, $time);
    }


    public function getCancelUnpayedOrderTimeCache()
    {
        $res = \Redis\Db5\OrderRedisModel::getInstance()->tableCacheGet(\Our\NameConst::cancelUnPayedOrderTimePrefix);
        echo 'abcd' . json_encode($res);
        return \Redis\Db5\OrderRedisModel::getInstance()->tableCacheGet(\Our\NameConst::cancelUnPayedOrderTimePrefix);
    }

    public function updateCancelUnReceivedOrderTimeCache($time)
    {
        \Redis\Db5\OrderRedisModel::getInstance()->tableCacheSet(\Our\NameConst::cancelUnReceivedOrderTimePrefix, $time);
    }

    public function getCancelUnReceivedOrderTimeCache()
    {
        return \Redis\Db5\OrderRedisModel::getInstance()->tableCacheGet(\Our\NameConst::cancelUnReceivedOrderTimePrefix);
    }

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


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

        return self::$_instance;
    }

}
