<?php

namespace DAO\Store;

use OSS\Common;
use Our\ApiConst;
use Our\DbNameConst;
use Redis\Db6\StoreRedisModel;

/**
 * 店铺数据统计
 * @date 2018-5-14
 * @author csw
 */
class SellerModel extends \DAO\AbstractModel
{


    protected $redis;

    private $detailField = "seller_id as sellerId,seller_name as sellerName,member_id as memberId,seller_group_id as sellerGroupId,store_id as storeId,is_admin as isAdmin,last_login_time as lastLoginTime,token";

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

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

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

    /**
     * 获取店铺统计信息
     * @param $where
     * @return array
     */
    public function find($where)
    {
        $this->setDb($this->dbName);
        $data = $this->db->select($this->detailField)->from($this->_tableName)->where($where)->fetchOne();
        return $data;
    }

    public function getInfoBySellerName($sellerName)
    {
        $where['seller_name'] = $sellerName;
        return $this->find($where);
    }

    public function getByStoreIdAndGmtCreate($storeId, $gmtCreate)
    {
        $where['store_id'] = $storeId;
        $where['gmt_create'] = $gmtCreate;
        $res = $this->find($where);
        return $res;
    }

    public function getById($id)
    {
        $where['id'] = $id;
        $res = $this->find($where);
        return $res;
    }

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

    public function updateBySellerId($data,$sellerId){
        $where['seller_id']=$sellerId;
        return $this->update($data,$where);
    }

    /**
     * 插入数据
     * @param $data
     * @return mixed
     */
    public function insert($data)
    {
        return $this->db->insert($this->_tableName)->rows($data)->execute();
    }

    /**
     * @param $storeId 店铺id
     * @param $field 更新栏目
     * @param $value 增加值
     * @param $type ,'INC':增加,'DEC':减少
     */
    public function updateStoreStatisticsToday($storeId, $field, $value, $type = 'INC')
    {
        $h = 'todayData' . date('Ymd');
        $key = $storeId;
        $this->redis = StoreRedisModel::getInstance();
        $data = $this->redis->tableHGet($h, $key);
        $data[$field] = $type == 'INC' ? $data[$field] + $value : $data[$field] - $value;
        StoreRedisModel::tableHSet($h, $storeId, $data, ApiConst::oneDaySecond);
    }

    public function getInfoById($id, $field = '*', $isField = false)
    {
        $this->setDb();
        $where[$this->_primaryKey] = $id;
        $store = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        if ($isField) {
            return $store[$isField];
        } else {
            return $store;
        }

    }

    public function getInfoByMemberId($memberId, $field = '*', $isField = false)
    {
        $this->setDb();
        $where['member_id'] = $memberId;
        $store = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        if ($isField) {
            return $store[$isField];
        } else {
            return $store;
        }
    }

    //插入数据大量
    public function addAllReduce($datas)
    {
        $this->setDb(DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}(store_id,order_count,order_total,gmt_create) values";
        $extentSql = " ON DUPLICATE KEY UPDATE order_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}),", $datas[$i]['storeId'], $datas[$i]['orderCount'], $datas[$i]['orderTotal'], datas[$i]['gmtCreate']);
            $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 addAll($datas)
    {
        $this->setDb(DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}(store_id,order_count,order_total,fav_count,gmt_update,gmt_create) values";
        $extentSql = " ON DUPLICATE KEY UPDATE order_count=order_count+values(order_count),order_total=order_total+values(order_total),fav_count=fav_count+values(fav_count),gmt_update=values(gmt_update)";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("({0},{1},{2},{3},{4},'{5}'),", $datas[$i]['storeId'], $datas[$i]['orderCount'], $datas[$i]['orderTotal'], $datas[$i]['favCount'], TIMESTAMP, date('Y-m-d', 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_statics_day失败,' . $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;
    }


    /**
     * 获取字段
     * @return array
     */
    private function _getColumns()
    {
        return array(
            'store_id as storeId',
            'order_count as orderCount',
            'order_total as orderTotal',
            'fav_count as favCount',
            'goods_count as goodsCount',
        );
    }

}
