<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/7/5
 * Time: 下午6:34
 */

require_once(BASE_ROOT_PATH . '/helper/user_session/storage.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/generator.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/content.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/answer.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/comments.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/special.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/setting.php');
require_once(BASE_ROOT_PATH . '/helper/ugc/category.php');
require_once(BASE_ROOT_PATH . '/helper/search/tcp_client.php');
require_once(BASE_ROOT_PATH . '/helper/bonus_helper.php');
require_once(BASE_ROOT_PATH . '/helper/predeposit_helper.php');
require_once(BASE_ROOT_PATH . '/helper/relation_helper.php');
require_once(BASE_ROOT_PATH . '/helper/tools/fast_image.php');

use ugc\special_vote;
use ugc\special;
use ugc\special_answer;
use ugc\special_submitor;
use ugc\special_support;

class ugc_helper
{
    const public_all = 0;
    const protected_self = 1;
    const private_self   = 2;

    public static function crate_special($data,&$err)
    {
        $generator = new ugc\generator();
        $special = $generator->crate_special($data,$err);
        return $special;
    }

    public static function pub_special($special_id,$setting,&$err)
    {
        $mod_special = Model('mb_special');
        $special_info = $mod_special->getMbSpecialByID($special_id,'*',true);
        if(empty($special_info)) {
            $err = ['code' => errcode::ErrParamter,'msg' => "该专题不存在"];
            return false;
        }
        $special = new ugc\special($special_info);
        if($special->published()) {
            $err = ['code' => errcode::ErrParamter,'msg' => "文章发布之后，不可以编辑."];
            return false;
        }
        $setting = new ugc\setting($setting,$special);
        $rule = $setting->format();
        $rule['pubtime'] = time();
        $rule['state'] = 0;

        $ret = $mod_special->editUserSpecial($special_id,['special_id' => $special_id,'member_id' => session_helper::memberid()],$rule);
        if($ret != false)
        {
            $type = $setting->reader_type();
            if($type != ugc\setting::mine_type) {
                $spid = intval($special_id);
                QueueClient::push('onAsyncUgcPublish',['special_id'=> $spid]);
            }
         }
        return $ret;
    }

    public static function del_special($special_id,&$err)
    {
        $mod_special = Model('mb_special');
        $special_info = $mod_special->getMbSpecialByID($special_id,'*',true);
        if(empty($special_info)) {
            $err = ['code' => errcode::ErrParamter,'msg' => "该专题不存在"];
            return false;
        }
        $special = new ugc\special($special_info);
        if($special->memberid() != session_helper::memberid()) {
            $err = ['code' => errcode::ErrSpecial,'msg' => "您不能删除该内容"];
            return false;
        }

        $ret = $mod_special->delMbSpecialByID($special_id);
        if($ret != false) {
            $type = $special->reader_type();
            $spid = intval($special_id);
            QueueClient::push('onAsyncUgcDel',['user_id' => session_helper::memberid(),'specials'=> array(['type' => $type,'spid' => $spid])]);
            return $ret;
        } else {
            $err = ['code' => errcode::ErrSpecial,'msg' => "删除失败"];
            return false;
        }
    }

    public static function subscribe($memberid,$special_id)
    {
        $mod_special = Model('mb_special');
        $special_info = $mod_special->getMbSpecialByID($special_id,'*',true);
        $special = new special($special_info);
        $author = $special->memberid();
        return relation_helper::onSubscribe($memberid,$author);
    }

    public static function submit($special_id,$options,&$err)
    {
        $mod_special = Model('mb_special');
        $special_info = $mod_special->getMbSpecialByID($special_id,'*',true);
        $special = new special($special_info);
        $vote_single = $special->vote_single();

        $submitor = new special_submitor($special_id,$vote_single);
        if($submitor->submited()) {
            $err = ['code' => errcode::ErrSpecial,'msg' => "您已经提交过"];
            return false;
        } else {
            $submitor->submit();
        }

        if(!empty($options))
        {
            $vote = $options['vote'];
            $answers = $options['question'];
        } else {
            $vote = false;
            $answers = false;
        }

        $answer_diff = [];
        $vote_result = [];
        $num = 0;

        if($special->has_vote() || $special->has_question())
        {
            if($special->has_vote() && $vote != false)
            {
                $voter = new special_vote($special->special_id());
                $vote_result = $voter->vote($vote,$vote_num);

                if($vote_result == false) {
                    return false;
                } else {
                    $num += $vote_num;
                    $bonus_type = 0;
                }
            }
            if($special->has_question() && $answers != false)
            {
                $answor = new special_answer($special);
                $correct_num = $answor->answer($answers,$answor_id);
                if($answor_id == false) {
                    $err = ['code' => errcode::ErrSpecial,'msg' => "您已经答过题了，不能再答"];
                    return false;
                }
                $num += $correct_num;
                $answer_diff = $answor->diff();
                $bonus_type = 1;
            }
        }
        else {
            $num = 1;
            $bonus_type = 2;
        }

        $type_sn = "";
        $amount = 0.0;

        $rule = $special->submit_rule();
        if($rule != false && $num > 0)
        {
            $type_sn = $rule->make_bonus($num,$amount,$bonus_rate);
            if(isset($answor_id) && $type_sn != false) {
                Model()->table('special_answer')->where(['spanswer_id' => $answor_id])->update(['amount' => $amount,'bonus_rate' => $bonus_rate]);
            }
        }

        QueueClient::push('onAsyncUgcSubmit',['special_id' => $special_id,'user_id' => session_helper::memberid()]);

        return ['vote_result' => $vote_result,'answer_diff' => $answer_diff,'type_sn' => $type_sn,'num' => $num,'amount' => $amount,'bonus_type' => $bonus_type];
    }

    public static function support_special($special_id,$comment_id)
    {
        $supporter = new special_support($special_id,$comment_id);

        if($supporter->supported()) {
            $supporter->unsupport();
            $supported = false;
        } else {
            $supporter->support();
            $supported = true;
        }

        if($supported) {
            QueueClient::push('onAsyncUgcSupport',['special_id' => $special_id,'comment_id' => $comment_id,'user_id' => session_helper::memberid()]);
        }

        return $supported;
    }

    public static function appreciate($special_id,$rate,$money,$bless)
    {
        $mod_special = Model('mb_special');
        $special_info = $mod_special->getMbSpecialByID($special_id,'*',true);
        $special = new special($special_info);
        $toid = $special->memberid();
        $senderid = session_helper::memberid();

        return account_helper::appreciate($senderid,$rate,$money,$toid,$bless);
    }

    public static function categories()
    {
        return ugc\category::instance()->categories();
    }
    public static function category_title($category_id) {
        return ugc\category::instance()->title($category_id);
    }

    public static function init_server()
    {
        $initer = new ugciniter();
        $initer->init_relation();
//        $initer->init_special();
//        $initer->init_fellows();
    }
    public static function send_reward()
    {

    }
}

class ugciniter
{
    public function init_relation()
    {
        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = Model()->table('member_relation')->field('*')->where(['member_id' => ['gt',0]])->order('member_id asc')->limit("{$start},1000")->select();
            if(empty($items)) {
                return;
            }
            $i++;

            foreach ($items as $item)
            {
                $iRelation = new \relation\mem_relation($item);
                $follows = $iRelation->subscriber();
                $uids = [];
                foreach ($follows as $val)
                {
                    $uid = intval($val);
                    if($uid > 0) {
                        $uids[] = $uid;
                    }
                }
                if(!empty($uids)) {
                    search\relation_client::instance()->add_follow(array('user_id' => $iRelation->member_id(),'friends' => $uids));
                }
            }
        }
    }

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

            foreach ($items as $item) {
                $this->add_follow($item['member_id'],$item['inviter_id']);
            }
        }
    }

    private function add_follow($member_id, $inviter_id)
    {
        $member_id  = intval($member_id);
        $inviter_id = intval($inviter_id);

        if($inviter_id > 0) {
            search\relation_client::instance()->add_follow(array('user_id' => $member_id,'friends'=>[$inviter_id]));
            search\relation_client::instance()->add_follow(array('user_id' => $inviter_id,'friends'=>[$member_id]));
        }

        if($member_id > 0)
        {
            $iRelation = new \relation\mem_relation($member_id);
            $follows = $iRelation->subscriber();
            $uids = [];
            foreach ($follows as $val)
            {
                $uid = intval($val);
                if($uid > 0) {
                    $uids[] = $uid;
                }
            }
            if(!empty($uids)) {
                search\relation_client::instance()->add_follow(array('user_id' => $member_id,'friends' => $uids));
            }
        }

        if($member_id > 0)
        {
            $mod_member = Model('member');
            $items = $mod_member->getMemberList(['inviter_id' => $member_id],'member_id');

            $uids = [];
            foreach ($items as $val) {
                $uid = intval($val['member_id']);
                if($uid > 0) {
                    $uids[] = $uid;
                }
            }
            if(!empty($uids)) {
                search\relation_client::instance()->add_follow(array('user_id' => $member_id,'friends' => $uids));
            }
        }
    }
    public function init_special()
    {
        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = Model()->table('mb_special')->where(['from_user' => 1,'state' => 0])->field('special_id,member_id,reader_type')->order('member_id asc')->limit("{$start},1000")->select();
            if(empty($items)) {
                return;
            }
            $i++;

            foreach ($items as $item) {
                $this->add_special($item);
            }
        }
    }
    private function add_special($item)
    {
        $user_id     = intval($item['member_id']);
        $special_id  = intval($item['special_id']);
        $reader_type = intval($item['reader_type']);

        if($user_id >0 && $special_id > 0 && $reader_type != ugc_helper::private_self) {
            search\relation_client::instance()->add_special(array('user_id' => $user_id,'specials'=> [['type' => $reader_type,'spid' => $special_id]]));
        }
    }
}