<?php
namespace DAO\Coupon;
/**
 * User: liuyuzhen
 * Date: 2018/6/7
 * Time: 13:50
 * Description:
 */

class MemberCouponModel extends \DAO\AbstractModel{

    public $errorCode;

    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_member_coupon';
    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';

    public function init(){
    }

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

    /**
     * 获取会员指定优惠券领取记录列表
     * @param $memberId
     * @param $couponIds
     * @return mixed
     */
    public function getListByMemberId($memberId,$couponIds){
        $whereSql = ' member_id = '.$memberId .' and coupon_id in ('.implode(',',$couponIds).')';
        return $result;
    }

    /**
     * 获取指定会员的优惠券记录
     * @param $where
     * @param null $memberId
     * @return mixed
     * @throws \Our\Exception
     */
    public function getMemberCouponsByMemberId($where,$memberId = null){
        $this->setDb($this->dbName);
        $field = 'coupon_id,add_time,out_time';
        $memberCoupons = \Our\RedisHelper::cachedFunction(\Redis\Db13\MemberCouponRedisModel::getInstance(),array(&$this, 'getList'),array($where,$field),\Our\ApiConst::oneHour,array($memberId));
        return $memberCoupons;
    }

    /**
     * 获取当前用户未领取的有效优惠券
     * @param $where
     * @param $memberId
     * @return array
     */
    public function getMemberCouponByMemberIdWithOuttime($memberId){
        $memberCouponRedisModel = \Redis\Db13\MemberCouponRedisModel::getInstance();
        $memberCoupons = $memberCouponRedisModel->tableCacheGet(\Our\NameConst::memberCounponListPrefix.$memberId);
        if($memberCoupons){
            $memberCoupons = unserialize($memberCoupons);
            $newMemberCouponArray = array();
            foreach($memberCoupons as $tempMemberCoupon){
                if($tempMemberCoupon['out_time']>=TIMESTAMP){
                    $newMemberCouponArray[] =$tempMemberCoupon;
                }
            }
            return $newMemberCouponArray;
        }
        $where = ' coupon_state ='.\Our\ApiConst::couponUnused.' and member_id ='.$memberId;
        $where .= ' and out_time > '.TIMESTAMP;
        $field = 'coupon_id,add_time,out_time';
        $memberCoupons = $this->getList($where , $field);
        if($memberCoupons){
            $memberCouponRedisModel->tableCacheSet(\Our\NameConst::memberCounponListPrefix.$memberId,serialize($memberCoupons),\Our\ApiConst::oneDaySecond);
        }
        return $memberCoupons;
    }

    public function getValidMemberCoupon($where,$memberId){
        if(!$memberId){
            $this->errorCode = \Error\CodeConfigModel::emptyMemberCouponMemberId;
            return false;
        }
        if(!$where['couponState']){
            $this->errorCode = \Error\CodeConfigModel::emptyMemberCouponState;
            return false;
        }
        if(!in_array($where['couponState'],array_keys(\Our\ArrayConst::couponState))){
            $this->errorCode = \Error\CodeConfigModel::wrongMemberCouponState;
            return false;
        }
        return true;
    }

    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 insertBatch($datas){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $error = 0;
        $baseSql = "insert IGNORE into {$this->_tableName}(coupon_id,coupon_state,add_time,out_time,member_id,gift_order_id) values";
        $insertAllSql = $baseSql;
        for ($i = 0; $i < count($datas); $i++) {
            $addSql = \Our\Common::format("('{0}','{1}','{2}','{3}','{4}','{5}'),", $datas[$i]['coupon_id'], $datas[$i]['coupon_state'], $datas[$i]['add_time'], $datas[$i]['out_time'], $datas[$i]['member_id'], $datas[$i]['gift_order_id']);
            $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;
    }

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

}