<?php

namespace DAO;


class SaleMemberModel extends \DAO\AbstractModel {



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

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';
    public function init(){

    }

    public function getOne($where,$field){
        $this->setDb();
        return $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
    }

    public function getList($where,$field){
        $this->setDb();
        return $this->db->from($this->_tableName)->select($field)->where($where)->fetchAll();
    }
    public function getActAndSale($where,$field){
        $this->setDb();
        return $this->db->from($this->_tableName)->select($field)->join('han_sale_activity','han_sale_activity.sale_act_id = han_sale_member.sale_act_id','inner')->where($where)->where('sale_act_state = 1')->where('sale_start_date <='.time())->where('sale_end_date >='.time())->fetchAll();
    }
    /**
     * 是否有参加该店铺的销售活动
     */
    public function isJoin($storeId,$memberId){
        $saleDb4Redis = \Redis\Db4\SaleActivityRedisModel::getInstance();
        if($saleDb4Redis->tableKeyExists('storeId:'.$storeId) === false){
            //$memberIds = \DAO\SaleMemberModel::getInstance()->getList(array('store_id'=>$storeId),'member_id');
            $memberIds = $this->getActAndSale(array($this->_tableName.'.store_id'=>$storeId),'member_id');
            if($memberIds) {
                $memberIds = array_column($memberIds, 'member_id');
                in_array($memberId, $memberIds) ? $join = true : $join = false;
                $memberIds = array_flip($memberIds);
            }else{
                $memberIds = array('empty'=>1);
                $join = false;
            }
            $saleDb4Redis->tableHMSet('storeId:'.$storeId,$memberIds,\Our\ApiConst::oneDaySecond);
        }else{
            $saleDb4Redis->tableHGet('storeId:'.$storeId,$memberId) === false ? $join = false : $join = true;
        }
        return $join;
    }
    /**
     * 判断用户是否有参加这个店铺的销售活动 有的话返回活动id数组 没有返回false
     * @param $storeId
     * @param $memberId
     * @return array|bool|mixed
     * @throws \Our\Exception
     */
    public function isJoinStore($storeId,$memberId){
        if(!$storeId || !$memberId){
            return false;
        }
        if($memberId){
            $isJoin = $this->isJoin($storeId,$memberId);
        }
        if($isJoin){
            $activities = \Our\RedisHelper::cachedFunction(\Redis\Db4\SaleMemberRedisModel::getInstance(),array(&$this, 'getActAndSale'),array(array('han_sale_member.store_id'=>$storeId,'han_sale_member.member_id'=>$memberId),'han_sale_activity.sale_act_id,han_sale_activity.sale_start_date,han_sale_activity.sale_end_date,han_sale_member.sale_id'),\Our\ApiConst::oneHour,array($storeId));
            $acts = [];
            if($activities){
                foreach ($activities as $k=>$v){
                    if(!($v['sale_start_date'] <= time() && $v['sale_end_date'] >= time())){
                        unset($activities[$k]);
                    }
                }
                if($activities){
                    $acts = array_column($activities,'sale_id','sale_act_id');
                }
            }
            return $acts;
        }
        return false;
    }
    /**
     * 是否有参加平台的销售活动
     * @param $memberId
     * @return array
     * @throws \Our\Exception
     */
    public function isJoinPlatform($memberId){
        //$saleDAO = \DAO\SaleMemberModel::getInstance();
        $activities = \Our\RedisHelper::cachedFunction(\Redis\Db4\SaleMemberRedisModel::getInstance(),array(&$this, 'getActAndSale'),array(array('han_sale_member.member_id'=>$memberId),'han_sale_activity.sale_act_id,han_sale_activity.sale_start_date,han_sale_activity.sale_end_date,han_sale_member.sale_id'),\Our\ApiConst::tenMinSecond);
        $acts = [];
        if($activities){
            foreach ($activities as $k=>$v){
                if(!($v['sale_start_date'] <= time() || $v['sale_end_date'] >= time())){
                    unset($activities[$k]);
                }
            }
            if($activities){
                $acts = array_column($activities,'sale_id','sale_act_id');
            }
        }
        return $acts;
    }
    public function insert($data) {
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        return $this->db->insert($this->_tableName)->rows($data)->execute();
    }

    public function insertOrUpdate($data){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $baseSql = "insert  into {$this->_tableName}(sale_id,sale_act_id,member_id,store_id) values({0},{1},{2},{3}) ON DUPLICATE KEY UPDATE  sale_id=VALUES (sale_id)";
        $sql = \Our\Common::format($baseSql, $data['sale_id'], $data['sale_act_id'],$data['member_id'],$data['store_id']);
        return $this->db->insert($this->_tableName)->query($sql);
    }


    public function insertAllOrUpdate($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert into {$this->_tableName}(sale_id,sale_act_id,member_id,store_id) values";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("('{0}','{1}','{2}','{3}'),", $datas[$i]['sale_id'], $datas[$i]['sale_act_id'], $datas[$i]['member_id'], $datas[$i]['store_id']);
            $insertAllSql .= $addSql;
            if ($i % 1000 == 0 && $i != 0) {
                $insertAllSql = rtrim($insertAllSql, ',');
                $insertAllSql .= 'ON DUPLICATE KEY UPDATE sale_id = VALUES(sale_id)';
                $one = $this->db->insert()->query($insertAllSql);
                if ($one === false) {
                    $error++;
                }
                $insertAllSql = $baseSql;
            }
        }
        if ($insertAllSql != $baseSql) {
            $insertAllSql = rtrim($insertAllSql, ',');
            $insertAllSql .= 'ON DUPLICATE KEY UPDATE sale_id = VALUES(sale_id)';
            $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() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

}
