<?php
namespace addons\mylike\controller;
use think\addons\Controller;
use app\common\model\Cmsmodels;
use Request;
use Db;

class Index extends Controller
{
    protected $config;
    protected $ip;
    protected $modelid;
    protected $cid;
    protected $action;
    protected $userid;
    protected $likeList;
    protected $data;
    protected function initialize()
    {
        parent::initialize();
        $this->isInstall();
        if(!Request::isPost()) abort(404,lang('content_error'));
        $this->config = get_addons_config('mylike',true);
        // dump($this->config);
        // 判断是否开启会员
        if($this->config['isuser'] && !session('?userid')) $this->error($this->config['unlogin']);
        $this->userid = session('?userid') ? session('userid') : 0;
        // 获取IP
        $this->ip = Request::ip();
        // 判断参数
        $this->modelid = Request::post('modelid');
        $this->cid = Request::post('cid');
        if(empty($this->modelid) || empty($this->cid)) $this->error($this->config['showerror']);
        // 判断允许赞踩次数以及时间间隔
        $this->likeList = Db::name('mylike')->where(['cmsmodels_id'=>$this->modelid,'cid'=>$this->cid,'ip'=>$this->ip])->fetchCollection()->select();
        $count = $this->likeList->count();
        if(!$this->config['isrepeat']) {
            if($count>0) $this->error($this->config['repeatmsg']);
        } else {
            if($count>0) {
                $lstime = max(array_values($this->likeList->column('create_time')));
                if(time()-$lstime < intval($this->config['intime'])*60) $this->error($this->config['repeatmsg']);
            }
        }
        $this->data = ['cmsmodels_id'=>$this->modelid,'cid'=>$this->cid,'ip'=>$this->ip,'create_time'=>time(),'user_id'=>$this->userid];
    }

    public function islike()
    {
        if($this->config['onlyone'] && $this->likeList->where('islike','=',0)->count()>0) $this->error($this->config['onlyonemsg']);
        $this->data['islike'] = 1;
        $result = Db::name('mylike')->strict(false)->insert($this->data);
        if($result) {
            $this->success(Db::name('mylike')->where(['cmsmodels_id'=>$this->modelid,'cid'=>$this->cid,'ip'=>$this->ip,'islike'=>1])->count());
        }
    }

    public function dislike()
    {
        if($this->config['onlyone'] && $this->likeList->where('islike','=',1)->count()>0) $this->error($this->config['onlyonemsg']);
        $this->data['islike'] = 0;
        $result = Db::name('mylike')->strict(false)->insert($this->data);
        if($result) {
            $this->success(Db::name('mylike')->where(['cmsmodels_id'=>$this->modelid,'cid'=>$this->cid,'ip'=>$this->ip,'islike'=>0])->count());
        }
    }
}