<?php

namespace Forum\Src;

use Dever;

class Vote
{
    public function __construct()
    {
        $this->id = Dever::input('id');
        $this->table = Dever::input('table');
    }

    public function _token($id = false)
    {
        $token['id'] = $id ? $id : $this->id;
        $token['table'] = 1;

        return http_build_query(Dever::token($token));
    }

    public function _url()
    {
        return Dever::proxy('forum/vote.save', $this->_token());
    }

    public function save()
    {
        # 检测是否登录
        $user = Dever::load('passport/user.data');
        if (!$user) {
            Dever::alert('请先登录');
        }

        $param['option_source_table'] = $this->table;
        $param['option_source_id'] = $this->id;
        $param['option_uid'] = $user['id'];

        if (!$param['option_source_table']) {
            Dever::alert('请选择来源');
        }

        if (!$param['option_source_id']) {
            Dever::alert('请选择来源');
        }

        if ($param['option_source_table'] == 1) {
            $table = 'posts';
        } elseif ($param['option_source_table'] == 2) {
            $table = 'review';
        }

        $check = Dever::load('forum/' . $table . '-one', $param['option_source_id']);
        if (!$check) {
            Dever::alert('请选择来源');
        }

        $info = Dever::load('forum/vote-one', $param);

        if ($info) {
            $param['set_state'] = $info['state'] == 1 ? 2 : 1;
            $id = $param['where_id'] = $info['id'];

            $state = Dever::load('forum/vote-update', $param);

            if ($state && $param['set_state'] == 1) {
                Dever::load('forum/' . $table . '-addUp', array('where_id' => $param['option_source_id']));
            } elseif ($state && $param['set_state'] == 2) {
                Dever::load('forum/' . $table . '-desUp', array('where_id' => $param['option_source_id']));
            }

            Dever::out($param['set_state']);
        } else {
            $param['add_source_table'] = $param['option_source_table'];
            $param['add_source_id'] = $param['option_source_id'];
            $param['add_uid'] = $user['id'];
            $param['add_state'] = 1;
            $param['add_ip'] = Dever::ip();

            $id = Dever::load('forum/vote-insert', $param);

            if ($id > 0) {
                Dever::load('forum/' . $table . '-addUp', array('where_id' => $param['option_source_id']));
            }

            Dever::out(1);
        }
    }
}
