<?php

namespace DAO;
use \Our\Common;
use Our\CommonExtension;



class GoodsCommonModel extends \DAO\AbstractModel {


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

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

    public function init(){

    }

    /**
     * 更新商品主表商品库存
     * @param $goodsId 商品ID
     * @param $num 库存数量
     * @param $op 1增加 2设置
     * @return mixed
     */
    public function updateStorage($goodsCommonid, $op = 1) {
        $this->setDb();
        $whereSql = 'goods_commonid='.$goodsCommonid;
        if($op==1){
            $updateSql = 'goods_storage = (select sum(t.goods_storage) from '.$this->_child_tableName.' t where t.goods_commonid='.$goodsCommonid.')';
        } else {
            $updateSql = 'goods_storage_alarm = 0';
        }
        $updateSql=$updateSql . ",goods_edittime=".TIMESTAMP;
        $updateAllSql = "UPDATE {$this->_tableName} set {$updateSql} where {$whereSql}";
        return $this->db->update($this->_tableName)->query($updateAllSql);
    }

    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 getOneByIdCache($goodsCommonId) {
        $commonInfo = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsCommonRedisModel::getInstance(),array(&$this, 'getOneById'),array($goodsCommonId),0,array($goodsCommonId));
        return $commonInfo;
    }
    public function getOne($where,$field = \Our\NameConst::allField){
        $this->setDb($this->dbName);
        if(is_array($where)){
            $where = $this->db->getSqlWhereByArray($where);
        }
        $result = $this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
        return $result ;

    }


    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);
        if($attrStr) {
            $field = 'DISTINCT '.$field;
        }
        $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')->where('is_del = 0')";
        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;
    }

    public function syncGoodsCommonStorageByGoods(){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $sql =" update han_goods_common t set t.goods_storage = (select sum(a.goods_storage) from han_goods a where a.goods_commonid = t.goods_commonid)";
        return $this->db->update($this->_tableName)->query($sql);
    }

    /**
     * 商品列表(需要获取销售价格)
     * @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);
        if($attrStr) {
            $attrStr = '('.$attrStr.')';
            $field = ' DISTINCT '.$field;
        }
        $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 (is_del = 0) 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)->where(array('goods_state'=>1,'goods_verify'=>1,'is_del'=>0))->fetchNum();
        }
        return $this->db->from($this->_tableName)->where(array('goods_state'=>1,'goods_verify'=>1,'is_del'=>0))->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($op!=\Our\ApiConst::set){
            $updateSaleNumOp = $op==\Our\ApiConst::minus?'+':'-';
        }else{
            $updateSaleNumOp = '=';
            $updateSaleNumFlag= false;
        }

        $goodsCommonSql = ' goods_storage = case goods_commonid ';
        $goodsEdittimeSql = ' goods_edittime = 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']);
            $goodsEdittimeSql .= \Our\Common::format("  WHEN {0} THEN goods_edittime={1}", $datas[$i]['goodsCommonId'],TIMESTAMP);
            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';
                $goodsEdittimeSql = trim($goodsEdittimeSql,',').' END';
                $updateAllSql .= $goodsCommonSql;
                $updateAllSql .= ','.$goodsEdittimeSql;
                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 ';
                $goodsEdittimeSql = ' goods_edittime = case goods_commonid ';
                if($updateSaleNumFlag){
                    $saleNumSql = 'sale_num = case goods_commonid ';
                }
                $dataIds = array();
            }
        }
        if ($goodsCommonSql) {
            $goodsCommonSql = trim($goodsCommonSql,',').' END ';
            $goodsEdittimeSql = ','.trim($goodsEdittimeSql,',').' END';
            $updateAllSql .= $goodsCommonSql;
            $updateAllSql .= $goodsEdittimeSql;
            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;
    }

}
