<?php

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


    protected $redis;

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

    /**
     * 主键
     *
     * @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 deleteGetByStoreIdCache($storeId){
        \Our\RedisHelper::delCachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$this, 'getByStoreId'), array(), array($storeId));
    }
    public function getByStoreId($storeId){
        $where['store_id']=$storeId;
        $res=$this->find($where);
        return $res?$res:array();
    }

    /**
     * 更新数据
     * @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 addAll($datas)
    {
        $this->setDb(DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}(store_id,order_count,order_total,fav_count,add_time) values";
        $extentSql=" ON DUPLICATE KEY UPDATE order_count=order_count+values(order_count),order_total=order_total+values(order_total),fav_count=fav_count+values(fav_count),add_time=values(add_time)";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("({0},{1},{2},{3},{4}),", $datas[$i]['storeId'], $datas[$i]['orderCount'], $datas[$i]['orderTotal'], $datas[$i]['favCount'],TIMESTAMP);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertSql=$insertAllSql.$extentSql;
                $one = $this->db->insert($this->_tableName)->query($insertSql);
                if (!$one) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertSql=$insertAllSql.$extentSql;
            $one =  $this->db->insert($this->_tableName)->query($insertSql);
            if (!$one) {
                $error++;
            }
        }
        if ($error > 0) {
            $dataJson=json_encode($datas);
            throw  new Exception('插入han_store_statics_day失败,'.$dataJson, 4);
        }
    }
    public function getInfoByMemberId($memberId,$field='*',$isField=false)
    {
        $this->setDb();
        $where['member_id'] =  $memberId;
        $store = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        if ($isField) {
            return $store[$isField];
        } else {
            return $store;
        }
    }

    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;
    //插入数据大量
    public $insertFields="store_id,order_count,order_total,order_total_online,fav_count,goods_count,add_time";
    public function addOrUpdate($data)
    {
        $this->setDb(DbNameConst::masterDBConnectName);
        $baseSql = "insert into {$this->_tableName}({$this->insertFields}) values";
        $addSql = \Our\Common::format("({0},{1},{2},{3},{4},{5},{6}) ", $data['storeId'],$data['orderCount'], $data['orderTotal'],$data['orderTotalOnline'], $data['favCount'], $data['goodsCount'],TIMESTAMP);
        $extentSql=" ON DUPLICATE KEY UPDATE order_count=values(order_count),order_total=values(order_total),order_total_online=values(order_total_online),fav_count=values(fav_count),goods_count=values(goods_count),add_time=".TIMESTAMP;
        $excuteSql=$baseSql.$addSql.$extentSql;
        $one = $this->db->insert($this->_tableName)->query($excuteSql);
        return $one;

    }
    /**
     * 获取类实例
     *
     * @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',
            'order_total_online as orderTotalOnline',
        );
    }

}
