<?php

namespace DAO;
use Our\Common;
use Our\DbNameConst;
use Our\ApiConst;
use Redis\Db6\StoreRedisModel;
/**
 * 店铺数据统计
 * @date 2018-5-14
 * @author csw
 */
class StoreMemberStatisticsModel extends \DAO\AbstractModel {


    protected $redis;

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

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';
    private $insertField='store_id,member_id,order_goods_count,order_total,add_time';

    public function init(){
        //$this->setDb();
    }

    /**
     * 获取店铺统计信息
     * @param $where
     * @return array
     */
    public function find($where) {
        $this->setDb();
        $field='*';
        $data=$this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
        return $data;
    }
    public function getField(){
        return "id as Id,store_id as storeId,member_id as memberId,order_goods_count as orderGoodsCount,order_total as orderTotal,add_time as addTime,fav_time as favTime,is_black as isBlack,member_name as memberName";
    }
    /**
     * 更新数据
     * @param $data
     * @param $where
     * @return mixed
     */
    public function update($data,$where){
        $this->setDb();
        return $this->db->update($this->_tableName)->where($where)->rows($data)->execute();
    }

    /**
     * 插入数据
     * @param $data
     * @return mixed
     */
    public function insert($data){

    }
    /**
     * 排序，1：关注时间降序，2：关注时间升序，3：购买力降序，4：购买力升序，默认1
     * @param $data
     * @return mixed
     */
    public function getSortBySortType($sortType){

    }
   
    /**
     * 删除数据
     * @param $where
     * @return bool
     */
    public function delete($where){
        $this->setDb();
        return $this->db->delete($this->_tableName)->where($where)->execute();
    }

    /**
     * 分页获取店铺粉丝消费情况数据
     * @param $storeId
     * @param string $field
     * @param $pageIndex
     * @param $pageSize
     * @param $order
     * @return bool
     */
    public function getListByStoreId($storeId,$field='*',$pageIndex,$pageSize,$keyword,$order,$sort){
        $this->setDb();
        if(empty($storeId)){
            return false;
        }
        $where = 'han_store_member_statistics.store_id='.$storeId;
        if(!empty($keyword)){
            $where .= ' and (member_name like %'.$keyword.'% or member_mobile like %'.$keyword.'%';
        }
        $pageIndex=$pageIndex+\Our\ApiConst::one;
        //$this->updateData($storeId);
        $field = 'han_member.member_name,han_member.member_avatar,han_member.member_mobile,han_store_member_statistics.order_total,han_store_member_statistics.order_goods_count';
        $data = $this->db->from($this->_tableName)->select($field)
            ->join('han_member','han_member.member_id = han_store_member_statistics.member_id','inner')
            ->where($where)->order($order,$sort)->page($pageIndex,$pageSize)->fetchAll();
        if(!empty($data)){
            foreach($data as $v){
                if($v['member_avatar'] != ''){
                    if(strpos($v['member_avatar'],'http') !== 0){
                        $v['member_avatar'] = $storeLabel = \Our\Common::getStaticFile($v['member_avatar'],'/data/upload/mall/avatar/','ossHost');
                    }
                }else{
                    $v['member_avatar'] = $storeLabel = \Our\Common::getStaticFile('default_member_avatar','/data/upload/mall/common/','ossHost');
                }
            }
        }
        return $data;
    }
    /**
     * 更新店铺关注会员统计数据（定时器更新用）
     * @param $storeId
     * @return bool
     */
    public function updateData($storeId){
        $this->setDb('resources.database.params');
        $where = 'han_order.order_state > '.\Our\ApiConst::orderStateNew.' and han_favorites_store.store_id='.$storeId;
        $order_goods_count = $this->db->select('han_favorites_store.member_id,sum(han_order_goods.goods_num) as order_goods_count')->from('han_favorites_store')
            ->join('han_order','han_favorites_store.member_id = han_order.buyer_id and han_favorites_store.store_id = han_order.store_id','left')
            ->join('han_order_goods','han_order.order_id = han_order_goods.order_id','left')
            ->where($where)->group('member_id')->fetchAll();
        if(!empty($order_goods_count)){
            foreach($order_goods_count as $v){
                $data[$v['member_id']]['order_goods_count'] = $v['order_goods_count'];
            }
        }
        $order_total = $this->db->select('han_favorites_store.member_id,han_favorites_store.fav_time,sum(han_order.order_amount) as order_total')->from('han_favorites_store')
            ->join('han_order','han_favorites_store.member_id = han_order.buyer_id and han_favorites_store.store_id = han_order.store_id','left')
            ->where($where)->group('member_id')->fetchAll();
        if(!empty($order_total)){
            foreach($order_total as $v){
                $data[$v['member_id']]['order_total'] = $v['order_total'];
                $data[$v['member_id']]['fav_time'] = $v['fav_time'];
            }
        }
        if(!empty($data)) {
            foreach ($data as $key => $val) {
                $memberData = $this->db->from($this->_tableName)->where(array('store_id' => $storeId, 'member_id' => $key))->fetchOne();
                if (empty($memberData)) {
                    $insert_data = array();
                    $insert_data['member_id'] = $key;
                    $insert_data['store_id'] = $storeId;
                    $insert_data['add_time'] = time();
                    $insert_data['order_goods_count'] = $val['order_goods_count'];
                    $insert_data['order_total'] = $val['order_total'];
                    $insert_data['fav_time'] = $val['fav_time'];
                    $result = $this->db->insert($this->_tableName)->rows($insert_data)->execute();
                } else {
                    $result = $this->db->update($this->_tableName)->where(array('store_id' => $storeId, 'member_id' => $key))->rows($val)->execute();
                }
            }
        }
        return $result;
    }

    //插入数据大量
    public function addAll($datas)
    {
        $this->setDb(DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}({$this->insertField}) values";
        $extentSql=" ON DUPLICATE KEY UPDATE order_goods_count=order_goods_count+values(order_goods_count),order_total=order_total+values(order_total)";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("({0},{1},{2},{3},{4}),", $datas[$i]['storeId'], $datas[$i]['memberId'],$datas[$i]['orderGoodsCount'], $datas[$i]['orderTotal'],TIMESTAMP);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertSql=$insertAllSql.$extentSql;
                $one = $this->db->insert($this->_tableName)->query($insertSql);
                if (!$one) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertSql=$insertAllSql.$extentSql;
            $one =  $this->db->insert($this->_tableName)->query($insertSql);
            if (!$one) {
                $error++;
            }
        }
        if ($error > 0) {
            $dataJson=json_encode($datas);
            throw  new Exception('插入han_store_member_statistics失败,'.$dataJson, 4);
        }
    }

    //插入数据大量
    public function addAllReduce($datas)
    {
        $this->setDb(DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}({$this->insertField}) values";
        $extentSql=" ON DUPLICATE KEY UPDATE order_goods_count=order_goods_count-values(order_goods_count),order_total=order_total-values(order_total)";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("({0},{1},{2},{3},{4}),", $datas[$i]['storeId'], $datas[$i]['memberId'],$datas[$i]['orderGoodsCount'], $datas[$i]['orderTotal'],TIMESTAMP);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertSql=$insertAllSql.$extentSql;
                $one = $this->db->insert($this->_tableName)->query($insertSql);
                if (!$one) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertSql=$insertAllSql.$extentSql;
            $one =  $this->db->insert($this->_tableName)->query($insertSql);
            if (!$one) {
                $error++;
            }
        }
        if ($error > 0) {
            $dataJson=json_encode($datas);
            throw  new Exception('插入han_store_member_statistics失败,'.$dataJson, 4);
        }
    }

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

}
