<?php
namespace DAO\Goods;
/**
 * User: liuyuzhen
 * Date: 2018/5/31
 * Time: 14:53
 * Description:
 */
class StoreTopSaleGoodsModel extends \DAO\AbstractModel{

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

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

    public function init()
    {

    }

    public function pushChangeSaleStore($storeId){
        $storeTopSaleGoodsRedis = \Redis\Db4\StoreTopSaleGoodsRedisModel::getInstance();
        $storeTopSaleGoodsRedis->tableLPush('TopSaleStores',$storeId);
        //删除购物车缓存
        $cartRedis = \Redis\Db7\CartRedisModel::getInstance();
        $memberCartKey = \Our\NameConst::memberStoreCartsPrefix.'*_'.$storeId;
        $cartRedis->tableDelAll($cartRedis->tableKeys($memberCartKey));
    }

    public function getChangedSaleStoreId(){
        $storeTopSaleGoodsRedis = \Redis\Db4\StoreTopSaleGoodsRedisModel::getInstance();
        $storeId = $storeTopSaleGoodsRedis->tableLPop('TopSaleStores');
        return $storeId;
    }

    public function getList($where){
        $this->setDb();
        if(is_array($where)){
            $where = $this->db->getSqlWhereByArray($where);
        }
        return $this->db->select('goods_commonid as goodsCommonId,goods_name as goodsName,goods_image as goodsImage,goods_score as evalScore')->from($this->_tableName)->where($where)->fetchAll();
    }

    /**
     * 获取缓存中店铺销量前三的商品列表
     * @param $where array 店铺id数组
     * @return array|bool
     */
    public function getGoodsList($storeIds)    {
        $storeTopSaleGoodsRedis = \Redis\Db4\StoreTopSaleGoodsRedisModel::getInstance();
        $orderGoods = array();
        if($storeIds) {

            foreach ($storeIds as $storeId) {
                $storeGoods = $storeTopSaleGoodsRedis->find($storeId);
                if ($storeGoods) {
                    $orderGoods = empty($orderGoods)?$storeGoods:array_merge($orderGoods, $storeGoods);
                }else{
                    $singleStoreGoods = $this->getList(array('store_id'=>$storeId,'goods_commonid'=>array('neq','')));
                    if($singleStoreGoods){
                        $orderGoods = empty($orderGoods)?$singleStoreGoods:array_merge($orderGoods,$singleStoreGoods);
                        $storeTopSaleGoodsRedis->update($storeId,$singleStoreGoods,\Our\ApiConst::oneDaySecond);
                    }
                }
            }
        }
        if ($orderGoods) {
            foreach($orderGoods as &$goods){
                $goods['goodsImage'] = \Our\ImageUtil::getGoodsImgUrl($goods['goodsImage'],\Our\ImageConst::homeIndexHotGoodsImageSize);
            }
            return $orderGoods;
        }
        return false;
    }

    /**
     * 以店铺为单位获取当前店铺的销量前三商品以及其对应评分
     * @param $storeId
     * @return mixed
     */
    public function getStoreTopSaleGoodsListByStoreId($storeId){
        $this->setDb();
        $sql = \Our\Common::format('SELECT a.store_id,a.sale_num,a.goods_commonid,IFNULL((evaluation_score/evaluation_number),{0}) as goods_score,a.group_id as rank,a.goods_name,a.goods_image
FROM
(
SELECT t1.*,(SELECT COUNT(*)+1 FROM han_goods_common WHERE store_id=t1.store_id AND sale_num>t1.sale_num) AS group_id
FROM han_goods_common t1 where t1.goods_state={1} and t1.goods_verify={2} and t1.store_id ={3} and t1.is_del ={4}
) a
left join han_goods_score_statistics b
on a.goods_commonid = b.goods_commonid
WHERE a.group_id<=3 AND a.sale_num>0 order by a.group_id asc limit 3',\Our\ApiConst::defaultGoodsScore,\Our\ApiConst::onlineGoodsState,\Our\ApiConst::onlineGoodsVerify,$storeId,\Our\ApiConst::onlineGoodsDel);

        $list = $this->db->query($sql)->rows;
        if($list){
            $newlist = array();
            foreach($list as $key=>$goods){
                $goods['rank'] = $key+1;
                $newlist[] = $goods;
            }
            return $newlist;
        }
        return $list;
    }

    /**
     * @return mixed
     */
    public function getSourceGoodsList(){
        $this->setDb();
        $sql = 'SELECT  a.store_id,a.goods_commonid,IFNULL(a.evaluation_score/a.evaluation_number,'.\Our\ApiConst::defaultGoodsScore.') as goods_score,a.group_id as rank,a.goods_name,a.goods_image
FROM
(
SELECT t1.*,t2.evaluation_score,t2.evaluation_number,(SELECT COUNT(*)+1 FROM han_goods_common WHERE store_id=t1.store_id AND sale_num>t1.sale_num) AS group_id
FROM han_goods_common t1
LEFT JOIN han_goods_score_statistics t2
on t1.goods_commonid = t2.goods_commonid
where t1.
) a
WHERE a.group_id<=3 AND a.sale_num>0 and a.goods_state=1 and a.goods_verify=1 and a.is_del=0 ORDER BY a.store_id ,a.group_id';
        $list = $this->db->query($sql)->rows;
        return $list;
    }

    public function insertAllOrUpdate($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}(store_id,goods_commonid,goods_score,rank,goods_name,goods_image) values";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("('{0}','{1}','{2}','{3}','{4}','{5}'),", $datas[$i]['store_id'],$datas[$i]['goods_commonid'], $datas[$i]['goods_score'], $datas[$i]['rank'],$datas[$i]['goods_name'],$datas[$i]['goods_image']);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertAllSql .= 'ON DUPLICATE KEY UPDATE goods_commonid = VALUES(goods_commonid),goods_score=VALUES(goods_score),goods_name=VALUES(goods_name),goods_image=VALUES(goods_image)';
                $one = $this->db->insert()->query($insertAllSql);
                if ($one === false) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertAllSql .= 'ON DUPLICATE KEY UPDATE goods_commonid = VALUES(goods_commonid),goods_score=VALUES(goods_score),goods_name=VALUES(goods_name),goods_image=VALUES(goods_image)';
            $one = $this->db->insert($this->_tableName)->query($insertAllSql);
            if ($one === false) {
                $error++;
            }
        }
        if ($error > 0) {
            return false;
        }
        return true;
    }


    /**
     * 类实例
     *
     * @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;
    }
}