<?php

namespace DAO;
use \Our\Common;



class GoodsCommonModel extends \DAO\AbstractModel {


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

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

    public function init(){

    }
    public function getOneById($goodsCommonId,$field = \Our\NameConst::allField){
        $this->setDb($this->dbName);
        return $this->db->select($field)->from($this->_tableName)->where(array('goods_commonid'=>$goodsCommonId))->fetchOne();
    }

    public function getOne($where,$field = \Our\NameConst::allField){
        $this->setDb($this->dbName);
        return $this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
    }
    public function getGoodsSaleNumFromCache($goodsCommonId){
        $goodsCommonRedis = \Redis\Db4\GoodsCommonRedisModel::getInstance();
        $onlineGoodsCommonSaleNumKey = \Our\NameConst::onlineGoodsCommonSaleNumPrefix;
        if($goodsCommonRedis->tableHExists($onlineGoodsCommonSaleNumKey,$goodsCommonId)){
            $saleNum = $goodsCommonRedis->tableHGet($onlineGoodsCommonSaleNumKey,$goodsCommonId);
        }else{
            $goodsCommon = $this->getOneById($goodsCommonId,'sale_num');
            $saleNum = $goodsCommon['sale_num'];
            $goodsCommonRedis->tableHIncrBy($onlineGoodsCommonSaleNumKey,$goodsCommonId,$saleNum);
        }
        return $saleNum;
    }

    /**
     * 删除销量缓存
     * @param $goodsCommonId
     */
    public function deleteGoodsSaleNumFromCache($goodsCommonId){
        $goodsCommonRedis = \Redis\Db4\GoodsCommonRedisModel::getInstance();
        $onlineGoodsCommonSaleNumKey = \Our\NameConst::onlineGoodsCommonSaleNumPrefix;
        $goodsCommonRedis->tableHDel($onlineGoodsCommonSaleNumKey,$goodsCommonId);
    }

    /**
     * 商品列表
     * @param $where
     * @param $field
     * @param bool $limit
     * @param array $order
     * @return mixed
     */
    public function getGoodsList($where,$field,$limit=array(),$order=array(),$attrStr=''){
        $this->setDb($this->dbName);
        $str = '$data =  $this->db->select($field)->from($this->_tableName)';
        if($attrStr){
            $str .="->join('han_goods_attribute_value','han_goods_attribute_value.goods_commonid = han_goods_common.goods_commonid')";
            $str .='->where($attrStr)';
        }
        foreach ($where as $v){
            $str .= '->where("'.$v.'")';
        }
        $str .="->where('goods_verify = 1')->where('goods_state = 1')";
        if($limit){
            $str .= "->limit({$limit[0]},{$limit[1]})";
        }
        if($order){
            foreach ($order as $v){
                $str .= "->order('{$v[0]}','{$v[1]}')";
            }
        }
        $str .= "->fetchAll();";
        eval($str);
        return $data;
    }
    /**
     * 商品列表(需要获取销售价格)
     * @param $where
     * @param $field
     * @param $actIds
     * @param bool $limit
     * @param array $order
     * @return mixed
     */
    public function getListWithSale($where,$field,$actIds,$limit=array(),$order=array(),$attrStr='',$online = true){
        $this->setDb($this->dbName);
        $str = "select ".$field." FROM ".$this->_tableName." LEFT JOIN (SELECT MIN(discount_price) discount_price,goods_commonid,goods_id FROM han_sale_goods where sale_act_id in(".implode(',',$actIds).") GROUP BY goods_commonid) a on (han_goods_common.goods_commonid = a.goods_commonid)";
        if($attrStr){
            $str .= "INNER JOIN han_goods_attribute_value ON han_goods_attribute_value.goods_commonid = han_goods_common.goods_commonid ";
//            $str .="->join('han_goods_attribute_value','han_goods_attribute_value.goods_commonid = han_goods_common.goods_commonid')";
//            $str .='->where($attrStr)';
        }
        $str .= 'where ';
        if($online){
            $str .=" (goods_verify = 1) AND (goods_state = 1) AND ";
        }
        $str .= '('.implode(') AND (',$where).')';
        if($attrStr){
            $str .= "AND {$attrStr}";
        }
        if($order){
            $str .= " ORDER BY ";
            foreach ($order as $v){
                $str .= "{$v[0]} {$v[1]},";
            }
            $str = rtrim($str,",");
        }
        if($limit){
            $str .=" limit {$limit[0]},{$limit[1]}";
        }
        $data = $this->db->query($str);
        return $data->rows;
    }


    /**
     * 获取图片oss路径
     * @param $goodsImg 图片名
     * @param $type 图片尺寸
     * @return mixed|string
     */
    public function getGoodsImgSrc($goodsImg,$type=240){
        if(!in_array($type,\Our\ArrayConst::goodsImageExt)){
            $type = 240;
        }
        if (empty($goodsImg)) {
            $directory =\Our\ImageConst::defaultPath;
            $goodsImg = str_ireplace('.', '_' . $type . '.', 'default_goods_image.jpg');
        }else{
            $storeId = substr ( $goodsImg, 0, strpos ( $goodsImg, '_' ) );
            $directory = \Our\ImageConst::goods.$storeId.'/';
            $goodsImg = str_ireplace('.', '_' . $type . '.', $goodsImg);
        }
        $goodsImg =  Common::getStaticFile($goodsImg,$directory,'ossHost');
        return $goodsImg;
    }

    /**
     * 商品详情处理
     * @param $mobileBody
     * @return string
     */
    public function getMobileBody($mobileBody){
        $mobile_body_array = unserialize($mobileBody);
        if (is_array($mobile_body_array)) {
            $mobile_body = '';
            foreach ($mobile_body_array as $val) {
                switch ($val['type']) {
                    case 'text':
                        $mobile_body .= '<div>' . $val['value'] . '</div>';
                        break;
                    case 'image':
                        $mobile_body .= '<img src="' . $val['value'] . '">';
                        break;
                }
            }
            return $mobile_body;
        }
    }

    public function getCount($where,$attrStr=''){
        $this->setDb($this->dbName);
        if($attrStr){
            return $this->db->from($this->_tableName)->join('han_goods_attribute_value','han_goods_attribute_value.goods_commonid = han_goods_common.goods_commonid')->where($where)->where($attrStr)->fetchNum();
        }
        return $this->db->from($this->_tableName)->where($where)->fetchNum();
    }
    /**
     * 获取分享信息
     * @param $commonInfo
     * @param $store_share_desc  店铺分享简介
     * @return mixed
     * @throws \Exception
     * @throws \OSS\Core\OssException
     * @throws \Our\Exception
     */
    public function getShareInfo($commonInfo,$store_share_desc){
        if(!is_array($commonInfo)){
            $commonInfo = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsCommonRedisModel::getInstance(),array(&$this, 'getOneById'),array($commonInfo),0,array($commonInfo));
            if(!$commonInfo){
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::goodsNotExist);
            }
        }

        $share['title'] = $commonInfo['goods_name']?$commonInfo['goods_name']:$commonInfo['goods_jingle'];
        $share['desc'] = $commonInfo['goods_jingle']?$commonInfo['goods_jingle']:$store_share_desc;
        $share['link']='http://www.shenbd.com';
        $share['imgUrl'] = \Our\ImageUtil::getGoodsImgUrl($commonInfo['goods_image']);
        return $share;
    }
    public function updateAll($datas){

    }


    public function updateGoodsStorage($dataList , $op = \Our\ApiConst::minus,$updateSaleNumFlag = false){
        $datas = array_values($dataList);
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "UPDATE {$this->_tableName} set ";
        $updateAllSql = $baseSql;
        $dataIds = array();
        if($updateSaleNumFlag&&$op!=\Our\ApiConst::set){
            $updateSaleNumOp = $op==\Our\ApiConst::minus?'+':'-';
        }
        $goodsCommonSql = 'goods_storage = case goods_commonid ';
        if($updateSaleNumFlag){
            $saleNumSql = 'sale_num = case goods_commonid ';
        }
        for ($i = 0; $i < count($datas); $i++) {
            $goodsCommonSql .= \Our\Common::format("  WHEN {0} THEN goods_storage{1}{2}, ", $datas[$i]['goodsCommonId'],\Our\ArrayConst::ops[$op], $datas[$i]['goodsNum']);
            if($updateSaleNumFlag){
                $saleNumSql .= \Our\Common::format(" when {0} THEN sale_num {1}{2},", $datas[$i]['goodsCommonId'],$updateSaleNumOp, $datas[$i]['goodsNum']);
            }
            $dataIds[] = $datas[$i]['goodsCommonId'];
            if ($i % 1000 == 0 && $i != 0) {
                $goodsCommonSql = trim($goodsCommonSql,',').' END';
                $updateAllSql .= $goodsCommonSql;
                if($updateSaleNumFlag){
                    $saleNumSql = ','.trim($saleNumSql,',').' END ';
                    $updateAllSql .= $saleNumSql;
                }
                $updateAllSql .= \Our\Common::format(' where goods_commonid in ({0})',implode(',',$dataIds));
                $one = $this->db->update($this->_tableName)->query($updateAllSql);
                if (!$one) {
                    $error++;
                }
                $updateAllSql = $baseSql;
                $goodsCommonSql = 'goods_storage = case goods_commonid ';
                if($updateSaleNumFlag){
                    $saleNumSql = 'sale_num = case goods_commonid ';
                }
                $dataIds = array();
            }
        }
        if ($updateAllSql != $baseSql) {
            $goodsCommonSql = trim($goodsCommonSql,',').' END ';
            $updateAllSql .= $goodsCommonSql;
            if($updateSaleNumFlag){
                $saleNumSql = ','.trim($saleNumSql,',').' END ';
                $updateAllSql .= $saleNumSql;
            }
            $updateAllSql .= \Our\Common::format(' where goods_commonid in ({0})',implode(',',$dataIds));
            $one = $this->db->update($this->_tableName)->query($updateAllSql);

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

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

}
