<?php

namespace DAO\Order;

use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;
use Our\ImageConst;


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

    public $fieldList = 'id,finish_time finishTime,get_time as getTime,order_id as orderId';
    public $fieldDetail = 'id,finish_time finishTime,get_time as getTime,order_id as orderId,delivery_state as deliveryState,order_type as orderType';

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

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';

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

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

    public function updateStatusById($id)
    {
        $where['id'] = $id;
        $data['delivery_state'] = ApiConst::deliveryStateComplete;
        $data['finish_time'] = TIMESTAMP;
        return $this->update($where, $data);
    }

    /**
     * 获取配送员列表
     * @param $where
     * @param $field
     * @param $pageIndex
     * @param $pageSize
     * @return array
     */
    public function getList($where, $field, $pageIndex, $pageSize, $order = array('get_time' => 'desc'))
    {
        $this->setDb($this->dbName);
        if (is_array($where)) {
            $where = $this->db->getSqlWhereByArray($where);
        }
        $list = $this->lists($where, $order, $field, $pageIndex, $pageSize);
        return $list ? $list : array();
    }

    /**
     * 更具状态获得配送订单列表
     * @param $where
     * @param $field
     * @param $pageIndex
     * @param $pageSize
     * @return array
     */

    public function getListByDeliverymanIdAndType($diliveryId, $type, $pageIndex, $pageSize, $order = array('get_time' => 'desc'))
    {
        $this->setDb($this->dbName);
        $where['diliveryman_id'] =array('in',$diliveryId);

        if ($type == ApiConst::orderTypeBuy) {
            $where['order_type'] = ApiConst::orderTypeBuy;
            $where['delivery_state'] = ApiConst::deliveryStateWait;
        }
        if ($type == ApiConst::orderTypeRefund) {
          //  $where=Common::format(" diliveryman_id in ({0}) and order_type={1} and (delivery_state={2} or delivery_state={3})",$diliveryId,ApiConst::orderTypeRefund,ApiConst::deliveryStateWait,ApiConst::deliveryStateWaitTen);
            $where['order_type'] = ApiConst::orderTypeRefund;
            $where['delivery_state'] = ApiConst::deliveryStateWait;
        }
        if ($type == ApiConst::deliveryStateWait) {
            $where['delivery_state'] = ApiConst::deliveryStateComplete;
        }
        if(is_array($where)){
            $where=$this->db->getSqlWhereByArray($where);
        }

        if($type==ApiConst::deliveryStateComplete){
            $order = array('finish_time' => 'desc');
        }
        $list = $this->lists($where, $order, $this->fieldList, $pageIndex, $pageSize);
        return $list;
    }

    public function getListByDeliverymanIdAndTypeCache($diliveryId, $type, $pageIndex, $pageSize, $order = array('get_time' => 'desc'),$memberId)
    {
        return \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getListByDeliverymanIdAndType'), array($diliveryId, $type, $pageIndex, $pageSize, $order), ApiConst::oneDaySecond, array($memberId));
    }

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

    public function findById($id)
    {
        $this->setDb($this->dbName);
        $where[$this->_primaryKey] = $id;
        return $this->find($where);
    }

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


    public function convert($info, $keyValues, $imageField = 'qrcode_path')
    {
        $convertInfo = array();
        foreach ($keyValues as $key => $val) {
            if ($key != $imageField) {
                $convertInfo[$val] = $info[$key];
            } else {
                $convertInfo[$val] = \Our\Common::getStaticFile($info[$key], ImageConst::memberAvatar);
            }
        }
        return $convertInfo;
    }

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

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

    //删除订单缓存
    public function deleteOrderCache($deliveryId, $id)
    {
        $this->deleteGetListByDeliverymanIdAndType($deliveryId);
        $this->deletefindByIdCache($id);
    }

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

    }

    //任务脚本方法
    public function getFinishDeliveryByOrderId($orderIds=false)
    {
        $where['order_type'] = ApiConst::orderTypeBuy;
        $where['delivery_state'] = ApiConst::deliveryStateComplete;
        if(is_array($orderIds)){
            $where['order_id'] = array('in', $orderIds);
        }else{
            $where['order_id']=$orderIds;
        }
        $limitTime=TIMESTAMP-ApiConst::deliveryFinishTwentyFourHours;
        $where['finish_time']=array('lt',$limitTime);
        $res=$this->getAllByWhere($where);
        return $res;
    }

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

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */

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

        return self::$_instance;
    }

}
