<?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 getList($where){
        $this->setDb();
        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));
                    if($singleStoreGoods){
                        $ordesGoods = empty($orderGoods)?$singleStoreGoods:array_merge($orderGoods,$singleStoreGoods);
                        $storeTopSaleGoodsRedis->update($storeId,$singleStoreGoods);
                    }
                }
            }
        }
        if ($orderGoods) {
            foreach($orderGoods as &$goods){
                $goods['goodsImage'] = \Our\ImageUtil::getGoodsImgUrl($goods['goodsImage'],\Our\ImageConst::homeIndexHotGoodsImageSize);
            }
            return $orderGoods;
        }
        return false;
    }

    /**
     * @return mixed
     */
    public function getSourceGoodsList(){
        $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
) a
WHERE a.group_id<=3 AND a.sale_num>0 and a.goods_state=1 and a.goods_verify=1 ORDER BY a.store_id ,a.group_id';
        $list = $this->db->query($sql)->fetchAll();
        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;
    }
}