<?php
namespace DAO\Cart;
/**
 * User: liuyuzhen
 * Date: 2018/6/20
 * Time: 14:27
 * Description:
 */
class CartModel extends \DAO\AbstractModel{




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

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

    public function init(){

    }

    public function getDb(){
        return $this->db;
    }

    /**
     * 获取单条数据
     * @param $where
     * @return array
     */
    public function find($where,$field= \Our\NameConst::allField){
        $this->setDb($this->dbName);
        if(is_array($where)){
            $where = $this->db->getSqlWhereByArray($where);
        }
        $data = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        return $data;
    }

    public function insert($data){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result = $this->db->insert($this->_tableName)->rows($data)->execute();
        return $result ;
    }

    public function update($data,$where){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result=$this->db->update($this->_tableName)->rows($data)->where($where)->execute();
        return $result;
    }


    public function del($where){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result  = $this->db->delete($this->_tableName)->where($where)->execute();
        return $result;
    }

    public function getList($where,$field = \Our\NameConst::allField,$order = null){
        $this->setDb($this->dbName);
        $this->db->select($field)->from($this->_tableName)->where($where);
        if($order){
            foreach($order as $key => $value){
                $this->db->order($key,$value);
            }
        }
        $result = $this->db->fetchAll();
        return $result;
    }

    /**
     * @param $where 查询条件
     * @param $memberId 对应会员ID
     * @param string $field 查询对应的字段
     * @param null $group 分组
     * @param null $order 排序
     * @return bool|mixed
     */
    public function getCartStoreIdsByMemberId($where,$memberId,$field= \Our\NameConst::allField,$group = null,$order = null){
        $memberCartKey = \Our\NameConst::memberCartStorePrefix.$memberId;
        $cartRedis = \Redis\Db7\CartRedisModel::getInstance();
        $storeIds = $cartRedis->find($memberCartKey);
        if(!$storeIds){
            $this->setDb($this->dbName);
            $this->db->from($this->_tableName);
            $this->db->where($where);
            $this->db->select($field);
            if($group){
                $this->db->group($group);
            }
            if($order){
                if(is_array($order)){
                    foreach($order as $key =>$value){
                        $this->db->order($key,$value);
                    }
                }
            }
            $lists=$this->db->fetchAll();
            if($lists&&count($lists)>\Our\ApiConst::zero){
                $cartRedis->update($memberCartKey,$lists,\Our\ApiConst::tenDaySecond);
                return $lists;
            }
            return false;
        }
        return $storeIds;

    }

    /**
     * 根据店铺Id和会员Id获取购物车信息
     * @param $storeIds
     * @param $memberId
     * @param string $field
     * @param null $order
     * @return array
     */
    public function getStoreCartListByMemberId($storeIds,$memberId,$field= \Our\NameConst::allField,$order = null){
        $cartRedis = \Redis\Db7\CartRedisModel::getInstance();
        $goodsDao = \DAO\GoodsModel::getInstance();
        $storeCartList = array();
        foreach($storeIds as $storeId){
            $memberStoreCartsKey = \Our\NameConst::memberStoreCartsPrefix.$memberId.\Our\NameConst::underline.$storeId;
            $storeCarts = $cartRedis->find($memberStoreCartsKey,\Our\ApiConst::tenDaySecond);
            if(!$storeCarts){
                $where['buyer_id'] = $memberId;
                $where['store_id'] = $storeId;
                $this->setDb($this->dbName);
                $this->db->from($this->_tableName);
                $this->db->where($where);
                $this->db->select($field);
                if($order){
                    if(is_array($order)){
                        foreach($order as $key =>$value){
                            $this->db->order($key,$value);
                        }
                    }
                }
                $returnStoreCarts=$this->db->fetchAll();
                $storeCartList[$storeId] = array('updateFlag'=>\Our\ApiConst::one,'storeCarts'=>$returnStoreCarts);

            }else{
                $storeCartList[$storeId] = array('updateFlag'=>\Our\ApiConst::zero,'storeCarts'=>$storeCarts);
            }
        }
        return $storeCartList;
    }

    /**
     * 根据店铺Id和会员Id获取购物车信息
     * @param $storeIds
     * @param $memberId
     * @param string $field
     * @param null $order
     * @return array
     */
    public function getStoreCartListByMemberId1($storeIds,$memberId,$field= \Our\NameConst::allField,$order = null){
        $cartRedis = \Redis\Db7\CartRedisModel::getInstance();
        $goodsDao = \DAO\GoodsModel::getInstance();
        $storeCartList = array();
        $noRedisStoreIds = array();
        foreach($storeIds as $storeId){
            $memberStoreCartsKey = \Our\NameConst::memberStoreCartsPrefix.$memberId.\Our\NameConst::underline.$storeId;
            $storeCarts = $cartRedis->find($memberStoreCartsKey,\Our\ApiConst::tenDaySecond);
            if(!$storeCarts){
                $noRedisStoreIds[] = $storeId;
            }else{
                $storeCartList[$storeId] = array('updateFlag'=>\Our\ApiConst::zero,'storeCarts'=>$storeCarts);
            }
        }
        $blIds = array();
        $goodsIds = array();
        $goodsCommonIds = array();
        if($noRedisStoreIds&&count($noRedisStoreIds)>\Our\ApiConst::zero){
            $sql = \Our\Common::format(' buyer_id = {0} and store_id in ({1})',$memberId,implode(',',$noRedisStoreIds));
            $this->setDb($this->dbName);
            $this->db->from($this->_tableName);
            $this->db->where($sql);
            $this->db->select($field);
            if($order){
                if(is_array($order)){
                    foreach($order as $key =>$value){
                        $this->db->order($key,$value);
                    }
                }
            }
            $returnStoreCarts=$this->db->fetchAll();
            if($returnStoreCarts){
                foreach($returnStoreCarts as $temp){
                    $storeCartList[$temp['store_id']]['storeCarts'][] = $temp;
                    if($temp['type'] == \Our\ApiConst::addBundingToCart){
                        $blIds[] = $temp['goods_id'];
                    }else{
                        $goodsIds[] = $temp['goods_id'];
                        $goodsCommonIds[] = $temp['goods_commonid'];
                    }
                }
                foreach($noRedisStoreIds as $storeId){
                    $storeCartList[$storeId]['updateFlag'] = \Our\ApiConst::one;
                }
            }
        }
        return array(
            'goodsIds'=>$goodsIds,
            'goodsCommonIds'=>$goodsCommonIds,
            'blIds'=>$blIds,
            'cartList'=>$storeCartList,
            'storeIds'=>$storeIds
        );
    }

    /**GroupSaleService.php
     * 根据购物车IDS和会员id获取店铺购物车列表
     * @param $cartIds 购物车IDs
     * @param $memberId 会员ID
     * @param string $field
     * @param array $order
     * @return array|bool
     */
    public function getStoreCartListByCartIds($cartIds,$memberId,$field= \Our\NameConst::allField,$order= array('store_id'=>'desc')){
        $sql = \Our\Common::format(' cart_id in ({0}) and buyer_id = {1}',implode(',',$cartIds),$memberId);
        $this->setDb($this->dbName);
        $this->db->from($this->_tableName);
        $this->db->where($sql);
        $this->db->select($field);
        if($order){
            if(is_array($order)){
                foreach($order as $key =>$value){
                    $this->db->order($key,$value);
                }
            }
        }
        $carts = $this->db->fetchAll();
        if($carts&&count($cartIds)==count($carts)){
            $result = array();
            foreach($carts as $obj){
                $result[$obj['store_id']][] = $obj;
            }
            $cartList = array();
            foreach($result as $key=>$cartArray){
                $cartList[$key] = array(
                    'updateFlag' => \Our\ApiConst::one,
                    'storeCarts' => $cartArray
                );
            }
            $goodsIds = array();
            $goodsCommonIds = array();
            $blIds = array();
            foreach($carts as $temp){
                if($temp['type']==\Our\ApiConst::addGoodsToCart){
                    $goodsIds[] = $temp['goods_id'];
                    $goodsCommonIds[] = $temp['goods_commonid'];
                }else{
                    $blIds[] = $temp['goods_id'];
                }
            }
            $storeIds = array_keys($cartList);
            $goodsCommonIds = array_unique($goodsCommonIds);
            return array('cartList'=>$cartList,'storeIds'=>$storeIds,'goodsIds'=>$goodsIds,'blIds'=>$blIds,'goodsCommonIds'=>$goodsCommonIds);

        }
        return false;
    }
    public function refundGoodsRemove($storeCarts,$goodsIds){
        for($i=0;$i<count($storeCarts);$i++){
            if(is_array($goodsIds)){
                if(in_array($storeCarts[$i]['goodsId'],$goodsIds)){
                    unset($storeCarts[$i]);
                }
            }else{
                if($storeCarts[$i]['goodsId']==$goodsIds){
                    unset($storeCarts[$i]);
                }
            }
        }
        return $storeCarts;
    }

    public function insertAllOrUpdate($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}(store_id,goods_id,goods_commonid,type,store_name,goods_name,goods_price,goods_image,goods_spec,goods_mid,gmt_update,goods_num,buyer_id,snapshot_id,goods_original_price) values";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}'),", $datas[$i]['store_id'], $datas[$i]['goods_id'], $datas[$i]['goods_commonid'],$datas[$i]['type'], $datas[$i]['store_name'], $datas[$i]['goods_name'], $datas[$i]['goods_price'],$datas[$i]['goods_image'], $datas[$i]['goods_spec'], $datas[$i]['goods_mid'], $datas[$i]['gmt_update'],$datas[$i]['goods_num'], $datas[$i]['buyer_id'], $datas[$i]['snapshot_id'], $datas[$i]['goods_original_price']);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertAllSql .= 'ON DUPLICATE KEY UPDATE goods_num =`goods_num`+VALUES(goods_num),store_id=VALUES(store_id),store_name=VALUES(store_name),goods_name=VALUES(goods_name),goods_price=VALUES(goods_price),goods_image=VALUES(goods_image),goods_spec=VALUES(goods_spec),goods_mid=VALUES(goods_mid),gmt_update=VALUES(gmt_update),snapshot_id=VALUES(snapshot_id),goods_original_price=VALUES(goods_original_price)';
                $one = $this->db->insert()->query($insertAllSql);
                if ($one === false) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertAllSql .= 'ON DUPLICATE KEY UPDATE goods_num =`goods_num` + VALUES(goods_num),store_id=VALUES(store_id),store_name=VALUES(store_name),goods_name=VALUES(goods_name),goods_price=VALUES(goods_price),goods_image=VALUES(goods_image),goods_spec=VALUES(goods_spec),goods_mid=VALUES(goods_mid),gmt_update=VALUES(gmt_update),snapshot_id=VALUES(snapshot_id),goods_original_price=VALUES(goods_original_price)';
            $one = $this->db->insert($this->_tableName)->query($insertAllSql);
            if ($one === false) {
                $error++;
            }
        }
        if ($error > 0) {
            return false;
        }
        return true;
    }

    /**
     * 类实例
     */
    private static $_instance = null;

    /**
     * 获取类实例
     */
    public static function getInstance($dbName=\Our\DbNameConst::salveDBConnectName) {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self($dbName);
        }

        return self::$_instance;
    }
}
