<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/3/28
 * Time: 下午4:36
 */
define('BASE_ROOT_PATH',str_replace('/test','',dirname(__FILE__)));

require_once(BASE_ROOT_PATH . '/fooder.php');
require_once(BASE_ROOT_PATH . '/helper/member_helper.php');

class member_helperTest extends PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass() {
        Base::run_util();
    }

    public function testExuser()
    {
        $user = member_helper::exmembers(array(array('member_mobile' => '13911129867','member_id' => 36490)),true,true);
        $user = member_helper::exmembers(array(array('member_mobile' => '13911129867','member_id' => 36490)),true,false);
        $user = member_helper::exmembers(array(array('member_mobile' => '13911129867','member_id' => 36490)),false,true);
    }

    public function testInitbonus()
    {
        $mod_member = Model('member');

        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = Model()->table('member')->field('*')->order('member_id asc')->limit("{$start},1000")->select();
            if(empty($items)) {
                return;
            }
            $i++;

            foreach ($items as $item)
            {
                $member_id = $item['member_id'];
                $pred = new predeposit_helper($member_id);
                $amount = $pred->total_bonus();
                $mod_member->editMember(['member_id' => $member_id],['available_bonus' => $amount]);
            }
        }
    }

    public function testInitinviter()
    {
        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = Model()->table('member_relation')->field('member_id,invited_user')->order('member_mobile asc')->limit("{$start},1000")->select();
            if(empty($items)) {
                return;
            }
            $i++;

            foreach ($items as $item)
            {
                $member_id = intval($item['member_id']);
                if($member_id <= 0) continue;
                $invitees = unserialize($item['invited_user']);
                if(empty($invitees)) continue;

                foreach ($invitees as $userid) {
                    $this->update_invitee($member_id,$userid);
                }
            }
        }
    }

    private function update_invitee($invitorid,$userid)
    {
        $mod = Model('member');
        $invitee = $mod->where(['member_id' => $userid])->find();
        if(empty($invitee)) return false;


        $inviter_id = intval($invitee['inviter_id']);
        if($inviter_id > 0) return false;

        $ret = $mod->editMember(['member_id' => $userid],['inviter_id' => $invitorid]);
        if($ret == false) {
            Log::record(__METHOD__ . "  update {$userid} invitor id err",Log::ERR);
        }
        else {
            Log::record(__METHOD__ . "  update {$userid} invitor id success",Log::DEBUG);
        }
    }
}
