<?php
/**
 * Created by PhpStorm.
 * User: songlintao
 * Date: 2017/9/25
 * Time: 下午3:30
 */
defined( 'InShopNC' ) or exit( 'Access Invalid!' );

require_once(BASE_ROOT_PATH . '/helper/session_helper.php');

use user_session\storage;

class festvalControl extends mobileControl
{
    const RELATIVE_UPLOAD = "/upfile";
    const UPFILE_PATH = BASE_UPLOAD_PATH . self::RELATIVE_UPLOAD;
    private $mod_activity_image;

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

	public function indexOp()
    {
        $this->topup();
        $url = BASE_SITE_URL . "/hfive/festval/index.html";
        if(session_helper::need_wechat_author())
        {
            $author = new thrid_author\wxauthor();
            $url = $author->enter($url);
        }

        return self::outsuccess(['direct_uri' => $url],"redirect");
    }

	private function from_base64($base_input, &$file_name)
    {
        if(empty($base_input)) {
            return false;
        }

        $regx = '/^(data:\s*image\/(\w+);base64,)/';
        if (preg_match($regx, $base_input, $result))
        {
            $file_type = $result[2];
            $content = str_replace( $result[1], '', $base_input);
            $file_name = md5($content) .'.'. $file_type;
            return base64_decode($content);
        } else {
            return false;
        }
    }


	function add_imageOp()
    {
		$image_content = $this->from_base64($_POST['image_data'],$file_name);
		$act_id = intval($_POST['act_id']);

		if ($image_content == false || $act_id <= 0) {
			return self::outerr( errcode::ErrParamter, "参数错误", "festval/error" );
		}
		$file_path = self::UPFILE_PATH . "/{$file_name}";
        if(file_put_contents($file_path,$image_content) == false) {
            return self::outerr( errcode::ErrParamter, "保存文件失败", "festval/error" );
        }

        $datas = [];
        {
            if(session_helper::logined()) {
                $datas['member_id'] = session_helper::memberid();
            } else {
                $datas['member_id'] = 0;
            }

            if(session_helper::unionid() != false) {
                $datas['unionid'] = session_helper::unionid();
            } else {
                $datas['unionid'] = "";
            }
            $datas['act_id']     = $act_id;
            $datas['image_path'] = self::RELATIVE_UPLOAD . "/" . $file_name;
            $datas['add_time']   = time();
            $datas['likes']      = 0;
        }
        $ret = $this->mod_activity_image->insert($datas);
        if($ret > 0) {
            return self::outsuccess(null);
        } else {
            return self::outerr( errcode::ErrParamter, "保存文件失败", "festval/error" );
        }
	}

	function likeOp()
    {
        $act_id   = $_GET['act_id'];
		$image_id = $_GET['image_id'];

        if($act_id < 0 || $image_id < 0) {
            return self::outerr(errcode::ErrParamter,"参数错误");
        }

        $supporter = new festval_support($act_id,$image_id);
        if($supporter->supported()) {
            $supporter->unsupport();
            $supported = false;
        } else {
            $supporter->support();
            $supported = true;
        }

        $ret = $this->mod_activity_image->likes($image_id,true);
        return self::outsuccess(['supported' => $supported,'likes' => intval($ret['likes'])]);
	}

	function listOp()
    {
        $act_id = intval($_POST['act_id']);
        if ($act_id <= 0) {
            return self::outerr( errcode::ErrParamter, "参数错误", "festval/error" );
        }
        $items = $this->mod_activity_image->image_list(['act_id' => $act_id],'*',$this->page_size());
        $pages = $this->mod_activity_image->gettotalpage();

        $result = [];
        foreach ($items as $item) {
            $result[] = $this->format($item);
        }
		return self::outsuccess(['blocks' => $result,'mobile_page' => mobile_page($pages)]);
	}

	private function format($item)
    {
        $result = [];
        $image_id = intval($item['image_id']);
        $act_id   = intval($item['act_id']);

        $result['image_id'] = $image_id;
        $supporter = new festval_support($act_id,$image_id);
        $result['supported'] = $supporter->supported();
        $result['act_id'] = $item['act_id'];
        $result['member_id'] = $item['member_id'];
        $result['image'] = $this->img_url($item['image_path']);

        $result['likes'] = intval($item['likes']);
        $result['add_time'] = intval($item['add_time']);

        return $result;
    }

    private function img_url($path)
    {
        if(strncasecmp($path,"http://",strlen("http://")) == 0) {
            $url = $path;
        } else {
            $url = UPLOAD_SITE_URL . $path;
        }
        return $url;
    }
    private function topup()
    {
        if(session_helper::logined()) {
            $pred = new predeposit_helper($_SESSION['member_id']);
            $pred->topup_bonus($_SESSION['member_mobile']);
        }
    }
}

class festval_support extends storage
{
    private $act_id;
    private $image_id;

    public function __construct($act_id, $image_id)
    {
        $this->act_id = intval($act_id);
        $this->image_id = intval($image_id);
        parent::__construct();
    }

    public function is_act() {
        return ($this->act_id > 0 && $this->image_id <= 0);
    }

    public function limit_type()
    {
        return storage::NORMAL_SUPPORT;
    }
    public function storage_tag()
    {
        if($this->is_act()) {
            return "festval_support";
        } else {
            return "festval_image_{$this->act_id}";
        }
    }
    public function supported()
    {
        if($this->is_act()) {
            return parent::base_supported($this->act_id);
        } else {
            return parent::base_supported($this->image_id);
        }
    }
    public function support()
    {
        if($this->is_act())
        {
            $ret = parent::base_support($this->act_id);
            if($ret) {
                $this->add_act_likes();
            }
        }
        else
        {
            $ret = parent::base_support($this->image_id);
            if($ret) {
                $this->add_image_likes();
            }
        }
        return $ret;
    }
    public function unsupport()
    {
        if($this->is_act())
        {
            $ret = parent::base_unsupport($this->act_id);
            if($ret) {
                $this->sub_act_likes();
            }
        }
        else
        {
            $ret = parent::base_unsupport($this->image_id);
            if($ret) {
                $this->sub_image_likes();
            }
        }
        return $ret;
    }

    private function add_act_likes()
    {

    }
    private function sub_act_likes()
    {

    }
    private function add_image_likes()
    {
        $mod_image = Model('activity_image');
        $mod_image->where(['image_id' => $this->image_id])->update([ 'likes' => ['exp', 'likes + 1'] ]);
    }
    private function sub_image_likes()
    {
        $mod_image = Model('activity_image');
        $mod_image->where(['image_id' => $this->image_id])->update([ 'likes' => ['exp', 'likes - 1'] ]);
    }
}