<?php

namespace DAO\Order;
use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;
use Our\ImageConst;
use Our\ImageUtil;


class OrderGoodsModel extends \DAO\AbstractModel {


    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_order_goods';
    public $sumField="rec_id,store_id as storeId,buyer_id as buyerId,goods_num as goodsNum,goods_price as goodsPrice,gmt_create as gmtCreate,order_id as orderId";
    public $groupField=array('buyer_id','store_id');
    public $sumGoodsNum=' store_id as storeId,buyer_id as buyerId,sum(goods_num) as orderGoodsCount';
    public $orderGoodsField = "order_id as orderId,rec_id as recId,goods_id as goodsId,goods_name as goodsName,goods_price as goodsPrice,goods_num as goodsNum,goods_image as goodsImage,goods_pay_price as goodsPayPrice,sale_act_id as saleActId,sale_id as saleId,comment_state as commentState,is_refund as isRefund,goods_spec as goodsSpec,refund_state_name as refundStateName,refund_id as refundId";
    /**
     * 主键
     *
     * @var string
     */

    protected $_primaryKey = 'rec_id';
    public $orderGoodsGoodsNumCountField=" sum(goods_num) as goodsNum";

    public function init(){

    }

    public function getOrderGoodsList($where,$field,$group = null,$limit = []){
        $this->setDb();
        if($limit){
            return $this->db->from($this->_tableName)->select($field)->where($where)->group($group)->limit($limit[0],$limit[1])->fetchAll();
        }
        return $this->db->from($this->_tableName)->select($field)->where($where)->group($group)->fetchAll();
    }





    /**
     * 更新数据
     * @param $data
     * @param $where
     * @return mixed
     */
    public function update($where, $data){
        $this->setDb(DbNameConst::masterDBConnectName);
        $data['gmt_update']=TIMESTAMP;
        return $this->db->update($this->_tableName)->where($where)->rows($data)->execute();
    }

    public function getOrderGoods($where,$field,$db=DbNameConst::salveDBConnectName){
        $this->setDb($this->dbName);
        $list = $this->db->select($field)->from($this->_tableName)->where($where)->fetchAll();
        return $list;
    }
    public function getOrderGoodsCountByStoreId($storeId){
        $this->setDb($this->dbName);
        $where['store_id']=$storeId;
        $where['is_refund']=array('neq',ApiConst::refundSuccess);
        if(is_array($where)){
            $where=$this->db->getSqlWhereByArray($where);
        }
        $goodsCount = $this->db->select($this->orderGoodsGoodsNumCountField)->from($this->_tableName)->where($where)->fetchValue();
        return (int)$goodsCount;
    }
    /**
     * 获取单条数据
     * @param $where
     * @return array
     */
    public function find($where,$field='*',$db=DbNameConst::salveDBConnectName) {
        $this->setDb($db);
        $data=$this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        return $data;
    }
    /**
     * 根据订单id 和商品id 获得订单商品记录
     * @param $where
     * @return array
     */
    public function getOneByOrderIdAndGoodsId($orderId,$goodsId,$field='*'){
        $where['order_id']=$orderId;
        $where['goods_id']=$goodsId;
        $res=$this->find($where,$field);
        return $res;
    }
    public function findByRecId($RecId,$field='*'){
        $where['rec_id']=$RecId;
        return $this->find($where,$field);
    }
    /**
     * 根据订单id 获得订单商品记录
     * @param $where
     * @return array
     */
    public function getOrderGoodsByOrderIds($orderIds,$field='*'){
        if(is_array($orderIds)){
            $where=Common::format(" order_id in ({0})",implode(',',$orderIds));
        }else{
            $where['order_id']=$orderIds;
        }
        return $this->getOrderGoods($where,$field);
    }

    public function deleteOrderGoodsCache($memberId,$orderIds,$storeId=false){
        if($memberId){
          //  return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::get:Instance(), array(&$this, 'getOrderGoodsByOrderIds'), array($memberId));
           // \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getO:rderGoodsByOrderIds'), array($memberId));
            \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getOrderGoodsByOrderIds'),array(),array($memberId));
        }
        if($orderIds){
            //return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getOrderGoodsByOrderIds'), array(),array($orderIds));
             \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getOrderGoodsByOrderIds'), array(),array($orderIds));
        }
        if(!empty($storeId)){
          //  return \Our\RedisHelper::delCachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$this, 'getOrderGoodsCountByStoreId'), array(),array($storeId));
           \Our\RedisHelper::delCachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$this, 'getOrderGoodsCountByStoreId'), array(),array($storeId));
        }
        return true;
    }
    public function getIsRefundMoney($orderGoodses,$promotionsId){
        $isRefundMoney=ApiConst::zero;
        foreach($orderGoodses as $orderGood){
            if($orderGood['promotionsId']=$promotionsId){
                $isRefundMoney+=$orderGood['goodsPrice'];
            }
        }
        return $isRefundMoney;
    }
    //转换数组
    public function convertOrderGoods($orderGoodses,$key='rec_id'){
        $convertOrderGoods=array();
        foreach($orderGoodses as $orderGoods){
            $convertOrderGoods[$orderGoods[$key]]=$orderGoods;
        }

        return $convertOrderGoods;
    }
    //获得已经退款退货的商品id
    public function getRefundOrderGoodsIds($orderGoods){
        $orderGoods=array_values($orderGoods);
        for($i=ApiConst::zero;$i<count($orderGoods);$i++){
            if($orderGoods[$i]['refundId']==ApiConst::zero){
                unset($orderGoods[$i]);
            }
        }
        return array_column($orderGoods,'goodsId');
    }
    /**
     * 根据订单id 获得订单商品记录
     * @param $where
     * @return array
     */
    public function getOrderGoodsByRecIds($recIds,$field='*'){
        if(is_array($recIds)){
            $where=Common::format(" rec_id in ({0})",implode(',',$recIds));
        }else{
            $where['rec_id']=$recIds;
        }
        return $this->getOrderGoods($where,$field);
    }
    //更具订单id获取商品的单挑信息
   public function getOneByOrderId($orderId,$field='*'){
       $this->setDb(DbNameConst::salveDBConnectName);
       $where['order_id']=$orderId;
       return $this->db->from($this->_tableName)->where($where)->select($field)->fetchOne();
   }


    public function getGoodsCount($orderGoods){
        return count(array_sum(array_column($orderGoods, 'goodsNum')));
    }

    public function getRefundOrderGoods($orderGoods){
       return  array(
            'goodsId'=>$orderGoods['goodsId'],
            'goodsName'=>$orderGoods['goodsName'],
            'goodsPrice'=>$orderGoods['goodsPrice'],
            'goodsNum'=>$orderGoods['goodsNum'],
            'goodsImage'=>ImageUtil::getGoodsImgUrl($orderGoods['goodsImage'],ApiConst::goodsSmallSize),
            'goodsPayPrice'=>$orderGoods['goodsPayPrice'],
        );
    }
    //销售订单
    public function getSaleOrderGoods($field,$updateTime,$pageIndex,$pageSize) {
        $pageIndex += 1;
        $this->setDb($this->dbName);
        return $this->db->select($field)->from($this->_tableName)->join('han_order',"han_order.order_id = han_order_goods.order_id",'inner')->join('han_refund_return','han_order_goods.refund_id = han_refund_return.refund_id','left')->where("sale_act_id > 0 AND (han_order_goods.gmt_update > {$updateTime} OR han_order.gmt_update > {$updateTime} OR han_refund_return.gmt_update > {$updateTime})")->page($pageIndex,$pageSize)->fetchAll();
    }
    public function insertAll($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert IGNORE into {$this->_tableName}(order_id,store_id,goods_id,goods_name,goods_num,goods_image,goods_price,goods_pay_price,buyer_id,snapshot_id,goods_spec,goods_commonid,gc_id,gc_id_1,gc_id_2,gc_id_3,gmt_create,gmt_update,sale_act_id,sale_id,goods_group) 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}','{15}','{16}','{17}','{18}','{19}','{20}'),", $datas[$i]['order_id'], $datas[$i]['store_id'], $datas[$i]['goods_id'], $datas[$i]['goods_name'], $datas[$i]['goods_num'], $datas[$i]['goods_image'], $datas[$i]['goods_price'], $datas[$i]['goods_pay_price'], $datas[$i]['buyer_id'], $datas[$i]['snapshot_id'], $datas[$i]['goods_spec'], $datas[$i]['goods_commonid'], $datas[$i]['gc_id'], $datas[$i]['gc_id_1'], $datas[$i]['gc_id_2'], $datas[$i]['gc_id_3'], $datas[$i]['gmt_create'], $datas[$i]['gmt_update'], $datas[$i]['sale_act_id'], $datas[$i]['sale_id'],$datas[$i]['goods_group']);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $one = $this->db->insert($this->_tableName)->query($insertAllSql);
                if (!$one) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $one = $this->db->insert($this->_tableName)->query($insertAllSql);

            if (!$one) {
                $error++;
            }
        }
        if ($error > 0) {
            return false;
        }
        return true;
    }
    public function getMemberStoreStaticsByCreateTime($gmtCreate,$pageIndex,$pageSize){
        $this->setDb($this->dbName);
        $where =\Our\Common::format(' gmt_update>={0} and gmt_update<{1} ',$gmtCreate,TIMESTAMP);
        $res=$this->lists($where,array('gmt_create'=>'asc'),$this->sumField,$pageIndex,$pageSize);
        return $res['list']?$res:false;
    }
    public function getMemberStoreOrderGoodsCount($storeIds,$memberIds){
        $this->setDb($this->dbName);
        $where['store_id']=array('in',$storeIds);
        $where['buyer_id']=array('in',$memberIds);
        $where['is_refund']=array('neq',ApiConst::refundSuccess);
        $where=$this->db->getSqlWhereByArray($where);
        $res=$this->db->from($this->_tableName)->select($this->sumGoodsNum)->where($where)->group("buyer_id")->group("store_id")->fetchAll();
        return $res;

    }
    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;



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

        return self::$_instance;
    }

}
