<?php

namespace DAO;


use OSS\Common;
use Our\ApiConst;

class FavoritesStoreModel extends \DAO\AbstractModel {



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

    public $favoriteMemberCountField='favid as favid,store_id as storeId,fav_time as favTime';
    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'favid';
    public function init(){

    }

    public function getList($where,$field,$pageIndex,$pageSize,$memberId){
        $this->setDb($this->dbName);
        return $this->db->select($field)->from($this->_tableName)->join('han_store',"han_favorites_store.store_id = han_store.store_id",'inner')->join('han_store_score_statistics',"han_favorites_store.store_id = han_store_score_statistics.store_id",'left')->where(['han_favorites_store.member_id'=>$memberId,'fav_type'=>1])->where($where)->page($pageIndex,$pageSize)->order('fav_time','DESC')->fetchAll();
    }

    public function selectList($where,$field = \Our\NameConst::allField,$order=array('fav_time'=>'desc')){
        $this->setDb($this->dbName);
        if(is_array($where)){
            $where = $this->db->getSqlWhereByArray($where);
        }
        $this->db->select($field)->from($this->_tableName)->where($where);
        foreach($order as $key=>$val){
            $this->db->order($key,$val);
        }
        return $this->db->fetchAll();
    }

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

    public function insert($param){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result = $this->db->insert($this->_tableName)->rows($param)->execute();
        if($result){
            if($param&&(isset($param['member_id'])&&$param['member_id'])){
                \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($param['member_id']));
            }
        }
        return $result;
    }

    public function update($param,$where,$del = false,$memberId = null){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        if($del){
            $result  = $this->db->update($this->_tableName)->rows($param)->where(array('member_id'=>$memberId))->where($where)->execute();
            if($result){
                \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($memberId));
            }
            return $result;
        }
        $result = $this->db->update($this->_tableName)->rows($param)->where($where)->execute();
        if($result){
            $temp = $this->getOne('member_id',$param);
            \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($temp['member_id']));
        }
        return $result;
    }
    public function getFavoritesStoreCount($where){
        $this->setDb($this->dbName);
        return $this->db->from($this->_tableName)->where($where)->fetchNum();
    }

    public function getFavoritesCountByStoreId($storeId){
        $where=\Our\Common::format(" store_id={0}",$storeId);
        $total['favCount']=$this->getFavoritesStoreCount($where);
        $todayBegin=strtotime(date('Y-m-d',TIMESTAMP));
        $todayEnd=TIMESTAMP;
        $where.=\Our\Common::format( " and fav_time between {0} and {1}",$todayBegin,$todayEnd);
        $total['todayFavCount']=$this->getFavoritesStoreCount($where);
        return $total?$total:array();
    }
//删除订单列表缓存
    public function deleteGetFavoritesCountByStoreId($storeId)
    {
        return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getFavoritesCountByStoreId'), array(), array($storeId));
    }
    public function getFavoritesCountByStoreIdCache($storeId){
        return \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getFavoritesCountByStoreId'), array($storeId), \Our\ApiConst::oneDaySecond,array($storeId));
    }

    public function insertOrUpdate($data){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $baseSql = "insert  into {$this->_tableName}(member_id,store_id,fav_type,fav_time) values({0},{1},1,{2}) ON DUPLICATE KEY UPDATE fav_type=1,fav_time=VALUES (fav_time)";
        $sql = \Our\Common::format($baseSql, $data['member_id'], $data['store_id'],$data['fav_time']);
        $result = $this->db->insert($this->_tableName)->query($sql);
        if($result){
            if($data&&(isset($data['member_id'])&&$data['member_id'])){
                \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($data['member_id']));
            }
        }
        return $result;
    }

    public function insertAll($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert IGNORE into {$this->_tableName}(member_id,store_id,fav_from,fav_time) values";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("('{0}','{1}','{2}','{3}'),", $datas[$i]['member_id'], $datas[$i]['store_id'], $datas[$i]['fav_from'],TIMESTAMP);
            \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($datas[$i]['member_id']));
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertAllSql .= 'ON DUPLICATE KEY UPDATE fav_time=VALUES (fav_time)';
                $one = $this->db->insert($this->_tableName)->query($insertAllSql);
                if (!$one) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertAllSql .= 'ON DUPLICATE KEY UPDATE fav_time=VALUES (fav_time)';
            $one = $this->db->insert($this->_tableName)->query($insertAllSql);

            if (!$one) {
                $error++;
            }
        }
        if ($error > 0) {
            return false;
        }
        return true;
    }

    /**
     * 批量添加
     * @param $datas
     */
    public function addBatch($datas){
        parent::setDb(\Our\DbNameConst::masterDBConnectName);

        $sql = "INSERT INTO {$this->_tableName} ( store_id,member_id,fav_from,fav_time) values";
        foreach($datas as $key => $data){
            $sql .=\Our\Common::format(" (store_id={0} and member_id = {1} and fav_from={2} ),",$data['storeId'],$data['memberId'],$data['type']);
            \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($data['memberId']));
        }
        $sql = trim($sql,',');
        $sql .= ";";
        $res = $this->db->insert($this->_tableName)->query($sql);
        return $res;
    }

    public function getFavoritesStoreCountByStoreId($storeId, $num = 0) {
        $statisticsDb6Redis = \Redis\Db6\StatisticsRedisModel::getInstance();
        $collectCount = $statisticsDb6Redis->tableCacheGet('storeCollectCount:'.$storeId);
        if($collectCount === false) {
            $collectCount = $this->getFavoritesStoreCount(array('store_id'=>$storeId,'fav_type'=>1));
            $statisticsDb6Redis->tableCacheSet('storeCollectCount:'.$storeId, $collectCount, \Our\ApiConst::sevenDaySecond);
            return $collectCount;
        }
        if($num == 1) {
            $collectCount = $statisticsDb6Redis->tableIncr('storeCollectCount:'.$storeId);
        }elseif ($num == -1) {
            $collectCount = $statisticsDb6Redis->tableDecr('storeCollectCount:'.$storeId);
        }
        return $collectCount;
    }
    /**
     * 批量插入关注数据
     * @param $datas
     * @return bool
     */
    public function insertBatch($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert IGNORE into {$this->_tableName}(member_id,store_id,fav_time,fav_from) values";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("('{0}','{1}','{2}','{3}'),", $datas[$i]['member_id'], $datas[$i]['store_id'], $datas[$i]['fav_time'], $datas[$i]['fav_from']);
            \Our\RedisHelper::delCachedFunction(\Redis\Db6\FavoritesStoreRedisModel::getInstance(), array(&$this, 'selectList'), array() ,array($datas[$i]['member_id']));
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $one = $this->db->insert($this->_tableName)->query($insertAllSql);
                if (!$one) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $one = $this->db->insert($this->_tableName)->query($insertAllSql);

            if (!$one) {
                $error++;
            }
        }
        if ($error > 0) {
            return false;
        }
        return true;
    }
    /**
     * 获取店铺关注统计
     * @param $where
     * @return bool
     */
    public function getFavCount($where){
        $this->setDb($this->dbName);
        return $this->db->from($this->_tableName)->where($where)->fetchNum();
    }

    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();
    }
    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

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

        return self::$_instance;
    }

}
