<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/6/9
 * Time: 上午11:57
 */

require_once (BASE_ROOT_PATH . '/helper/algorithm.php');
require_once (BASE_ROOT_PATH . '/helper/login_helper.php');
require_once (BASE_ROOT_PATH . '/helper/session_helper.php');
require_once (BASE_ROOT_PATH . '/helper/sms_helper.php');

class inoherbControl extends mobileControl
{
    private $mModInoherb;

    public function __construct()
    {
        parent::__construct();
        $this->mModInoherb = Model('inoherb');
    }

    public function indexOp()
    {
        $inoherb_id = intval($_GET['inoherb_id']);
        if($inoherb_id > 0) {
            $url = "http://p.lrlz.com/hfive/inoherb/index.html?#/share?inoherb_id={$inoherb_id}";
        }
        else {
            $url = "http://p.lrlz.com/hfive/inoherb/index.html?2";
        }
        return self::outsuccess(['direct_uri' => $url],"redirect");
    }

    public function listOp()
    {
        $items = $this->items($this->page_size(),false);
        $count = $this->mModInoherb->gettotalpage();
        if(empty($items)) {
            return self::outsuccess(['articles' => null,
                'mobile_page' => mobile_page(0)]);
        } else {
            $articles = $this->format($items);
            return self::outsuccess(['articles' => $articles,
                'mobile_page' => mobile_page($count)]);
        }
    }
    public function addOp()
    {
        $content = $_GET['content'];
        if(empty($content)) {
            return self::outerr(errcode::ErrParamter,"填写的内容不能为空.");
        }
        $flower_type = intval($_GET['flower_type']);

        $url = BASE_SITE_URL . "/mobile/index.php?act=inoherb&op=add&content={$content}&flower_type={$flower_type}";
        if(session_helper::need_wechat_author())
        {
            $author = new thrid_author\wxauthor();
            $url = $author->enter($url);
            return self::outsuccess(['direct_uri' => $url],"redirect");
        }

        $content = urldecode($content);
        $trans = new trans_wapper($this->mModInoherb,__METHOD__);
        try
        {
            if(!$this->exists())
            {
                $flower_type = intval($_GET['flower_type']);
                $data['content'] = $content;
                $data['flower_type'] = $flower_type;
                $data['unionid'] = session_helper::unionid();
                $data['content'] = $content;
                $data['likes'] = 0;
                $data['avatar'] = session_helper::avatar();
                $data['nickname'] = session_helper::nickname();

                if(session_helper::logined()) {
                    $data['member_id'] = session_helper::memberid();
                    $data['mobile'] = session_helper::cur_mobile();
                } else {
                    $data['member_id'] = 0;
                }
                $this->mModInoherb->insert($data);
            }
            else
            {
                $data['content'] = $content;
                $this->mModInoherb->where(['unionid' => session_helper::unionid()])->update($data);
            }

            $trans->commit();
        } catch (Exception $ex) {
            $trans->rollback();
        }

        return self::outsuccess(null);
    }

    public function supportOp()
    {
        $inoherb_id = intval($_GET['inoherb_id']);
        if($inoherb_id < 0) {
            return self::outerr(errcode::ErrParamter,'错误的文章序列号.');
        }

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

        return self::outsuccess(['likes' => $supports,'supported' => $supported,'inoherb_id' => $inoherb_id]);
    }

    private function supported($inoherb_id)
    {
        $time = strtotime(date('Y-m-d',time()));
        if(!isset($_SESSION['inoherb'])) {
            $_SESSION['inoherb'] = [];
        }
        if(!isset($_SESSION['inoherb'][$time])) {
            $_SESSION['inoherb'][$time] = [];
        }

        $inoherb = &$_SESSION['inoherb'][$time];
        if(algorithm::binary_search($inoherb,$inoherb_id)) {
            return true;
        } else {
            return false;
        }
    }

    private function support($inoherb_id)
    {
        $time = strtotime(date('Y-m-d',time()));
        if(!isset($_SESSION['inoherb'])) {
            $_SESSION['inoherb'] = [];
        }
        if(!isset($_SESSION['inoherb'][$time])) {
            $_SESSION['inoherb'][$time] = [];
        }

        $inoherb = &$_SESSION['inoherb'][$time];
        if(algorithm::binary_search($inoherb,$inoherb_id) == false) {
            $pos = algorithm::lower_bonud($inoherb,$inoherb_id);
            algorithm::array_insert($inoherb,$pos,$inoherb_id);
            $ret = $this->mModInoherb->where(['inoherb_id' => $inoherb_id])->update(['likes' => ['exp', 'likes + 1']]);
        }
        return $this->likes($inoherb_id);
    }

    private function unsupport($inoherb_id)
    {
        $time = strtotime(date('Y-m-d',time()));
        if(!isset($_SESSION['inoherb'])) {
            $_SESSION['inoherb'] = [];
        }
        if(!isset($_SESSION['inoherb'][$time])) {
            $_SESSION['inoherb'][$time] = [];
        }

        $inoherb = &$_SESSION['inoherb'][$time];
        if(algorithm::binary_search($inoherb,$inoherb_id) == true) {
            $pos = algorithm::lower_bonud($inoherb,$inoherb_id);
            algorithm::array_erase($inoherb,$pos);
            $ret = $this->mModInoherb->where(['inoherb_id' => $inoherb_id])->update(['likes' => ['exp', 'likes - 1']]);
        }

        return $this->likes($inoherb_id);
    }

    public function mineOp()
    {
        $inoherb_id = intval($_GET['inoherb_id']);
        if($inoherb_id < 0) {
            return self::outerr(errcode::ErrParamter,'错误的文章序列号.');
        }
        if(empty(session_helper::unionid()))
        {
            return self::outsuccess(['articles' => null,
                'mobile_page' => mobile_page(0)]);
        }

        $item = $this->item(['unionid' => session_helper::unionid()],true);
        if(empty($item)) {
            return self::outsuccess(['articles' => null,
                'mobile_page' => mobile_page(0)]);
        }
        else
        {
            $articles = $this->format($item);
            return self::outsuccess(['articles' => $articles,
                'mobile_page' => mobile_page(1)]);
        }
    }

    public function infoOp()
    {
        $inoherb_id = intval($_GET['inoherb_id']);
        if($inoherb_id < 0) {
            return self::outerr(errcode::ErrParamter,'错误的文章序列号.');
        }
        $item = $this->item(['inoherb_id' => $inoherb_id]);

        if(empty($item)) {
            return self::outsuccess(['articles' => null, 'mobile_page' => mobile_page(0)]);
        } else {
            $articles = $this->format($item);
            return self::outsuccess(['articles' => $articles, 'mobile_page' => mobile_page(1)]);
        }
    }

    public function loginedOp()
    {
        $logined = session_helper::logined();
        return self::outsuccess(['logined' => $logined]);
    }

    public function bindOp()
    {
        $mobile = $_GET['mobile'];
        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrParamter, $err);
        }

        if(!isset($_GET['code']) || empty($_GET['code'])) {
            return self::outerr(errcode::ErrParamter, "请输入验证码.");
        }
        $code = $_GET['code'];
        $ret = sms_helper::check_code(Sms::getbonus_code,$code,$mobile);

        if(is_array($ret)) {
            return self::outerr($ret['code'], $ret['msg']);
        } else {
            login_helper::onBinded($mobile,$code,session_helper::relay_id());
            $member_id = session_helper::memberid();
            $nickname = session_helper::nickname();

            $this->mModInoherb->where(['unionid' => session_helper::unionid()])->update(['mobile' => $mobile,'member_id' => $member_id,'nickname' => $nickname]);
            return self::outsuccess(null);
        }
    }

    private function exists()
    {
        $unionid = session_helper::unionid();
        if(empty($unionid)) return true;

        $items = $this->mModInoherb->field('*')->where(['unionid' => $unionid])->select();
        if(empty($items)) {
            return false;
        } else {
            return true;
        }
    }

    private function likes($inoherb_id)
    {
        $items = $this->mModInoherb->field('likes')->where(['inoherb_id' => $inoherb_id])->lock(true)->select();
        if(empty($items)) {
            return 0;
        } else {
            return intval($items[0]['likes']);
        }
    }

    private function item($condition,$lock = false)
    {
        return $this->mModInoherb->field('*')->where($condition)->lock($lock)->select();
    }

    private function items($page = 0,$lock = false)
    {
        return $this->mModInoherb->field('*')->order('likes desc,inoherb_id desc')->page($page)->lock($lock)->select();
    }

    private function format($items)
    {
        $result = [];
        foreach ($items as $item)
        {
            $val = [];
            $val['inoherb_id'] = intval($item['inoherb_id']);
            $val['avatar'] = $item['avatar'];
            $val['flower_type'] = intval($item['flower_type']);
            $val['content'] = $item['content'];
            $val['likes'] = $item['likes'];
            $val['supported'] = $this->supported($val['inoherb_id']);
            $val['nickname'] = $item['nickname'];


            $result[] = $val;
        }

        return $result;
    }
}