<?php

namespace DAO\Store;
use Our\ApiConst;
use Our\Common;
use Redis\Db6\StoreRedisModel;
/**
 * 店铺数据统计
 * @date 2018-5-14
 * @author csw
 */
class MemberFavoritesStoreStoreMemberStatisticsModel extends \DAO\AbstractModel {


    protected $redis;

    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_member-favorites_store-store_member_statistics';
    public $sumField='sum(order_total) as orderTotal,sum(order_goods_count) as orderGoodsCount';

    public $field="fav_type as favType,member_id as memberId,member_mobile as memberMobile,is_backlist as isBacklist,fav_time as favTime,member_avatar as memberAvatar,member_name as memberName,order_total as orderTotal,order_goods_count as orderGoodsCount";
    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';

    public function init(){
        $this->setDb();
    }
    /**
     * 获取店铺统计信息
     * @param $where
     * @return array
     */
    public function find($where) {
        $this->setDb($this->dbName);
        $field = $this->_getColumns();
        $data=$this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
        return $data;
    }


    public function getById($id){
        $where['id']=$id;
        $res=$this->find($where);
        return $res;
    }
    public function getSortBySortType($sortType){
        $order=array("fav_time"=>'asc');
        switch($sortType){
            case ApiConst::favTimeAsc: $order=array("fav_time"=>'asc');break;
            case ApiConst::favTimeDesc: $order=array("fav_time"=>'desc');break;
            case ApiConst::orderTotalAsc: $order=array("order_total"=>'asc');break;
            case ApiConst::orderTotalDesc: $order=array("order_total"=>'desc');break;
            default:break;
        }
        return $order;
    }
    public function getList($storeId, $pageIndex, $pageSize, $sort, $keyword=''){
        $this->setDb($this->dbName);
        $whereStr=" store_id=".$storeId;
        if(!empty($keyword)){
            $whereStr.=Common::format(" and(member_name like '%{0}%' or member_mobile like '%{0}%') ",$keyword);
        }
        $result=$this->lists($whereStr, $sort, $this->field, $pageIndex, $pageSize);
        if(!empty($result['list'])){
            $result['list']=$this->getListNotNull($result['list']);
            foreach($result['list'] as $key=>$val){
                if($val['favType']==ApiConst::two){
                    $result['list'][$key]['isBacklist']=ApiConst::one;
                }else{
                    $result['list'][$key]['isBacklist']=ApiConst::zero;
                }
               // $result['list'][$key]['isBacklist']=$val['isBacklist']?$val['isBacklist']:ApiConst::zero;
                $result['list'][$key]['orderTotal']=$val['orderTotal']?$val['orderTotal']:ApiConst::zero;
                $result['list'][$key]['orderGoodsCount']=$val['orderGoodsCount']?$val['orderGoodsCount']:ApiConst::zero;
            }
        }
        return $result;
    }
    /**
     * 更新数据
     * @param $data
     * @param $where
     * @return mixed
     */
    public function update($data,$where){
        return $this->db->update($this->_tableName)->where($where)->rows($data)->execute();
    }

    /**
     * 插入数据
     * @param $data
     * @return mixed
     */
    public function insert($data){
        return $this->db->insert($this->_tableName)->rows($data)->execute();
    }

    /**
     * @param $storeId 店铺id
     * @param $field 更新栏目
     * @param $value 增加值
     * @param $type,'INC':增加,'DEC':减少
     */
    public function updateStoreStatisticsToday($storeId,$field,$value,$type='INC'){
        $h = 'todayData'.date('Ymd');
        $key = $storeId;
        $this->redis = StoreRedisModel::getInstance();
        $data = $this->redis->tableHGet($h,$key);
        $data[$field] = $type=='INC' ? $data[$field] + $value : $data[$field] - $value;
        StoreRedisModel::tableHSet($h,$storeId,$data,ApiConst::oneDaySecond);
    }

    public function getInfoById($id,$field='*',$isField=false){
        $this->setDb();
        $where[$this->_primaryKey]=$id;
        $store=$this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        if($isField){
            return $store[$isField];
        }else{
            return $store;
        }

    }
    public function getInfoByMemberId($memberId,$field='*',$isField=false)
    {
        $this->setDb($this->dbName);
        $where['member_id'] =  $memberId;
        $store = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        if ($isField) {
            return $store[$isField];
        } else {
            return $store;
        }
    }
    public function getGoodsCountOrderTotalByStoreId($storeId){
        $this->setDb($this->dbName);
        $where['store_id']=$storeId;
        $res=$this->db->from($this->_tableName)->select($this->sumField)->where($where)->fetchOne();
        return $res?$res:[];
    }
    public function deleteCacheGetGoodsCountOrderTotalByStoreId($storeId){
        return \Our\RedisHelper::delCachedFunction(\Redis\Db6\OrderRedisModel::getInstance(), array(&$this, 'getGoodsCountOrderTotalByStoreId'), array(),array($storeId));
    }
    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * 获取字段
     * @return array
     */
    private function _getColumns() {
        return array(
            'store_id as storeId',
            'order_count as orderCount',
            'order_total as orderTotal',
            'fav_count as favCount',
            'goods_count as goodsCount',
        );
    }

}
