<?php

namespace DAO\Storage;
use \Our\Common;
use Our\DbNameConst;


class GoodsCommonStorageModel extends \DAO\AbstractModel {


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

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

    public function init(){

    }
    public function getOneById($goodsCommonId){
        $this->setDb();
        return $this->db->select('*')->from($this->_tableName)->where(array('goods_commonid'=>$goodsCommonId))->fetchOne();
    }

    /**
     * 商品列表
     * @param $where
     * @param $field
     * @param bool $limit
     * @param array $order
     * @return mixed
     */
    public function getGoodsList($where,$field,$limit=array(),$order=array(),$attrStr=''){
        $this->setDb();
        $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;
    }
    public function getAll(){
        $this->setDb($this->dbName);
        $res=$this->db->from($this->_tableName)->fetchAll();
        return $res;
    }
    public function createTestData(){
        $res =$this->getAll();
        $insertNames=array();
        $insertArray=array();
       $one= array('状元笔记','三点一测','初高中','另类学习','天才辅导','启蒙','课外学习','小天才','深入理解','黄冈练习');
        $two=array('七年级','八年级','九年级');
        $three=array('语文','数学','英语','物理','化学','生物','地理','历史','政治');
        $four=array('人教版','北师大版','苏教版');
        $five=array('上册','下册');
        $goodsStorage=\DAO\Storage\GoodsStorageModel::getInstance();
        foreach($one as $onekey=>$oneVal){
            foreach($two as $twoKey=>$twoVal){
                foreach($three as $threeKey=>$threeVal){
                    foreach($four as $fourKey=>$fourVal){
                        foreach($five as $fiveKey=>$fiveVal){
                            $diffKey=(string)$onekey.(string)$twoKey.(string)$threeKey.(string)$fourKey.(string)$fiveKey;
                            $catName=$oneVal.$twoVal.$threeVal.$fourVal.$fiveVal;
                            $resultIndex=array_rand($res);
                            $re=$res[$resultIndex];
                            $re['goods_commonid']=5000000+(int)$diffKey;
                            $re['goods_name']=$catName;
                            $re['goods_jingle']=$catName;
                            $re['gc_name']='学习辅导课程';
                            $re['store_id']=117;
                            $re['store_name']='testlyz1的小店';
                            $re['goods_addtime']=TIMESTAMP;
                            $re['gc_id']=1152;
                            $re['gc_id_1']=1064;
                            $re['gc_id_2']=1081;
                            $re['gc_id_3']=1152;
                            $this->db->insert($this->_tableName)->rows($re)->execute();
                            $goodsStorage->addOne($re);


                        }
                    }
                }
            }
        }



    }

    /**
     * 商品列表(需要获取销售价格)
     * @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();
        $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;
    }

    /**
     * 获取优惠券对应商品列表(指定品类)
     * @param $where
     * @param $field
     * @param $limit
     * @return mixed
     */
//    public function getCouponClassGoods($where,$field,$limit){
//        $this->setDb();
//        return $this->db->select($field)->from($this->_tableName)->join('han_store_coupon_goods_class','han_store_coupon_goods_class.gc_id = '.$this->_tableName.'.gc_id_1','inner')->where($where)->where('goods_verify = 1')->where('goods_state = 1')->limit($limit[0],$limit[1])->fetchAll();
//    }
    /**
     * 获取优惠券对应商品列表(指定品类)(需要获取销售价格)
     * @param $where
     * @param $field
     * @param $limit
     * @param $actIds
     */
//    public function getCouponClassGoodsWithSale($where,$field,$limit,$actIds){
//        $this->setDb();
//        $str = "select ".$field." FROM ".$this->_tableName." INNER JOIN han_store_coupon_goods_class on han_store_coupon_goods_class.gc_id = han_goods_common.gc_id_1 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) ";
//        $str .= 'where(goods_verify = 1) AND (goods_state = 1) AND ';
//        $str .= $where;
//        $str .=" limit {$limit[0]},{$limit[1]}";
//        $data = $this->db->query($str);
//        return $data->rows;
//    }
    /**
     * 获取优惠券对应商品列表(指定商品)
     * @param $where
     * @param $field
     * @param $limit
     * @return mixed
     */
//    public function getCouponGoods($where,$field,$limit){
//        $this->setDb();
//        return $this->db->select($field)->from($this->_tableName)->join('han_store_coupon_goods','han_store_coupon_goods.goods_commonid = '.$this->_tableName.'.goods_commonid','inner')->where($where)->where('goods_verify = 1')->where('goods_state = 1')->limit($limit[0],$limit[1])->fetchAll();
//    }

    /**
     * 获取优惠券对应商品列表(指定商品)(需要获取销售价格)
     * @param $where
     * @param $field
     * @param $limit
     * @param $actIds
     */
//    public function getCouponGoodsWithSale($where,$field,$limit,$actIds){
//        $this->setDb();
//        $str = "select ".$field." FROM ".$this->_tableName." INNER JOIN han_store_coupon_goods on han_store_coupon_goods.goods_commonid = han_goods_common.goods_commonid 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) ";
//        $str .= 'where(goods_verify = 1) AND (goods_state = 1) AND ';
//        $str .= $where;
//        $str .=" limit {$limit[0]},{$limit[1]}";
//        $data = $this->db->query($str);
//        return $data->rows;
//    }
    /**
     * 获取商品评分
     * @param $StoreId
     * @return mixed
     */
    public function getGrade($goodsCommonId,$commonInfo = null){
        $statisticsDb6Redis = \Redis\Db6\StatisticsRedisModel::getInstance();
        $grade = $statisticsDb6Redis->tableHGet('goodsCommon',$goodsCommonId);
        if($grade === false){
            if(!$commonInfo){
                $goodsScoreDAO = \DAO\GoodsScoreStatisticsModel::getInstance();
                $commonInfo = \Our\RedisHelper::cachedFunction(\Redis\Db4\GoodsScoreStatisticsRedisModel::getInstance(),array(&$goodsScoreDAO, 'getOne'),array('*',array('goods_commonid'=>$goodsCommonId)),\Our\ApiConst::oneDaySecond,array($goodsCommonId));
                if($commonInfo === false){
                    $commonInfo['evaluation_number'] = 0;
                    $commonInfo['evaluation_img_number'] = 0;
                    $commonInfo['evaluation_score'] = 0;
                }
            }
            $grade = array();
            $grade['evaluation_score'] = $commonInfo['evaluation_score'];
            $grade['evaluation_number'] = $commonInfo['evaluation_number'];
            $grade['evaluation_img_number'] = $commonInfo['evaluation_img_number'];
            $statisticsDb6Redis->tableHSet('goodsCommon',$goodsCommonId,serialize($grade));
            return $grade;
        }
        return unserialize($grade);
    }
    /**
     * 获取图片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();
        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){
        $datas = array_values($dataList);
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "UPDATE {$this->_tableName} set goods_storage = case goods_commonid ";
        $updateAllSql = $baseSql;
        $dataIds = array();
        for ($i = 0; $i < count($datas); $i++) {
            $updateSql = \Our\Common::format(" WHEN {0} THEN goods_storage-{1} ", $datas[$i]['goodsCommonId'], $datas[$i]['goodsNum']);
            $dataIds[] = $datas[$i]['goodsCommonId'];
            $updateAllSql .= $updateSql;
            if ($i % 1000 == 0 && $i != 0) {
                $updateAllSql .= \Our\Common::format('END where goods_commonid in ({0})',implode(',',$dataIds));
                $one = $this->db->update($this->_tableName)->query($updateAllSql);
                if (!$one) {
                    $error++;
                }
                $updateAllSql = $baseSql;
                $dataIds = array();
            }
        }
        if ($updateAllSql != $baseSql) {
            $updateAllSql .= \Our\Common::format('END 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() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

}
