<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/6/26
 * Time: 下午9:30
 */
require_once (BASE_ROOT_PATH . '/helper/account_helper.php');
require_once (BASE_ROOT_PATH . '/helper/predeposit_helper.php');
require_once (BASE_ROOT_PATH . '/helper/bonus_helper.php');
require_once (BASE_ROOT_PATH . '/helper/push_helper.php');


class notify_helper
{
    private static function secs_days($secs)
    {
        $days = intval($secs / 86400) + ($secs % 86400 != 0) ? 1 : 0;
        return $days;
    }

    static public function onBonusExpire($warn_remain_days, $warn_interval_days)
    {
        $mod_bonus = Model("user_bonus");
        $items = $mod_bonus->getNeedWarn($warn_remain_days, $warn_interval_days);
        if($items == false) return;

        $member_amount = [];
        $member_day = [];
        $ids = [];
        foreach ($items as $key => $val)
        {
            $bonus = bonus\user_bonus::create_by_param($val);
            $leftsecs = $bonus->usable_time() - time();
            $remain_days = self::secs_days($leftsecs);
            $amount = $bonus->remain_amount();

            if(isset($member_amount[$bonus->user_id()]) == false) {
                $member_amount[$bonus->user_id()] = $amount;
                $member_day[$bonus->user_id()] = $remain_days;
            } else {
                $member_amount[$bonus->user_id()] += $amount;
            }

            $ids[] = $bonus->bonus_id();
        }
        foreach ($member_amount as $member_id => $amount) {
            $remain_days = $member_day[$member_id];
            push_helper::notice_expring($member_id,$amount,$remain_days);
        }

        if (!empty($ids)) {
            $mod_bonus->edit(array('bonus_id' => array('in', $ids)),array("notify_time" => time()));
        }
    }

    static public function bonus_expired($maxtm)
    {
        $mod_bonus = Model("user_bonus");
        $items = $mod_bonus->getExpired($maxtm);

        if(empty($items)) return false;

        $ids = [];
        $member_amount = [];
        foreach ($items as $key => $val)
        {
            $bonus = bonus\user_bonus::create_by_param($val);
            $user_id = $bonus->user_id();
            $amount  = $bonus->remain_amount();

            $pred = new predeposit_helper($user_id);
            $pred->bonus_expire($val);
            $ids[] = $bonus->bonus_id();

            if(isset($member_amount[$bonus->user_id()]) == false) {
                $member_amount[$bonus->user_id()] = $amount;
            } else {
                $member_amount[$bonus->user_id()] += $amount;
            }
        }

        foreach ($member_amount as $member_id => $amount) {
            push_helper::notice_expired($member_id,$amount);
        }

        if (!empty($ids)) {
            $mod_bonus->edit(array('bonus_id' => array('in', $ids)),array("expired" => 1));
            return true;
        } else {
            return false;
        }
    }

    static public function release_bonus()
    {
        $bonus_type = Model('bonus_type');

        $one_hour = 60 * 60;
        $condition = array('remain_amount' => array('gt',0),'is_refund' => 0,'send_end_date' =>array('lt',time() - $one_hour));
        $bonus_types = $bonus_type->getTypeList($condition,'','*','',false);
        if(empty($bonus_types) || count($bonus_types) <= 0) {
            return;
        }

        foreach($bonus_types as $type)
        {
            try
            {
                $pred = new predeposit_helper($type['sender_id']);
                $trans = new trans_wapper(null,__METHOD__);

                $bonus_type->edit(array('type_id' =>$type['type_id']),array('is_refund' => 1,'refund_time' => time()));
                if ($bonus_type->affected_rows() <= 0) {
                    $sresult = implode(',',$type);
                    Log::record("bonus refund 更新状态失败，result:{$sresult}.");
                } else {
                    $pred->bonus_refund($type);
                    $condition = array('type_id' =>$type['type_id'],'bonus_status' => array('in','0,1'));
                    Model('user_bonus')->where($condition)->delete();
                }
                $trans->commit();
            }
            catch (Exception $e)
            {
                $trans->rollback();
                $sresult = implode(',',$type);
                Log::record('bonus refund : error:' . $e->getMessage() . " result:{$sresult}.");
            }
        }
    }

    static public function onFcodeWarning()
    {
        $pre_secs = 86400 * 5;

        $mod_member = Model('member');
        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = Model()->table('goods_fcode')
                            ->field('fc_id,mobile,goods_commonid,usable_time')
                            ->where(array('usable_time&usable_time' => ['_multi'=>true,['gt',time() - $pre_secs],['lt',time()]],'fc_state' => 0,'warning_time' => 0))
                            ->order('fc_id desc')
                            ->limit("{$start},1000")->select();
            if(empty($items)) {
                return;
            }
            $i++;
            foreach ($items as $item)
            {
                $fc_id = $item['fc_id'];
                $cid   = $item['goods_commonid'];
                $usable_time = $item['usable_time'];
                $mobile = $item['mobile'];
                $mid   = self::member_id($mod_member,$mobile);

                if($mid!= false && $mid > 0) {
                    push_helper::fcode_warning($cid,$mid,$usable_time);
                }
                Model()->table('goods_fcode')->where(['fc_id' => $fc_id])->update(['warning_time' => time()]);
            }
        }
    }
    static private function member_id($mod_member,$mobile)
    {
        $items = $mod_member->where(['member_mobile' => $mobile])->select();
        if(!empty($items)) {
            return intval($items[0]['member_id']);
        }
        return false;
    }
}