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

class Index extends Controller
{
    protected $config;
    protected $modelid;
    protected $cid;
    protected $userid;
    protected $data;
    protected function initialize()
    {
        parent::initialize();
        $this->isInstall();
        if(!Request::isPost()) abort(404,lang('content_error'));
        $this->config = get_addons_config('favorite',true);
        if(!session('?userid')) $this->error($this->config['unlogin']);
        $this->userid = session('userid');
        // 判断参数
        $this->modelid = Request::post('modelid');
        $this->cid = Request::post('cid');
        if(empty($this->modelid) || empty($this->cid)) $this->error($this->config['showerror']);
        $this->data = ['cmsmodels_id'=>$this->modelid,'cid'=>$this->cid,'user_id'=>$this->userid];
    }

    public function index()
    {
        $has = Db::name('favorite')->where($this->data)->find();
        if(!$has) {
            $result = Db::name('favorite')->strict(false)->insert(array_merge($this->data,['create_time'=>time()]));
            $msg = $this->config['smsg'];
            if($result) {
                $this->success($msg);
            } else {
                $this->error('系统错误');
            }
        }
        $this->error('该收藏已存在');
        
    }

    public function del()
    {
        $result = Db::name('favorite')->where($this->data)->delete();
        if($result) {
            $this->success();
        } else {
            $this->error();
        }
    }
}