<?php

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

require_once(BASE_ROOT_PATH . '/mobile/control/special.php');
require_once(BASE_ROOT_PATH . '/helper/ugc_helper.php');
require_once(BASE_ROOT_PATH . '/helper/search/tcp_client.php');
require_once(BASE_ROOT_PATH . '/helper/text_filter.php');
require_once(BASE_ROOT_PATH . '/helper/bonus_helper.php');
require_once(BASE_ROOT_PATH . '/helper/session_helper.php');

class member_ugcControl extends specialControl
{
    const greater = 0;
    const lesser  = 1;
    private $mUgcBanner;

    public function __construct()
    {
        parent::__construct();
        global $config;
        $this->mUgcBanner = $config['ugc_banner'];
    }

    public function pub_listOp()
    {
        return $this->fetch('pub_list');
    }

    public function pri_listOp()
    {
        $this->need_login();
        return $this->fetch('pri_list');
    }
    public function mine_listOp()
    {
        $this->need_login();
        return $this->fetch('mine_list');
    }

    private function fetch($type)
    {
        $special_id = intval($_GET['special_id']);
        $count = $this->page_size();

        if($special_id == -1) {
            $special_id = -1;
            $direct = self::lesser;
        }
        elseif ($special_id == 0) {
            return self::outsuccess(['special_list' => null,'mobile_page' => mobile_page(0)]);
        }
        else {
            $direct = $this->direct();
        }

        if($type == "pub_list") {
            $specials = search\relation_client::instance()->fetch_pub_special(['special_id' => $special_id,'count'=> $count,'type' => $direct]);
        }
        elseif($type == 'pri_list') {
            $specials = search\relation_client::instance()->fetch_pri_special(['user_id' => session_helper::memberid(),
                'special_id' => $special_id,'count'=> $count,'type' => $direct]);
        }
        elseif($type == "mine_list") {
            $specials = $this->mine_specials($special_id,$count);
        }
        else {
            return self::outerr(errcode::ErrParamter);
        }

        $blocks = [];
        if($special_id == -1)
        {
            $extid = $this->tip_block($type);
            if($extid != false) {
                $helper = new special_formater($extid);
                $blocks = $helper->format($goods_ids);
            }
        }

        if(empty($specials))
        {
            $page_no = $this->page_no();
            if($page_no == 1) $page_no = 0;
            return self::outsuccess(['special_list' => $blocks,'mobile_page' => mobile_page($page_no)]);
        }
        else
        {
            $special_list = $this->special_list($specials,$ugcs);
            $page_no = $this->page_no();
            if($this->page_size() <= count($specials)) {
                $page_no += 1;
            }
            foreach ($special_list as $val) {
                $blocks[] = $val;
            }
            return self::outsuccess(['special_list' => $blocks,
                'ugcs' => $ugcs,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'mobile_page' => mobile_page($page_no)]);
        }
    }

    private function mine_specials($special_id,$count)
    {
        $mod_special = Model();
        $userid = session_helper::memberid();

        if($special_id == -1) {
            $items = $mod_special->table('mb_special')->field('special_id')
                ->where(['member_id' => $userid,'from_user' => 1])
                ->order('special_id desc')->limit($count)->select();
        } else {
            $items = $mod_special->table('mb_special')->field('special_id')
                ->where(array('special_id' => ['lt',$special_id],'member_id' => $userid,'from_user' => 1))
                ->order('special_id desc')->limit($count)->select();
        }

        $result = [];
        foreach ($items as $item) {
            $spid = intval($item['special_id']);
            $result[] = $spid;
        }

        return $result;
    }
    private function tip_block($type)
    {
        if($type == "pub_list") {
            $spid = $this->mUgcBanner['pub'];
        }
        elseif($type == 'pri_list') {
            $spid = $this->mUgcBanner['friend'];
        }
        elseif($type == "mine_list") {
            $spid = $this->mUgcBanner['mine'];
        }
        else {
            return false;
        }

        if(empty($spid) || $spid == 0) {
            return false;
        }
        else {
            return $spid;
        }
    }
    private function direct()
    {
        $cur_page = $this->page_no();
        if($cur_page == 1) {
            return self::greater;
        } else {
            return self::lesser;
        }
    }

    private function special_list($spids, &$ugcs)
    {
        $result = [];
        $mod_special = Model('mb_special');
        $items = $mod_special->getMbSpecialList(['special_id' => ['in',$spids],'member_id' => ['gt',0],'from_user' => 1]);

        $users = [];
        $specials = [];
        foreach ($items as $item)
        {
            $special = new ugc\special($item);
            $specials[] = $special;
            $sender = $special->memberid();
            $users[] = $sender;
        }
        sort($users);
        $users = array_unique($users);

        $minfos = [];
        if(!empty($users))
        {
            $mod_member = Model('member');
            $members = $mod_member->getMemberList(['member_id' => ['in',$users]]);
            foreach ($members as $member) {
                $info = new member_info($member);
                $mid = $info->member_id();
                $minfos[$mid] = $info;
            }
        }

        $ugcs = [];
        foreach ($specials as $special)
        {
            $block = special_formater::format_ugc($special);
            $result[] = $block;
            $divider = special_formater::def_divider();
            $result[] = $divider;

            $mid = $special->memberid();
            $minfo = $minfos[$mid];

            if(is_null($minfo) == false) {
                $ugc = $this->format_ugc($minfo,$special);
                $ugcs[] = $ugc;
            }
        }
        return $result;
    }

    private function format_ugc(member_info $minfo, ugc\special $special)
    {
        $ret['special_id'] = $special->special_id();
        $ret['member_avatar'] = $minfo->avatar();
        $ret['member_nickname'] = $minfo->nickname();
        $ret['has_vote'] = $special->has_vote();
        $ret['appreciate_num'] = $special->appreciates();
        $ret['comment_num'] = $special->comments();
        $ret['clicks'] = $special->clicks();
        $ret['pubtime'] = $special->editime();
        $ret['desc'] = $special->description();
        $supporter = new ugc\special_support($special->special_id(),0);
        $ret['supported'] = $supporter->supported();
        $ret['support_num'] = $special->likes();
        $cid = $special->category_id();
        $ret['category'] = ugc_helper::category_title($cid);

        $ret['can_del'] = false;
        if(session_helper::logined())
        {
            if($special->memberid() == $_SESSION['member_id']) {
                $ret['can_del'] = true;
            }
        }

        return $ret;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public function addOp()
    {
        $this->need_login();

        $contet = $_POST['content'];
        if(empty($contet)) {
            return self::outerr(errcode::ErrParamter,"上传的内容不能为空");
        }
        return $this->add($contet);
    }

    public function addexOp()
    {
        $this->need_login();

        $contet = $_POST['content'];
        if(empty($contet)) {
            return self::outerr(errcode::ErrParamter,"上传的内容不能为空");
        }
        else {
            $contet = urldecode($contet);
        }
        return $this->add($contet);
    }

    private function add($contet)
    {
        $sp_data = json_decode($contet,true);
        if(empty($sp_data)) {
            return self::outerr(errcode::ErrParamter,"上传的内容不能为空");
        }

        $spobj = ugc_helper::crate_special($sp_data,$err);
        if($spobj == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        if($spobj->count() > 0)
        {
            $special_id = $spobj->save($_SESSION['member_id'],$sp_data);
        } else {
            $special_id = false;
        }

        if($special_id == false) {
            return self::outerr(errcode::ErrUGC,"抱歉，内容云同步失败 :(");
        }
        else {
            return self::outsuccess(['special_id' => $special_id]);
        }
    }

    public function previewOp()
    {
        $this->need_login();
        return parent::indexOp();
    }

    public function publishOp()
    {
        $this->need_login();

        $special_id = intval($_GET['special_id']);
        $setting = $_GET['setting'];

        if($special_id < 0 || empty($setting)) {
            return self::outerr(errcode::ErrParamter);
        }
        return $this->publish($special_id,$setting);
    }

    public function publishexOp()
    {
        $this->need_login();

        $special_id = intval($_GET['special_id']);
        $setting = $_GET['setting'];

        if($special_id < 0 || empty($setting)) {
            return self::outerr(errcode::ErrParamter);
        }
        else {
            $setting = urldecode($setting);
        }
        return $this->publish($special_id,$setting);
    }

    private function publish($special_id,$setting)
    {
        $setting = json_decode($setting,true);
        if(ugc_helper::pub_special($special_id,$setting,$err) == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else {
            return self::outsuccess(['special_id' => $special_id]);
        }
    }

    public function delOp()
    {
        $this->need_login();

        $special_id = intval($_GET['special_id']);
        if(ugc_helper::del_special($special_id,$err) == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else {
            return self::outsuccess(['special_id' => $special_id]);
        }
    }

    public function supportOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }
        $comment_id = intval($_GET['comment_id']);
        $supported = ugc_helper::support_special($special_id,$comment_id);
        return self::outsuccess(['special_id' => $special_id,'comment_id' => $comment_id,'supported' => $supported]);
    }

    public function commentsOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }
        $comment_id = intval($_GET['comment_id']);
        if($comment_id <= 0)
        {
            $mod_comment = Model('ugc_comment');
            $count = $mod_comment->top_counts($special_id);
            $items = $mod_comment->getTopCommentList($special_id,'comment_id',$this->page_size(),$count);
            $pages = $mod_comment->gettotalpage();
            $mobile_page = mobile_page($pages);

            $commentids = $this->commentids($items);
            if(!empty($commentids))
            {
                $mod = Model('ugc_comment');
                $comment_subcounts = [];
                $items = $mod->comments_counts($special_id,$commentids);
                foreach ($items as $item) {
                    $comment_id = intval($item['comment_id']);
                    $count = intval($item['nc_count']);
                    $comment_subcounts[$comment_id] = $count;
                }
                $comments = $mod->getCommentList(array('top_id' => ['in',$commentids]),'*',0);
                $comments_obj =new ugc\comments($comments,$special_id,$comment_subcounts);
                $comments = $comments_obj->comments();
                $uids = $comments_obj->users();
                $members = $this->users($uids);
            } else {
                $comments = [];
                $members = [];
            }
        }
        else
        {
            $mod_comment = Model('ugc_comment');
            $count = $mod_comment->comment_counts($special_id,$comment_id);
            $items = $mod_comment->getSubCommentList($special_id,$comment_id,'comment_id',$this->page_size(),$count);
            $pages = $mod_comment->gettotalpage();
            $mobile_page = mobile_page($pages);
            $commentids = $this->commentids($items);

            if($commentids) {
                $mod = Model('ugc_comment');
                $comments = $mod->getCommentList(array('comment_id' => ['in',$commentids]),'*',0);
                $comments_obj =new ugc\comments($comments,$special_id,[]);
                $comments = $comments_obj->comments();
                $uids = $comments_obj->users();
                $members = $this->users($uids);
            } else {
                $comments = [];
                $members = [];
            }
        }

        return self::outsuccess(['comments' => $comments,'members' => $members,'mobile_page' => $mobile_page]);
    }

    private function users($user_ids)
    {
        if(empty($user_ids)) return [];

        $mod_member = Model('member');
        $members = $mod_member->getMemberList(array('member_id' => ['in',$user_ids]));
        if(empty($members)) return [];

        $result = [];
        foreach ($members as $item)
        {
            $member = new member_info($item);
            $val['member_id'] = $member->member_id();
            $val['avatar'] = $member->avatar();
            $val['nickname'] = $member->nickname();

            $result[] = $val;
        }
        return $result;
    }

    private function commentids($items)
    {
        $result = [];
        foreach ($items as $val) {
            $commentid = intval($val['comment_id']);
            $result[] = $commentid;
        }
        return $result;
    }

    public function commentOp()
    {
        $this->need_login();

        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }
        $comment = urldecode($_GET['content']);
        if(empty($comment)) {
            return self::outerr(errcode::ErrParamter,"评论内容不能为空.");
        }
        $comment = text_filter::filter_html($comment);
        if(empty($comment)) {
            return self::outerr(errcode::ErrParamter,"评论内容不能含非法字符.");
        }

        $comment_id = intval($_GET['comment_id']);
        $mod_comment = Model('ugc_comment');
        if($comment_id > 0) {
            $ret = $mod_comment->respond_comment($special_id,$comment_id,session_helper::memberid(),$comment);
        } else {
            $ret = $mod_comment->comment($special_id,session_helper::memberid(),$comment);
        }

        if($ret == false) {
            return self::outerr(errcode::ErrDB,"抱歉，评论出错了.");
        }
        else
        {
            $mod = Model('ugc_comment');
            $comments = $mod->getCommentList(['comment_id' => $ret],'*',0);
            $comments_obj = new ugc\comments($comments,$special_id,[]);
            $comments = $comments_obj->comments();
            $uids = $comments_obj->users();
            $members = $this->users($uids);

            QueueClient::push('onAsyncUgcComment',['special_id' => $special_id, 'comment_id' => $comment_id,'user_id' => session_helper::memberid()]);
            return self::outsuccess(['comments' => $comments,'members' => $members,'mobile_page' => mobile_page(0)]);
        }
    }

    public function mine_bonusOp()
    {
        $this->need_login();
        $pred = new predeposit_helper($_SESSION['member_id']);
        $bonus_rate = $pred->bonus_rate();

        if($bonus_rate != null)
        {
            $rates = $bonus_rate->format();
            $rates_money = [];
            foreach ($rates as $rate => $money) {
                $item['rate']  = $rate;
                $item['total'] = $money;
                $rates_money[] = $item;
            }
        }
        else {
            $rates_money = [];
        }

        return self::outsuccess(['bonus_rate' => $rates_money]);
    }

    public function appreciateOp()
    {
        $this->need_login();

        $special_id = intval($_GET['special_id']);
        $rate  = intval($_GET['rate']);
        $money = intval($_GET['money']);

        $bless = urldecode($_GET['bless']);
        $bless = text_filter::filter_html($bless);

        if($special_id < 0 || $rate <= 0 || $rate > 100 || $money <= 0) {
            return self::outerr(errcode::ErrParamter,"参数错误");
        }

        $ret = ugc_helper::appreciate($special_id,$rate,$money,$bless);
        if($ret == false) {
            return self::outsuccess(errcode::ErrBonus,"抱歉，赞赏失败，请晚点再试。");
        }
        else
        {
            $mod_appreciate = Model('appreciate');
            $insertid = $mod_appreciate->insert(['special_id' => $special_id,'member_id' => session_helper::memberid(),'rate' => $rate,'money' => $money,'addtime' => time()]);
            if($insertid != false) {
                $mod_special = Model('mb_special');
                $mod_special->table('mb_special')->where(['special_id' => $special_id])->update(array('appreciates' => ['exp', 'appreciates + 1'],
                                                                                                      'appreciate_amonut' => ['exp', "appreciate_amonut + {$money}"]));
            }
            QueueClient::push('onAsyncUgcAppreciate',['special_id' => $special_id,
                                                      'user_id' => session_helper::memberid(),
                                                      'rate' => $rate,'amount' => $money]);
            return self::outsuccess(null);
        }
    }
    public function appreciate_listOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }

        $mod_appreciate = Model('appreciate');
        $count = $mod_appreciate->counts($special_id);
        $items = $mod_appreciate->getListBySpecialid($special_id,'*',$this->page_size(),$count);
        $pages = $mod_appreciate->gettotalpage();

        $uids = [];
        foreach ($items as $val) {
            $user_id = intval($val['member_id']);
            $uids[] = $user_id;
        }
        $members = $this->users($uids);

        $result = [];
        foreach ($items as $item) {
            $val = [];
            $val['member_id'] = intval($item['member_id']);
            $val['rate'] = intval($item['rate']);
            $val['money'] = doubleval($item['money']);
            $val['addtime'] = intval($item['addtime']);

            $result[] = $val;
        }

        return self::outsuccess(['appreciate' => $result,'members' => $members,'mobile_page' => mobile_page($pages)]);
    }

    public function answer_pageOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }
        $memberid = session_helper::memberid();
        if($memberid > 0) {
            $mod_answer = Model('ugc_answer');
            $answer = $mod_answer->getAnswer($special_id,$memberid);
        }

        if(empty($answer))
        {
            return self::outsuccess(['answer' => [],'special_id' => $special_id,'scale' => 0],'ugc/answer.list');
        }
        else
        {
            $result = $this->format_answer($answer,'','');
            $correct_num = $answer['correct_num'];
            if($correct_num > 0)
            {
                $lt_count = $mod_answer->lt_count($special_id,$correct_num);
                $counts   = $mod_answer->counts($special_id);
                if($lt_count > 0 && $counts > 0) {
                    $scale = intval($lt_count * 100 / $counts + 0.5);
                } else {
                    $scale = false;
                }

            } else {
                $scale = false;
            }

            return self::outsuccess(['answer' => $result,'special_id' => $special_id,'scale' => $scale],'ugc/answer.list');
        }
    }

    private function format_answer($answer,$nickname,$avatar)
    {
        $result['correct_num'] = intval($answer['correct_num']);
        $result['total_num']   = intval($answer['total_num']);
        if($result['total_num'] == 0) {
            $result['score'] = 0;
        }
        else {
            $result['score']  = intval($result['correct_num'] * 100 / $result['total_num'] + 0.5);
        }
        $result['bonus_rate'] = intval($answer['bonus_rate']);
        $result['amount']     = doubleval($answer['amount']);
        $result['answer_time']= intval($answer['answer_time']);
        $result['nickname']   = $nickname;
        $result['avatar']     = $avatar;

        return $result;
    }

    public function answersOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }
        $mod_answer = Model('ugc_answer');
        $count = $mod_answer->counts($special_id);
        $items = $mod_answer->answer_list($special_id,'*',$this->page_size(),$count);
        $pages = $mod_answer->gettotalpage();

        if(empty($items)) {
            return self::outsuccess(['answers' => [],'mobile_page' => mobile_page(0)]);
        }

        $uids = [];
        foreach ($items as $val) {
            $user_id = intval($val['member_id']);
            $uids[] = $user_id;
        }
        $minfos = $this->users($uids);
        $members = [];
        foreach ($minfos as $val) {
            $mid = intval($val['member_id']);
            $members[$mid] = $val;
        }

        $answers = [];
        foreach ($items as $item) {
            $mid = intval($item['member_id']);
            $member = $members[$mid];
            $value = $this->format_answer($item,$member['nickname'],$member['avatar']);
            $answers[] = $value;
        }
        return self::outsuccess(['answers' => $answers,'mobile_page' => mobile_page($pages)]);
    }

    public function subscribe_authorOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }
        $memberid = $_SESSION['member_id'];
        $success = ugc_helper::subscribe($memberid,$special_id);
        return self::outsuccess(['success' => $success]);
    }
    public function report_pageOp()
    {
        $special_id = intval($_GET['special_id']);
        if($special_id < 0) {
            return self::outerr(errcode::ErrParamter,"该专题不存在");
        }

        return self::outsuccess(['special_id' => $special_id],'ugc/report');
    }
    public function reportOp()
    {
        $special_id = intval($_GET['special_id']);
        $content = urldecode($_GET['content']);
        if($special_id > 0 && !empty($content)) {
            $content = text_filter::filter_input($content);
            $mod_report = Model();
            $mod_report->table('special_report')->insert(['special_id' => $special_id,'reporter_id' => session_helper::memberid(),'content' => $content]);
        }
        return self::outsuccess([]);
    }
}